想到一块儿去了,只不过我打印的是"Life is short"
前几天有了类似想法,这几天用了七八个小时已经写了一大堆了,用了各种各样的高级特性来实现(猴子补丁/装饰器/协程/生成器/...)Life-is-Shortgithub.com
这样写表面看起来是违反Python哲学的,但也可以理解为写Python高级特性的demo顺带print-debug输出点东西,就比较好玩了
要说最长的,这个项目的集成测试就可以理解为“最长的”,因为它是套娃输出.
它用猴子补丁来捕获输出流,以测试其他实现是否正确输出,如果全部通过,就truncate然后释放输出流,最后自己输出"Life is short",所以无论你有多长的代码,都能塞进这个项目里,变成下面这个集成测试的依赖项。
import io
import sys
import unittest
class MyTestCase(unittest.TestCase):
manually_test_method = ["process_pool"]
words_result = [
"Life is short",
"Life is short ",
"Life is short\n",
"life is short\n",
"life is short ",
]
def setUp(self):
self.stdout, sys.stdout = sys.stdout, io.StringIO()
self.msg_buffer = ""
def tearDown(self):
sys.stdout = self.stdout
print(self.msg_buffer)
print("Life is short")
self.msg_buffer = ""
@staticmethod
def get_StringIO():
string = str(sys.stdout.getvalue())
sys.stdout.seek(0)
sys.stdout.truncate()
return string
def test_a(self):
from LifeIsShort.a import __all__ as method_list
for method in method_list:
exec(f"from LifeIsShort.a import {method}")
self.assertIn(self.get_StringIO(), self.words_result, msg=method)
def test_b(self):
from LifeIsShort.b import __all__ as method_list
for method in method_list:
exec(f"from LifeIsShort.b import {method}")
self.assertIn(self.get_StringIO(), self.words_result, msg=method)
def test_c(self):
from LifeIsShort.c import __all__ as method_list
for method in method_list:
exec(f"from LifeIsShort.c import {method}")
self.assertIn(self.get_StringIO(), self.words_result, msg=method)
def test_d(self):
from LifeIsShort.d import __all__ as method_list
for method in method_list:
if method in self.manually_test_method:
self.msg_buffer += f"Since sys.stdout sometimes cannot be captured, {method} needs to be tested manually.\n"
continue
for _ in range(10):
exec(f"from LifeIsShort.d import {method}")
eval(method).main()
self.assertIn(self.get_StringIO(), self.words_result, msg=method)
if __name__ == "__main__":
unittest.main()