Home > Software engineering >  Import python file to our unit test cases with popen variable
Import python file to our unit test cases with popen variable

Time:12-06

Objective : To Create UnitTestCases for main.py How can we import another python file which will dynamically return result

File : main.py

import os
_ENV = os.popen("echo ${RPM_ENVIRONMENT}").read().split('\n')[0]
_HOST = os.popen("echo $(hostname)").read().split('\n')[0]
_JOB_TYPE=os.popen("echo ${JOB_TYPE}").read().split('\n')[0]

SERVER_URL = {
    'DEV':{'ENV_URL':'https://dev.net'},
    'UAT':{'ENV_URL':'https://uat.net'},
    'PROD':{'ENV_URL':'https://prod.net'}
}[_ENV]
  1. Import another python file to our testing script
  2. when i import main.py , i will receive error on SERVER_URL = { KeyError '${RPM_ENVIRONMENT}'
  3. I believe the only reason why its returning error is because it does not recognize RPM_ENVIRONMENT, how can we mock _ENV variables in our main file and print server url as https://dev.net
  4. After i have succesfully import main.py in my test case file, then i will create my unitTest cases as the ENV variable is required for me.

Testing : test_main.py

import unittest, sys
from unittest import mock

# --> Error 
sys.path.insert(1, 'C:/home/src')
import main.py as conf

# For an example : we should be able to print https://dev.net when we include this in our line 
URL = conf.SERVER_URL.get('ENV_URL')
ENV =  conf._ENV 

#URL should return https://dev.net & ENV should return DEV


class test_tbrp_case(unittest.TestCase):
    def  test_port(self):
        #function yet to be created
        pass

if __name__=='__main__':
    unittest.main()

CodePudding user response:

There's little reason to shell out of Python. You can read an environment variable with os.environ. os.environ['RPM_ENVIRONMENT'].

import os
_ENV = os.environ['RPM_ENVIRONMENT']
SERVER_URL = {
    'DEV':{'ENV_URL':'https://dev.net'},
    'UAT':{'ENV_URL':'https://uat.net'},
    'PROD':{'ENV_URL':'https://prod.net'}
}[_ENV]

Now your test can set RPM_ENVIRONMENT before importing main.py.

os.environ['RPM_ENVIRONMENT'] = 'UAT'
sys.path.insert(1, 'C:/home/src')
import main.py as conf
  • Related