标签: python-unittest

以编程方式检测 python 代码是否正在测试

python程序如何知道它是否正在被测试?例如:

def foo():
    if foo_being_tested:
        pseudorandom()
    else:
        random()
Run Code Online (Sandbox Code Playgroud)

在测试时,程序应使用伪随机序列,以便能够与程序的 C 代码版本进行比较,并且在常规执行中numpy应使用随机序列。

python unit-testing python-unittest

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

pytest:如果发生崩溃/段错误/等。测试期间发生,有没有办法让 pytest 将崩溃记录为测试失败并继续测试?

我有一些使用 pytest 编写的单元测试,它们成功地导致了段错误的发生。然而,如果在执行期间发生段错误(在我的 Mac 上),pytest 似乎会完全退出,并且不提供有关导致 python 解释器崩溃的原因的信息。

现在我可以从日志中推断出崩溃的特定测试并确定其中使用的值,但我想知道是否有任何方法能够以某种方式将崩溃记录为常规测试失败并继续迭代我的测试而不停止?

如果有帮助,我可以尝试举一个例子,但我认为这个问题应该是不言自明的。

python testing unit-testing pytest python-unittest

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

为什么模拟“open”并返回 FileNotFoundError 会引发 AttributeError: __exit__?

open通过加薪进行FileNotFoundError模拟测试AttributeError: __exit__。为什么会发生这种情况以及我可以采取什么措施来解决它?

以下代码打开一个简单的文本文件。如果文件丢失,它会生成一个默认值。它已经通过定期运行进行了检查,并且看起来运行良好。

so_main.py

import os

import so_config


def load_savelocation():
    path = os.path.join(so_config.ROOT, so_config.SAVELOCATION_FN)
    savelocation_path = os.path.normpath(path)
    try:
        with open(savelocation_path) as f:
            so_config.SAVELOCATION_PATH = f.readline()
    except FileNotFoundError:
        so_config.SAVELOCATION_PATH = so_config.ROOT
Run Code Online (Sandbox Code Playgroud)

so_config.py

import os

ROOT, _ = os.path.split(__file__)
SAVELOCATION_PATH = None
SAVELOCATION_FN = 'savelocation.ini'
Run Code Online (Sandbox Code Playgroud)

单元测试则是另一回事。我嘲笑了open中的命令so.maintest_so_main.py有两项测试:一项用于正常打开存在的文件,第二项用于测试处理FileNotFoundError

常规文件打开的第一次测试test_read_path_from_disk_file_into_config_py工作正常。

FileNotFoundError第二个测试失败,因为AttributeError: __exit__. 我可以设置self.mock_open.return_valueFileNotFoundError或我可以将其设置为'garbage'。这没有什么区别。

测试so_main.py

import unittest
import unittest.mock as mock

import …
Run Code Online (Sandbox Code Playgroud)

mocking python-3.x try-except python-unittest

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

pytest Monkeypatch:每次调用修补方法时是否有可能返回不同的值?

unittest我可以用值断言side_effect可迭代 - 当调用修补方法时,每个值都会一一返回,而且我发现unittest我的修补方法中可以根据输入参数返回不同的结果。我可以在 pytest 中做类似的事情吗?文档没有提到这一点。

python unit-testing pytest python-unittest

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

FileNotFoundError [Errno 2] on os.getcwd()

我收到 FileNotFoundError os.getcwd()

def setUp(self):
    try:
        self.previous_dir=os.getcwd()
    except:
        print("no file?")
    try:
        self.test_dir.mkdir(parents=True, exist_ok=True)
        os.chdir(self.test_dir)
        self.logger.debug(f'CDed to {self.test_dir}')
    except (IOError, TypeError) as ioe:
        self.logger.error(f'Unable to make or CD to {self.test_dir}')                
        sys.exit(1)
Run Code Online (Sandbox Code Playgroud)

self.previous_dir在 tearDown() 中执行 cd并删除临时目录。

它是否试图访问已删除的文件?

python python-3.x python-unittest

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

如何捕获 Python Unittest 测试用例失败的屏幕截图

我使用 Python 3.6.5 和以下库:

  • Appium-Python-客户端==0.26
  • unittest2==1.1.0
  • 硒==3.5.0
  • pytest==3.6.3

现在我需要在测试失败的情况下捕获屏幕截图,所以我故意放了一个错误的陈述 self.driver.find_element_by_css_selector('test')

我正在使用sys.exc_info(). 但是当我使用命令执行以下代码时:py.test untitled.py或者python3 -m unittest untitled.py它没有捕获它。

代码:

import sys, time, unittest2
from selenium import webdriver

class FB360(unittest2.TestCase):
    def setUp(self):
        self.driver = webdriver.Chrome()

    def test_user_can_login(self):
            self.driver.get('https://www.google.co.in')
            self.driver.find_element_by_css_selector('test')

    def tearDown(self):
        print(sys.exc_info())
        if sys.exc_info()[0]:
            test_method_name = self._testMethodName
            self.driver.save_screenshot(test_method_name + str(time.time()) + '.png')
        self.driver.quit()

if __name__ == '__main__':
    unittest2.main()
Run Code Online (Sandbox Code Playgroud)

开/关:

(无,无,无)

================================================== ==================== 错误:test_user_can_login (untitled.FB360)


回溯(最近一次通话):文件“/Volumes/Harry/Projects/pythonScreenshots/untitled.py”,第 11 行,在 test_user_can_login self.driver.find_element_by_css_selector('test') 文件“/Library/Frameworks/Python.framework/ Versions/3.6/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 498, in find_element_by_css_selector …

python pytest selenium-webdriver python-unittest python-3.6

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

单击模块的单元测试

我编写了一个简单的命令行实用程序,它接受一个文本文件并使用 click 模块在其中搜索给定的单词。

sfind.py

import click
@click.command()
@click.option('--name', prompt='Word or string')
@click.option('--filename', default='file.txt', prompt='file name')
@click.option('--param', default=1, prompt="Use 1 for save line and 2 for word, default: ")
def find(name, filename, param):
    """Simple program that find  word or string at text file and put it in new"""
    try:
        with open(filename) as f, open('result.txt', 'w') as f2:
            count = 0
            for line in f:
                if name in line:
                    if param == 1:
                        f2.write(line + '\n')
                    elif param == 2:
                        f2.write(name + …
Run Code Online (Sandbox Code Playgroud)

python python-unittest python-click

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

Python 预提交单元测试失败

我希望pre-commit在提交我的代码之前运行测试。
该命令python -m unittest discover正在命令行中工作。

D:\project_dir>python -m unittest discover
...
...
...
----------------------------------------------------------------------
Ran 5 tests in 6.743s

OK
Run Code Online (Sandbox Code Playgroud)

但是当我尝试提交时,我得到了

D:\project_dir>git commit -m "fix tests with hook"
run tests................................................................Failed
hookid: tests

usage: python.exe -m unittest discover [-h] [-v] [-q] [--locals] [-f] [-c]
                                       [-b] [-k TESTNAMEPATTERNS] [-s START]
                                       [-p PATTERN] [-t TOP]
python.exe -m unittest discover: error: unrecognized arguments: bigpipe_response/processors_manager.py
usage: python.exe -m unittest discover [-h] [-v] [-q] [--locals] [-f] [-c]
                                       [-b] [-k TESTNAMEPATTERNS] [-s START]
                                       [-p …
Run Code Online (Sandbox Code Playgroud)

python git pre-commit-hook python-unittest pre-commit.com

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

如何模拟第三方静态方法

为了简化我的问题,请考虑以下代码:
如何foo1使用修补\模拟S3Downloader.read_file部件编写功能测试?

我更喜欢你向我展示pytest-mock或 的示例用法unitest.mock

from sagemaker.s3 import S3Downloader

class Fooer(object):
    @staticmethod
    def foo1(s3_location):       
        s3_content = S3Downloader.read_file(s3_location)
        return Fooer.foo2(s3_content)


    @staticmethod
    def foo2(s3_content):
       return s3_content +"_end"
Run Code Online (Sandbox Code Playgroud)

pytest python-3.x python-unittest pytest-mock

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

未调用 python 模拟函数

我正在测试 python 代码(一个 django 3.0.5 项目,虽然我认为它不相关),但我无法调用我的模拟对象的函数。这是我的代码:

**myproject.mypackage.myhelpers**


def get_dict():
    return dict()

**myproject.mypackage.mythings**

from .myhelpers import get_dict


def use_dict():
    the_dict = get_dict()
    pass
    return


**myproject.tests.test_mythings**

from ..mypackage import mythings
import unittest
import unittest.mock as mock


class MyThingsTests(unittest.TestCase):

    @mock.patch('myproject.mypackage.myhelpers')
    def test_using_dict(self, mock_myhelpers):
        test_dict = {
            "hi": "foo",
            "there": "bar",
            "sir": "foobar"
        }

        mock_myhelpers.get_dict.return_value = test_dict

        mythings.use_dict()

        mock_myhelpers.get_dict.assert_called_once()
Run Code Online (Sandbox Code Playgroud)

但是最终测试失败并出现错误:

AssertionError: Expected 'get_dict' to have been called once. Called 0 times

python mocking python-unittest python-unittest.mock

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