python程序如何知道它是否正在被测试?例如:
def foo():
if foo_being_tested:
pseudorandom()
else:
random()
Run Code Online (Sandbox Code Playgroud)
在测试时,程序应使用伪随机序列,以便能够与程序的 C 代码版本进行比较,并且在常规执行中numpy应使用随机序列。
我有一些使用 pytest 编写的单元测试,它们成功地导致了段错误的发生。然而,如果在执行期间发生段错误(在我的 Mac 上),pytest 似乎会完全退出,并且不提供有关导致 python 解释器崩溃的原因的信息。
现在我可以从日志中推断出崩溃的特定测试并确定其中使用的值,但我想知道是否有任何方法能够以某种方式将崩溃记录为常规测试失败并继续迭代我的测试而不停止?
如果有帮助,我可以尝试举一个例子,但我认为这个问题应该是不言自明的。
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.main。test_so_main.py有两项测试:一项用于正常打开存在的文件,第二项用于测试处理FileNotFoundError。
常规文件打开的第一次测试test_read_path_from_disk_file_into_config_py工作正常。
FileNotFoundError第二个测试失败,因为AttributeError: __exit__. 我可以设置self.mock_open.return_value为FileNotFoundError或我可以将其设置为'garbage'。这没有什么区别。
测试so_main.py
import unittest
import unittest.mock as mock
import …Run Code Online (Sandbox Code Playgroud) 在unittest我可以用值断言side_effect可迭代 - 当调用修补方法时,每个值都会一一返回,而且我发现在unittest我的修补方法中可以根据输入参数返回不同的结果。我可以在 pytest 中做类似的事情吗?文档没有提到这一点。
我收到 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 3.6.5 和以下库:
现在我需要在测试失败的情况下捕获屏幕截图,所以我故意放了一个错误的陈述
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 …
我编写了一个简单的命令行实用程序,它接受一个文本文件并使用 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) 我希望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) 为了简化我的问题,请考虑以下代码:
如何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) 我正在测试 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-unittest ×10
python ×8
pytest ×4
python-3.x ×3
unit-testing ×3
mocking ×2
git ×1
pytest-mock ×1
python-3.6 ×1
python-click ×1
testing ×1
try-except ×1