前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python怎么去写单元测试用例去测试hello world呢

Python怎么去写单元测试用例去测试hello world呢

作者头像
未来sky
发布2018-08-30 14:38:16
7460
发布2018-08-30 14:38:16
举报
文章被收录于专栏:好好学习吧好好学习吧

逛着博客园,看到乙醇大佬的一篇随笔 https://www.cnblogs.com/nbkhic/p/9370446.html,于是就在想怎么测试这句hello world

代码语言:javascript
复制
print('hello world')

想法是修改stdout的指向到一个io.StringIO流中,然后把流中的数据与‘hello world’去比较,可是写完之后发现,程序虽然没报错,但是流中无数据写入,百思不得其解;只好换成文件流,代码如下:

代码语言:javascript
复制
import sys


def hi():
    print('hello world')

if __name__ == '__main__':
    old = sys.stdout

    with open('test','w') as oFile:
        sys.stdout = oFile
        hi()

    sys.stdout = old

    with open('test','r') as oFile:
        if 'hello world' + '\n' == oFile.readline():
            print('PASS')
        else:
            print('FAIL',file=sys.stderr)

结果也输出了PASS

代码语言:javascript
复制
C:\Users\suneee\AppData\Local\Programs\Python\Python36\python.exe E:/wangjz/PyWorkSpace/LearnPython/test.py
PASS

Process finished with exit code 0

PS:至于比较字符串‘hello world’后面为什么要加个'\n',可以看下print函数说明

代码语言:javascript
复制
def print(*args, sep=' ', end='\n', file=None): # known special case of print
    """
    print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
    
    Prints the values to a stream, or to sys.stdout by default.
    Optional keyword arguments:
    file:  a file-like object (stream); defaults to the current sys.stdout.
    sep:   string inserted between values, default a space.
    end:   string appended after the last value, default a newline.
    flush: whether to forcibly flush the stream.
    """
    pass
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018-08-13 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档