单元测试 pyinotify 成功吗?
我正在使用 pyinotify 将文件从源目录镜像到目标目录。当我手动执行时,我的代码似乎可以正常工作,但我无法获得准确的单元测试结果。我认为问题归结为:
- 我必须使用 ThreadedNotifier 在我的测试中,否则他们会 挂起,等待手动输入。
- 因为我正在使用另一个线程,所以我的测试和通知程序不同步。运行观察性测试时通过的测试,运行单元测试时手动测试失败。
有人成功进行了 pyinotify 单元测试吗?
I'm using pyinotify to mirror files from a source directory to a destination directory. My code seems to be working when I execute it manually, but I'm having trouble getting accurate unit test results. I think the problem boils down to this:
- I have to use ThreadedNotifier
in my tests, otherwise they will
just hang, waiting for manual input. - Because I'm using another thread, my tests and the Notifier get out of sync. Tests that pass when running observational, manual tests fail when running the unit tests.
Has anyone succeeded in unit testing pyinotify?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在进行单元测试时,通常应该排除线程和文件系统之类的东西。您是否有理由使用实际文件系统、用户输入等进行单元测试?
Python 使得猴子补丁变得非常容易;例如,您可以将整个 os/sys 模块替换为模拟对象(例如 Python Mock )这样你就不需要处理文件系统了。这也将使您的测试运行得更快。
如果您想对文件系统进行功能测试,我建议您设置一个具有已知状态的虚拟机,并在每次运行测试时恢复到该状态。您还可以根据需要模拟用户输入、文件操作等。
编辑
这是一个如何伪造或模拟“打开”功能的简单示例。
假设您有一个带有
get_text_upper
函数的模块my_module
:您想在不实际接触文件系统的情况下测试它(最终您将开始只传递文件对象而不是文件名以避免这种情况,但现在......)。您可以模拟
open
函数,以便它返回 StringIO 对象:使用模拟库只会使此过程变得更加容易和灵活。
这是关于 python 模拟库的 stackoverflow 帖子。
When unit testing, things like threads and the file system should normally be factored out. Do you have a reason to unit test with the actual file system, user input, etc.?
Python makes it very easy to monkey patch; you could for example, replace the entire os/sys module with a mock object (such as Python Mock) so that you never need to deal with the file system. This will also make your tests run much more quickly.
If you want to do functional testing with the file system, I'd recommend setting up a virtual machine that will have a known state, and reverting to that state every time you run the tests. You could also simulate user input, file operations, etc. as needed.
Edit
Here's a simple example of how to fake, or mock the "open" function.
Say you've got a module,
my_module
, with aget_text_upper
function:You want to test this without actually touching the file system (eventually you'll start just passing file objects instead of file names to avoid this but for now...). You can mock the
open
function so that it returns a StringIO object instead:Using a mocking library just makes this process a lot easier and more flexible.
Here's a stackoverflow post on mocking libraries for python.