dimanche 26 novembre 2017

python code testing using unittest module

i have written a code in python 3.3 and which calls two functions. Now i want to write the test cases for this code. First thing i want to check that parameters are passed inside both the functions: main() and second(). Second thing i want to check that both the functions are called or not?

code_file:

import sys

def second(param1, param2):
    content = param1 + " " + param2
    with open("newfile.txt", "w") as fobj:
        fobj.write(content)
    print("[INFO]: File got created.")

def main(param1, param2):
    second(param1, param2)

if __name__ == "__main__":
    if(len(sys.argv) == 3):
        main(sys.argv[1], sys.argv[2])
    else:
        print("[ERROR]: please provide two arguments.")

This code creates a file with the given name.

test_code_file

from code_file import main,second
from mock import patch
import unittest

class pycode_testcase(unittest.TestCase):

    @patch("__main__.second")
    def test_main(self, mock):
        main("Python", "Django")
        self.assertTrue(mock.called)

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

Code is not working. Can anyone help me to resolve this Or suggest me a more appropriate method.

Aucun commentaire:

Enregistrer un commentaire