rookiE
rookiE

Reputation: 101

pytest: How to set global variable values in pytest test function

app.py below, running env = python 3.8

import argParse
    
#set global var 
ARGS = None
#a json data will be copied into CFG
CFG=None
# global var
PATTERN = re.compile(r'(\d{6})')

def parseCmdLineArgs():
      global ARGS
      ARGS = parser.parse_args(ARGV)
      #ARGS.arg1_value is a string
      #ARGS.arg2_val_is_jsonfile 
      CFG = json.loads(ARGS.arg2_val_is_jsonfile) #CFG["maxLen"] =100 is set

def some_func():
    msg=scan(PATTERN,CFG["maxLen"], ARGS.arg1_value)

pytest test_app.py:

import app
from app import some_func
def test_some_func():
    some_func() 
  

Question: above test_some_func() fails. How to set the global variable's (CFG, PATTERN )value from here ?

Upvotes: 0

Views: 2144

Answers (1)

chepner
chepner

Reputation: 532303

some_func uses CFG defined in its own global scope. You need to provide a value if you aren't calling app.parseCmdLineArgs to set its value.

import app
from app import some_func


app.CFG = {'maxlen': 100}  # for example

def test_some_func():
    some_func()

Upvotes: 1

Related Questions