rai
rai

Reputation: 229

Flask Unittest - Type Error because of NoneType argument

I tried to test my code using unittest, where a variable is stored somewhere in a file and accessed using os.getenv

settings.py

     import os
     TARGET_VAR = os.getenv('TARGET_VAR_VALUE')

some apiclass

     from settings import TARGET_VAR
     class someApi:
         def __init__(self):
                print(TARGET_VAR) // good if running normally
     ....rest of func

test

   def test_extreme_devices(self):
      app = Flask(__name__)
      app.config["LOGIN_DISABLED"] = True


      api = flask_restful.Api(app)

      api.add_resource('someApi', '/devices/')

      with app.test_client() as client:
         res = client.get('/devices/')

         self.assertEqual(res.status_code, 200)

.env

 TARGET_VAR_VALUE='some target value'

This is running good but not when running test I am confused when running test for testing the someApi class, I got the error

     TypeError: int() argument must be a string, a bytes-like object or a number, not 
     'NoneType'

obviously for the TARGET_VAR is NoneType, even if its value is set in .env

It will work if I add the actual value directly to it

   TARGET_VAR = 'actual value'

This issue is only on unittest, but not when flask is running and accessing the route(like postman)

Upvotes: 0

Views: 347

Answers (1)

s3bw
s3bw

Reputation: 3049

It could be that when you are running the flask app locally the environment already has TARGET_VAR_VALUE loading into the os environment.

If you use something like python-dotenv when running your unittests, you can ensure there's a consistent environment. Just by specifying the correct .env file to use and ensuring it overrides any other env vars:

from dotenv import load_dotenv

load_dotenv("tests/test.env", override=True)

tests/test.env

TARGET_VAR_VALUE='some target value'

Upvotes: 1

Related Questions