首页 > 解决方案 > 如何将参数从模块传递到单元测试模块?

问题描述

我有 2 个文件:

test_1.py:

import unittest

class TestMe(unittest.TestCase):

   @classmethod
   def setUpClass(cls):
       cls.name = "test"
       cls.password = "1234"

   def test_upper(self):
       self.assertEqual('foo'.upper(), 'FOO')

   def test_user_pass(self):
       print(self.name)
       print(self.password)


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

test_2.py:

import unittest
import test_1
import sys

a = sys.argv

if a[1] == '2':
    suite=unittest.TestLoader().loadTestsFromModule(test_1)
    unittest.TextTestRunner(verbosity=2).run(suite)

我想将参数传递给 test_1(unittes 模块),但我需要将此参数传递给 setUpClass。我怎样才能做到这一点?

谢谢!!!

标签: python

解决方案


尝试这个...

test_1.py:

import unittest
from test_2 import b


class TestMe(unittest.TestCase):

    e = b

    @classmethod
    def setUpClass(cls):
        cls.name = "test"
        cls.password = "1234"
        cls.parameter = cls.e

    def test_upper(self):
        self.assertEqual('foo'.upper(), 'FOO')

    def test_user_pass(self):
        print(self.name)
        print(self.password)
        print(self.parameter)


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

test_2.py:

import unittest
import test_1
import sys

a = sys.argv
b = ""

if a[1] == '2':
    b = a[1]
    suite = unittest.TestLoader().loadTestsFromModule(test_1)
    unittest.TextTestRunner(verbosity=2).run(suite)

我希望这能帮到您。


推荐阅读