Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mock.patch.dict at class level - python unit test

I have a dictionary which looks like this and is needed needed by all methods in the test class, is there a way to @mock.patch.dict it at class level rather than doing it at top of each method. The dictionary is set some os.environ variables as shown here:

@mock.patch.dict('os.environ',
                 {'MSSQL_DB_NAME': 'tempdb', 
                  'MSSQL_USERNAME': 'sa', 
                  'MSSQL_PASSWORD': 'password',
                  'MSSQL_DSN': 'MYMSSQL'})
@mock.patch("commonutils.connectors.mssql.pyodbc")
def test_connectivity(self, my_pyodbc):
    self.db = Database(os.environ['MSSQL_DB_NAME'], 
                       os.environ['MSSQL_DSN'], 
                       os.environ['MSSQL_USERNAME'],
                       os.environ['MSSQL_PASSWORD'])
like image 206
Toseef Zafar Avatar asked Oct 23 '18 08:10

Toseef Zafar


1 Answers

You can use @mock.patch.dict decorator at your TestCases class level:

import unittest
import unittest.mock
import os


@unittest.mock.patch.dict('os.environ', { 'VAR': '1' })
class MyTestCase1(unittest.TestCase):

    def test_feature_one(self):
        self.assertEqual(os.environ['VAR'], '1')

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

or, if you use setUp, you can patch it in setUp:

import unittest
import unittest.mock
import os


class MyTestCase1(unittest.TestCase):

    @unittest.mock.patch.dict('os.environ', { 'VAR': '1' })
    def setUp(self):
        print(os.environ['VAR'])
like image 120
akloboucnik Avatar answered Nov 15 '22 03:11

akloboucnik