标签: python-unittest

对于unittest.TestCase子类,当run table执行runcases时无法获取class属性

我想在测试方法中为类属性设置一个值,并在另一个测试方法中使用具有相同类属性的值.当我通过run方法执行测试用例以正常方式尝试时,得到错误AttributeError: 'Unit' object has no attribute 'b'.无论如何,我通过使用global变量和通过将类分配给变量来找到其他解决方案.我可以知道为什么我无法检索我使用其他方法设置相同的类属性的原因吗?另外,你能帮我用run方法解释实际过程......提前谢谢.

这是我尝试的示例代码:

import unittest
class Unit(unittest.TestCase):
    def test_i(self):
        self.b=20
    def test_j(self):
        print self.b


suite=unittest.TestLoader().loadTestsFromTestCase(Unit)
unittest.TextTestRunner(verbosity=2).run(suite)
test_i (__main__.Unit) ... ok
test_j (__main__.Unit) ... ERROR

======================================================================
ERROR: test_j (__main__.Unit)
----------------------------------------------------------------------
Traceback (most recent call last):
File "<pyshell#52>", line 5, in test_j
AttributeError: 'Unit' object has no attribute 'b'

----------------------------------------------------------------------
Ran 2 tests in 0.078s

FAILED (errors=1)
<unittest.runner.TextTestResult run=2 errors=1 failures=0>


    #The two ways which I solved...
    #1.By Assinging …
Run Code Online (Sandbox Code Playgroud)

python unit-testing python-3.x python-unittest

3
推荐指数
1
解决办法
2160
查看次数

在Python中编写Selenium Unittests的正确方法?

我有以下场景:

Load Page A
Check if Element_A exists in Page A
Click Button_A
On Clicking Button_A, Page B is loaded
Check if Element_B exists in Page B and Click Button_B
and so on...
Run Code Online (Sandbox Code Playgroud)

我写了这样的代码:

import unittest
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

class MyWebsiteTest(unittest.TestCase):

    def setUp(self):
        self.driver = webdriver.Firefox()

    def test_element_a_in_page_a(self):
        driver = self.driver
        driver.get(PAGE_A)
        element = driver.get_element_by_id("element_a")
        self.assertIsNotNone(element,"Oops.")

    def load_page_b_if_previous_function_is_true(self):
        #WHAT DO I DO HERE?
        #I Need to run this function given test_element_a_in_page_a succeeds.

    def tearDown(self):
        self.driver.close() …
Run Code Online (Sandbox Code Playgroud)

python selenium unit-testing python-unittest

3
推荐指数
1
解决办法
1774
查看次数

python 3.4 多处理不适用于单元测试

我有一个使用多处理的单元测试。

从 Python 3.2 升级到 Python 3.4 后,出现以下错误。我找不到提示,Python 内部发生了什么变化以及我必须改变什么才能使我的代码运行。

提前致谢。

Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "C:\Python341_64\lib\multiprocessing\spawn.py", line 106, in spawn_main
    exitcode = _main(fd)
  File "C:\Python341_64\lib\multiprocessing\spawn.py", line 116, in _main
    self = pickle.load(from_parent)
EOFError: Ran out of input

Error
Traceback (most recent call last):
  File "D:\test_multiproc.py", line 46, in testSmallWorkflow
    p.start()
  File "C:\Python341_64\lib\multiprocessing\process.py", line 105, in start
    self._popen = self._Popen(self)
  File "C:\Python341_64\lib\multiprocessing\context.py", line 212, in _Popen
    return _default_context.get_context().Process._Popen(process_obj)
  File "C:\Python341_64\lib\multiprocessing\context.py", line 313, in _Popen …
Run Code Online (Sandbox Code Playgroud)

python multiprocessing python-unittest python-3.4

3
推荐指数
1
解决办法
2887
查看次数

我可以使用 Selenium Python 在画布上绘图吗?

我正在尝试为 HTML5 画布应用程序运行自动化测试和基准测试。我已经使用 python-unittest 和 ChromeDriver 设置了 Selenium(尽管我愿意接受其他选择)。

画布应用程序是一个白板,通过单击鼠标并在画布上拖动来绘制线条。如何使用 Selenium 自动绘制简单的形状?我浏览了 python-selenium API,唯一的鼠标移动测试选项是 through ActionChains,但这些都将鼠标移动到基于它们的元素idclass. 我还没有看到根据画布上的坐标自动移动鼠标的方法。

有没有办法实现画布上绘图的自动化测试?

python selenium canvas selenium-webdriver python-unittest

3
推荐指数
1
解决办法
2845
查看次数

assertIsInstance()针对多个类名

我有一个函数应该将对象属性设置为PIL图像实例:

from PIL import Image

class SimpleExample:
    def __init__(self):
        self.img = self.load_image()

    def load_image():
        self.img = Image.open(image)
Run Code Online (Sandbox Code Playgroud)

为了测试load_image()的正确执行,我想使用unittest.TestCase.assertIsInstance(),但是对结果实例的内省给出了一个不同的.名称取决于加载的图像的文件类型.我在unittest 中找不到assertIsInstanceFromModule()的任何内容,所以这似乎是最能反映我真正想要测试的断言助手.

我想出了几个解决方案,但对其中任何一个都不满意:

使用循环 生成所有可能类名的列表,迭代列表,测试每个成员是否相等,然后使用assertIsInstance作为相应的列表成员.这是尴尬的,单声道的,我当然不会为此感到骄傲.它确实有效,它使用我认为最有意义的断言.

simplified_names = ['JpegImageFile', 'PngImageFile']
for i, name in enumerate(simplified_names):
    if SimpleExample.img.__class__.__name__ == name:
        TestCase.assertIsInstance(SimpleExample.img, simplified_names[i])
Run Code Online (Sandbox Code Playgroud)

使用不同的断言助手 生成所有可能的类名列表,并声明生成的对象的类名在该列表中.它很有用,很简单,但我不喜欢我实际上在这里断言的内容.

simplified_names = ['JpegImageFile', 'PngImageFile']
TestCase.assertIn(SimpleExample.img.__class__.__name__, simplified_names)
Run Code Online (Sandbox Code Playgroud)

有没有人对如何断言多个可能的类名有任何其他想法?我是否应该从不同的方向接近测试并使用不同的断言?这是我第一次涉足unittest.我应该回去只用print来测试我的代码吗?

~~~~~明显的答案是......

测试父类.或者,我可以注意到每次看到以下错误时都会向我提出更好的选项:

TypeError: isinstance() arg 2 must be a type or tuple of types
Run Code Online (Sandbox Code Playgroud)

强调"或元组".

感谢Martijn Pieters的所有帮助.

python unit-testing python-3.x python-unittest

3
推荐指数
1
解决办法
7621
查看次数

Unittest 因 sys.exit 而失败

我正在尝试使用 unittest 运行我的测试。这是我的结构:

projectname/
    projectname/
        foo.py
        bar.py
    tests/
        test_foo.py
        test_bar.py
Run Code Online (Sandbox Code Playgroud)

我运行它:

cd tests/
python -m unittest discover
Run Code Online (Sandbox Code Playgroud)

但是在一个文件中,例如foo.py,我使用了 a sys.exit(0),而 unittest 并不喜欢它:

$ python -m unittest discover
....E.
======================================================================
ERROR: test_foo (...)
----------------------------------------------------------------------
Traceback (most recent call last):
...
...
File "/home/.../projectname/foo.py", line 12, in write
    sys.exit(0)
SystemExit: 0

----------------------------------------------------------------------
Ran 6 tests in 0.018s

FAILED (errors=1)
Run Code Online (Sandbox Code Playgroud)

sys.exit()使用是自愿的,我无法将其删除。我知道有一个调用exitunittest.main 函数的选项:

if __name__ == "__main__":
    unittest.main(exit=False)
Run Code Online (Sandbox Code Playgroud)

但是我想测试tests目录中的所有文件。另一种方法是:

if __name__ == '__main__':
    tests = …
Run Code Online (Sandbox Code Playgroud)

python unit-testing python-unittest

3
推荐指数
1
解决办法
2610
查看次数

如何更改模拟 obj 的返回值?

我有课

import pandas as pd

class foo(object):
   def __init__(self):
      self.info = pd.DataFrame()

   def getData(self):
      self.__readCSV()

   def __readCSV(self):
      self.info = pd.read_csv(self.filename)
Run Code Online (Sandbox Code Playgroud)

我有一个单元测试类

class test(unittest.TestCase):
   def test(self):
      mock = patch('foo.pandas.read_csv')
      foo().getData()

      ...
Run Code Online (Sandbox Code Playgroud)

如何更改pd.read_csv(self.filename)返回值DataFrame({'column1': Series([1., 2., 3.]),'column2': Series([4., 5., 6.])})以测试是否self.info已分配assertEqual

python unit-testing pandas python-unittest

3
推荐指数
1
解决办法
4273
查看次数

Python unittest继承setUp覆盖

import unittest

class A(unittest.TestCase):
    def setUp(self):
        print "Hi it's you",self._testMethodName

    def test_one(self):
        self.assertEqual(5,5)

    def tearDown(self):
        print "Bye it's you", self._testMethodName

class B(A,unittest.TestCase): 

    def setUp(self):
        print "Hi it's me", self._testMethodName

    def test_two(self):
        self.assertNotEqual(5,5)


unittest.main()
Run Code Online (Sandbox Code Playgroud)

输出 :

Hi it's you test_one
Bye it's you test_one
.Hi it's me test_one
Bye it's you test_one
.Hi it's me test_two
FBye it's you test_two

======================================================================
FAIL: test_two (__main__.B)
----------------------------------------------------------------------

Traceback (most recent call last):
  File "try_test_generators.py", line 19, in test_two
    self.assertNotEqual(5,5)
AssertionError: 5 == 5 …
Run Code Online (Sandbox Code Playgroud)

python python-unittest

3
推荐指数
1
解决办法
3714
查看次数

在django中使用python unittest运行特定的测试用例

我有一组可以成功运行的单元测试: ./runtests.py wagtail.wagtailcore.tests

我也可以运行:

./runtests.py wagtail.wagtailcore.tests.test_page_privacy
Run Code Online (Sandbox Code Playgroud)

但是,如果我只想执行其中一个,我会收到一个错误 'module' object has no attribute [test_case_name]

我的课将是这样的:

class TestPagePrivacy(TestCase):
  def test_anonymous_user_must_authenticate(self):
Run Code Online (Sandbox Code Playgroud)

所以我认为你可以这样说: ./runtests.py wagtail.wagtailcore.tests.test_page_privacy.test_anonymous_user_must_authenticate

为什么这不起作用?

来自django文档:

https://docs.djangoproject.com/en/1.11/topics/testing/overview/#running-tests

# Run just one test method
$ ./manage.py test animals.tests.AnimalTestCase.test_animals_can_speak
Run Code Online (Sandbox Code Playgroud)

python django unit-testing python-unittest wagtail

3
推荐指数
1
解决办法
1027
查看次数

Python 3:unittest.mock如何为特定输入指定不同的返回值?

假设我有一个模拟对象(让它成为Mock或MagicMock).我想模拟其中一个方法为特定输入返回一个值,并为另一个特定输入返回另一个值.如何在不必关心输入发送到方法的顺序的情况下执行此操作?

伪代码:

def test_blah():
    o = MagicMock()

    # How to do I these?
    o.foo.return_value.on(1) = 10
    o.foo.return_value.on(2) = 20

    assert o.foo(2) == 20
    assert o.foo(1) == 10
Run Code Online (Sandbox Code Playgroud)

python mocking python-3.x python-unittest

3
推荐指数
1
解决办法
862
查看次数