如何为 Python 单元测试提供标准输入、文件和环境变量输入? [英] How to supply stdin, files and environment variable inputs to Python unit tests?

查看:39
本文介绍了如何为 Python 单元测试提供标准输入、文件和环境变量输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在出现以下情况时编写测试:

  1. 测试用户输入.
  2. 测试从文件中读取的输入.
  3. 测试从环境变量中读取的输入.

如果有人能告诉我如何处理上述场景,那就太好了;如果你能指点我一些文档/文章/博客文章,我仍然会很棒阅读.

解决方案

您所描述的所有三种情况都是您需要特别注意的地方,以确保您在设计中使用松散耦合.

真的需要对 Python 的 raw_input 方法进行单元测试吗?open 方法?os.environ.get?号

您需要设置您的设计,以便您可以用其他方式来检索该输入.然后,在您的单元测试期间,您将放入某种实际上并未调用 raw_inputopen 的存根.

例如,您的正常代码可能类似于:

导入操作系统def say_hello(input_func):名称 = input_func()返回你好"+名字def prompt_for_name():return raw_input("你叫什么名字?")打印 say_hello(prompt_for_name)# 通常会传入方法,但为了简洁起见,可以使用 lambdas打印 say_hello(lambda: open("a.txt").readline())打印 say_hello(lambda: os.environ.get("USER"))

会话看起来像:

<前>你叫什么名字?某人你好某人你好[一些文字]你好标记

那么您的测试将类似于:

def test_say_hello():输出 = say_hello(拉姆达:测试")断言(输出==你好测试")

请记住,您不应该测试一种语言的 IO 设施(除非您是设计该语言的人,这是完全不同的情况).

How to write tests where conditions like the following arise:

  1. Test user Input.
  2. Test input read from a file.
  3. Test input read from an environment variable.

It'd be great if someone could show me how to approach the above mentioned scenarios; it'd still be awesome if you could point me to a few docs/articles/blog posts which I could read.

解决方案

All three situations you've described are where you need to specifically go out of your way to ensure you are using loose coupling in your design.

Do you really need to unit test Python's raw_input method? The open method? os.environ.get? No.

You need to set up your design so that you can substitute other ways of retrieving that input. Then, during your unit tests, you'll throw in a stub of some sort that doesn't actually call raw_input or open.

For instance, your normal code might be something like:

import os
def say_hello(input_func):
    name = input_func()
    return "Hello " + name

def prompt_for_name():
    return raw_input("What is your name? ")

print say_hello(prompt_for_name)
# Normally would pass in methods, but lambdas can be used for brevity
print say_hello(lambda: open("a.txt").readline())
print say_hello(lambda: os.environ.get("USER"))

The session looks like:

What is your name? somebody
Hello somebody
Hello [some text]

Hello mark

Then your test will be like:

def test_say_hello():
    output = say_hello(lambda: "test")
    assert(output == "Hello test")

Keep in mind that you should not have to test a language's IO facilities (unless you're the one designing the language, which is a different situation entirely).

这篇关于如何为 Python 单元测试提供标准输入、文件和环境变量输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆