0

Using tinyDB the application is persisting data to a json file. I need to unittest if certain data is already contained in the database file.

I'm creating an alternate database setup in the setUP method in the variable db. I get the error below. Why is the db variable not available to the namespace in the function that's being tested?

When running the unittest I get:

ERROR: test_contains (__main__.TestDB)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test.py", line 65, in setUp
    print type(db)
NameError: global name 'db' is not defined

Code to test in project/app/sandbox.py

from tinydb import TinyDB, Query
db = TinyDB('db.json')
Check_keyword = Query()

def test_db(keyword):
    if db.contains(Check_keyword.keyword == keyword ):
        print "keyword already in db"
        return True

Unittest in project/test.py

from tinydb import TinyDB, Query
from app.sandbox import test_db



class TestDB(unittest.TestCase):

    def setUp(self):
        self.db = TinyDB('test_db.json')    
        self.Check_keyword = Query()     

    def test_contains(self):
        data = "doctor salarybljkhl"
        result = test_db(data)
        self.assertEqual(result, True)
jdubtd10
  • 105
  • 1
  • 2
  • 9

1 Answers1

1

The db and Check_keyword variables are located in your test class which the code under test has no reference to.

(Also your code under test seems not to use its imports, so best get rid of those).

You should pass the variables needed to the code under test:

sandbox.py

def test_db(db, Check_keyword, keyword):
    if db.contains(Check_keyword.keyword == keyword ):
        print "keyword already in db"
        return True

unittest.py

from tinydb import TinyDB, Query
from app.sandbox import test_db


class TestDB(unittest.TestCase):

    def setUp(self):
        self.db = TinyDB('test_db.json')    
        self.Check_keyword = Query()     

    def test_contains(self):
        data = "doctor salarybljkhl"
        result = test_db(self.db, self.Check_keyword, data)
        self.assertEqual(result, True)
quamrana
  • 37,849
  • 12
  • 53
  • 71
  • thanks for the help mate. This works however I made a mistake in the initial function being tested and didn't show where db instantiation and the query are created. They are the first few lines of the script so they don't need to be passed to the function as they are already in the namespace. The solution you gave requires me to modify the function which shouldn't be necessary as it works in the actual script. I think the purpose of setUp was to set these sort of external function variables. – jdubtd10 Feb 16 '19 at 00:29
  • Well, I hope that you consider changing your existing function so that it doesn't rely on a global variable. Programmers should always try really, really, really hard not to have global variables. – quamrana Feb 16 '19 at 11:00