相关疑难解决方法(0)

Python3中的__builtin__模块在哪里?为什么要重命名?

我很好奇该__builtin__模块以及它是如何使用的,但我在Python3中找不到它!为什么感动?

Python 2.7

>>> import __builtin__
>>>
Run Code Online (Sandbox Code Playgroud)

Python 3.2

>>> import __builtin__
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named __builtin__
>>>
Run Code Online (Sandbox Code Playgroud)

python

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

断言__init__是用正确的参数调用的

我正在使用python模拟声明一个特定的对象是用正确的参数创建的.这是我的代码的样子:

class Installer:
    def __init__(foo, bar, version):
        # Init stuff
        pass
    def __enter__(self):
        return self

    def __exit__(self, type, value, tb):
        # cleanup
        pass

    def install(self):
        # Install stuff
        pass

class Deployer:
    def deploy(self):
        with Installer('foo', 'bar', 1) as installer:
            installer.install()
Run Code Online (Sandbox Code Playgroud)

现在,我想断言installer用正确的参数创建.这是我到目前为止的代码:

class DeployerTest(unittest.TestCase):
    @patch('Installer', autospec=True)
    def testInstaller(self, mock_installer):
        deployer = Deployer()
        deployer.deploy()

        # Can't do this :-(
        mock_installer.__init__.assert_called_once_with('foo', 'bar', 1)
Run Code Online (Sandbox Code Playgroud)

这是我得到的错误:

  File "test_deployment.py", line .., in testInstaller
    mock_installer.__init__.assert_called_once_with('foo', 'bar', 1)
AttributeError: 'function' object has no attribute 'assert_called_once_with'
Run Code Online (Sandbox Code Playgroud)

这是固定代码(Call …

python testing mocking python-unittest

14
推荐指数
1
解决办法
5263
查看次数

模拟open()函数在类方法中使用

我试图模拟我班级方法中使用的open函数.我找到了这个线程如何模拟with语句中使用的open(在Python中使用Mock框架)?但无法解决我的问题.单元测试文档也显示了一个解决方案,它也没有模拟我的开放式https://docs.python.org/3/library/unittest.mock-examples.html#patch-decorators

这是我的类使用open函数的方法:

#__init.py__

import json

class MyClass:

    def save_data_to_file(self, data):
        with open('/tmp/data.json', 'w') as file:
            json.dump(data, file)
...
mc = MyClass()
Run Code Online (Sandbox Code Playgroud)

现在我找到了一个不同的解决方案.这是我的测试:

#save_to_file_test.py

from mymodule import MyClass
from mock import mock_open, patch
import ast

class SaveToFileTest(unittest.TestCase):

    def setUp(self):
        self.mc = MyClass()
        self.data = [
            {'id': 5414470, 'name': 'peter'},
            {'id': 5414472, 'name': 'tom'},
            {'id': 5414232, 'name': 'pit'},
        ]

    def test_save_data_to_file(self):
        m = mock_open()
        with patch('mymodule.open', m, create=True):
            self.mc.save_data_to_file(self.data)
            string = ''
            for call in m.return_value.write.mock_calls:
                string += (call[1][0]) …
Run Code Online (Sandbox Code Playgroud)

python unit-testing mocking

11
推荐指数
1
解决办法
1万
查看次数

如何在test注释中使用带有patch.object()的mock_open()

我正在尝试模拟从文件读取.使用示例可以使用如下结构:

with patch('__builtin__.open', mock_open(read_data='1'), create=True) as m:
    with open('foo') as h:
        result = h.read()
Run Code Online (Sandbox Code Playgroud)

我想知道,有没有办法使用我的testcase注释来模拟open函数.喜欢:

@patch.object(__builtin__, 'open')
def test_check_status_running(self, m_open):
Run Code Online (Sandbox Code Playgroud)

我没有找到正确的方法,因为对我来说它适用于int并且不适用于字符串:

@patch.object(__builtin__, 'open')
def test_check_status_running1(self, m_open):
    m_open = mock_open(read_data='1')
    pid = open('testfile').read().strip()
    print type(pid)                    # <class 'mock.MagicMock'>
    self.assertEqual(1, int(pid))      # Pass
    self.assertEqual('1', pid)         # Fails MismatchError: '1' != <MagicMock name='open().read()' id='39774928'>
Run Code Online (Sandbox Code Playgroud)

python unit-testing mocking

10
推荐指数
1
解决办法
8763
查看次数

单元测试访问文件的功能

我有两个函数 - 一个用于构建一组文件的路径,另一个用于读取文件.以下是两个功能:

def pass_file_name(self):
    self.log_files= []
    file_name = self.path+"\\access_"+self.appliacation+".log"
    if os.path.isfile(file_name):
        self.log_files.append(file_name)
    for i in xrange(7):
         file_name = self.path+"\\access_"+self.appliacation+".log"+"."+str(i+1)
         if os.path.isfile(file_name):
            self.log_files.append(file_name)
    return self.log_files


def read_log_files (self, log_file_names): 
    self.log_entrys = []
    self.log_line = []
    for i in log_file_names:
        self.f = open(i)
        for line in self.f:
            self.log_line = line.split(" ")
            #print self.log_line
            self.log_entrys.append(self.log_line)
    return self.log_entrys
Run Code Online (Sandbox Code Playgroud)

对这两个功能进行单元测试的最佳方法是什么?

python unit-testing

9
推荐指数
1
解决办法
5290
查看次数

如何检查是否正在通过鼻子测试运行代码?

我有一些用于单元测试的代码.但是,它加载的库需要一些鼻子测试实际上不需要的数据,因为这些数据被单元测试模拟出来.我想保护库中的文件读取,以便在进行鼻子测试的情况下不会调用它们.

是否有捷径可寻?

我可以用sys.modules或初始命令行做一些事情,但我更喜欢更优雅的东西,如果它存在的话.

python nose

7
推荐指数
2
解决办法
1718
查看次数

Python模拟 - 模拟几个开放

阅读本文后:如何模拟with语句中使用的open(使用Python中的Mock框架)?

我可以使用以下方法在python中模拟open函数:

with patch(open_name, create=True) as mock_open:
    mock_open.return_value = MagicMock(spec=file)
    m_file = mock_open.return_value.__enter__.return_value
    m_file.read.return_value = 'text1'

    diffman = Diffman()
    diffman.diff(path1, path2)
Run Code Online (Sandbox Code Playgroud)

当我的测试方法使用一个开放语句时,它运行良好.这是我测试的方法:

def diff(self, a, b):
    with open(a, 'r') as old:
        with open(b, 'r') as new:
            oldtext = old.read()
            newtext = new.read()
Run Code Online (Sandbox Code Playgroud)

oldtext和newtext的值相同(此处为'text1').

我想为oldtext设置'text1',为newtext设置'text2'.

我怎样才能做到这一点 ?

python file-io mocking with-statement

6
推荐指数
1
解决办法
3589
查看次数

模拟打开(文件)中的行:

我想对我的应用程序的一个组件进行单元测试.代码看起来有点像下面.

def read_content_generator(myfile):
    for line in open(myfile):
        # do some string manipulation.
        yield result
Run Code Online (Sandbox Code Playgroud)

我遇到的问题是我无法open()for循环中模拟功能.

我的目标是unittest这样的:(我知道这段代码不对,但它只是我想要做的一个例子):

def test_openiteration(self):
    with mock.patch('open') as my_openmock:
        my_openmock.return_value = ['1','2','3']
        response = myfunction()
        self.assertEquals([1,2,3], response)
Run Code Online (Sandbox Code Playgroud)

python unit-testing mocking

4
推荐指数
2
解决办法
2313
查看次数

如何模拟open(...).write()而不会出现"No such file or directory"错误?

我的解决方案基于:

我有一个类,我可以实例化,写入文件.我正试图测试它,但我有嘲弄的问题open().我使用以下代码作为最小的代码,可以

import os
import unittest
from unittest.mock import mock_open, patch

__author__ = 'drews'


class MockPathExists(object):
    def __init__(self, return_value):
        self.received_args = None
        self.return_value = return_value

    def __call__(self, *args, **kwargs):
        self.received_args = args
        return self.return_value


class WriteData:
    def __init__(self, dir, name='World'):
        self.name = name
        self.dir = dir

    def dump(self):
        if os.path.exists(self.dir):
            with open('{0}/output.text'.format(self.dir), 'w+') as fp:
                fp.write('Hello, {0}!'.format(self.name))


class TestListWindowsPasswords(unittest.TestCase):
    def setUp(self):
        self._orig_pathexists = os.path.exists
        os.path.exists = MockPathExists(True)

    def test_dump(self):
        m = mock_open() …
Run Code Online (Sandbox Code Playgroud)

python filesystems unit-testing mocking python-3.x

4
推荐指数
2
解决办法
8717
查看次数

如何在 Python 单元测试中模拟 readlines()

我正在尝试为使用 readlines 从文件读取的类 init 编写单元测试:

class Foo:
    def __init__(self, filename):
         with open(filename, "r") as fp:
             self.data = fp.readlines()
Run Code Online (Sandbox Code Playgroud)

包括健全性检查等。

现在我正在尝试创建一个模拟对象,它可以让我测试这里发生的事情。

我尝试这样的事情:

TEST_DATA = "foo\nbar\nxyzzy\n"
with patch("my.data.class.open",  mock_open(read_data=TEST_DATA), create=True)
    f = Foo("somefilename")
    self.assertEqual(.....)
Run Code Online (Sandbox Code Playgroud)

问题是,当我查看 f.data 时,只有一个元素:

["foo\nbar\nxyzzy\n"]
Run Code Online (Sandbox Code Playgroud)

这意味着无论发生什么,都不会被分成几行,而是被视为一行。如何在模拟数据中强制换行?

unit-testing python-3.x

4
推荐指数
1
解决办法
2289
查看次数