我的代码看起来有点像这样:
def write_wallet_file_entry(name, value, wallet_file, wallet_password):
some_code
some_more_code_to_write_to_the_wallet
...我使用Python (2.6)和单元测试模块来测试这段代码。如果钱包文件不存在,代码会创建它,然后向它写入一串键值对。
一旦我写到钱包,我就无法进行文本解析来确认写是干净的。
澄清:说明不太明显的问题:我不能使用"unittest.mock“或”模拟“模块,这会使问题更容易解决。我的环境停留在python2.6上,没有"virtualenv",没有“模拟”模块,也不允许在系统上安装外部模块。
任何建议都会很有帮助。
发布于 2017-06-11 06:44:02
一些假设
这些假设不会改变我回答的要点,但它们将意味着我们可以清楚地了解术语,因为您还没有发布最小、完整和可验证的示例。
open()是一个直接包装器。wallet_file和wallet_password是钱包文件特有的。name和value是要传递给文件的键值对。问题
您的问题在于能够测试您的写作是否“干净”。
但是,您不需要检查该文件是否被正确写入或是否已创建--您只需要以这种方式测试Python的file对象,这已经非常可靠地测试了。
单元测试的重点是测试您编写的代码,而不是外部服务。应该始终假定外部服务在单元测试中完成了它的工作--您只在集成测试中测试外部服务。
您需要的是一种方法,以确保您要写入的值被正确接收,而不是被混淆,并且您创建文件的请求是以您想要的格式接收的。测试邮件,而不是收件人。
一个方法
一种技术是将输入抽象为类,并将其子类化为具有虚拟方法。然后,您可以使用子类作为美化的模拟,用于所有意图和目的。
换句话说,改变
def write_wallet_file_entry(name, value, wallet_file, wallet_password):
...至
class Wallet(object):
def __init__(self, wallet_file, wallet_password):
self.file = wallet_file
self.password = wallet_password
def exists(self):
# code to check if file exists in filesystem
def write(self, name, value):
# code to write name, value
def write_wallet_file_entry(name, value, WalletObject):
assert isinstance(WalletObject, Wallet), "Only Wallets allowed"
if WalletObject.exists():
WalletObject.write(name, value)要进行测试,现在可以创建MockWallet
class MockWallet(Wallet):
def __init__(self, wallet_file, wallet_password):
super(MockWallet, self).__init__(wallet, wallet_password)
self.didCheckExists = False
self.didAttemptWrite = False
self.didReceiveCorrectly = False
def exists(self):
super(MockWallet, self).exists()
self.didCheckExists = True
def write(self, name, value):
# ... some code to validate correct arguments were pass
self.didReceiveCorrectly = True
if super(MockWallet, self).write(name, value):
self.didAttemptWrite = True现在您可以在生产中使用相同的函数(只需传递一个Wallet!)在测试中(只需通过一个MockWallet并检查该对象的属性!):
import unittest
from ... import MockWallet, write_wallet_file_entry
class Test(unittest.TestCase):
def testWriteFlow(self):
mock = MockWallet()
name, value = 'random', 'more random'
write_wallet_file_entry(name, value, mock)
self.assertTrue(mock.didCheckExists)
self.assertTrue(mock.didAttemptWrite)
self.assertTrue(mock.didReceiveCorrectly)瞧!现在,您已经有了一个经过测试的写流,它使用的只是依赖注入,而不是任意函数参数,使用的只是简单的临时模拟。
https://stackoverflow.com/questions/44406080
复制相似问题