简体   繁体   中英

Unittest Passing arguments from another script

So here is a pretty simple script im running from an webservice:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import sys

test=int(sys.argv[1])+int(sys.argv[2])
print(test)

and now I want to write an Unittest script to test this script, but I dont know how I should pass the 2 required arguments inside a unittest function. Here is my current code:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import unittest
import ExecuteExternal

class TestUnittest(unittest.TestCase):

    def test(self):
       self.assertTrue(ExecuteExternal, "5", "5"==10)

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

I did search here in the forum but was not able to find an answer

You can wrangle the sys args but the preferred way is to wrap your logic in a function, and put the typical main check around the function call in your script.

Them you can import the script in your unit test and call the function instead of ruining the script.

This is an untested version of your script:

# -*- coding: utf-8 -*-

import sys

def calc(a, b):
    return int(a)+int(b)

if __name__ == "__main__":
    print(calc(sys.argv[1], sys.argv[2]))

assuming your script is called ExecuteExternal.py then your test script goes:

# -*- coding: utf-8 -*-

import unittest
import ExecuteExternal

class TestUnittest(unittest.TestCase):

    def test(self):
        result = ExecuteExternal.calc("5", "6")
        self.assertTrue(result, 11)

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

Furthermore you should watch your naming convention for the script. See PEP8 at https://www.python.org/dev/peps/pep-0008/#package-and-module-names

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM