Flask 单元测试并且不理解我对“TypeError: a bytes-like object is required, not 'str'”的修复
问题:Flask 单元测试并且不理解我对“TypeError: a bytes-like object is required, not 'str'”的修复
我目前正在构建一个小型 Web 应用程序来提高我的技能,作为其中的一部分,我正在尝试全面采用最佳实践、测试、CI、良好的架构、干净的代码等等。在过去的几个工作中,我一直在努力对我的根路由进行测试,而不是通过路由函数返回一个字符串,我正在渲染一个模板,我已经让它工作了,但我没有理解它为什么起作用,这让我很困扰。
主要是使用 b,在我的断言字符串之前,我认为这与我渲染的不是字符串,而是 html 表示,类似于 return 和 print 之间的区别,但我是朦胧,希望有人给我上学。
我要问的行是 test_homepage_response 函数的第 4 行。以及它是如何运作的。特别是关于我得到的这个错误:
返回的错误:
ERROR: test_home_welcome_return (tests.home_page_tests.HomePageTestClass)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/xibalba/code/reel/tests/home_page_tests.py", line 31, in test_home_welcome_return
self.assertIn(u"Welcome to Reel!", response.data)
File "/usr/local/lib/python3.6/unittest/case.py", line 1077, in assertIn
if member not in container:
TypeError: a bytes-like object is required, not 'str'
我对家乡路线的测试:
# Test Suite
import unittest
from reel import app
from reel.views import home_welcome
class HomePageTesttClass(unittest.TestCase):
@classmethod
def setupClass(cls):
pass
@classmethod
def tearDownClass(cls):
pass
def setUp(self):
self.app = app.test_client()
self.app.testing = True
def test_homepage_response(self):
result = self.app.get('/')
self.assertEqual(result.status_code, 200)
self.assertIn(b"Welcome to Reel!", result.data)
def tearDown(self):
pass
if __name__ == '__main__':
unittest.main()
我的意见文件:
from reel import app
from flask import render_template
@app.route('/')
def home_welcome():
return render_template("homepage.html")
@app.route('/signup')
def signup_welcome():
return 'Welcome to the signup page!'
@app.route('/login')
def login_welcome():
return 'Welcome to the login page!'
@app.route('/become_a_guide')
def guide_welcome():
return 'Welcome to the guide page!'
@app.route('/help')
def help_welcome():
return 'Welcome to the help page!'
我使用的一些资源来解决这个问题,这使我倾向于使用 b:
https://github.com/mjhea0/flaskr-tdd#first-test
字符串字面量前面的'b'字符是做什么的?
感谢这是一个很长的问题,我试图提供尽可能多的上下文,因为我真的觉得这个问题很愚蠢,但我不想在不知道为什么我使用的解决方案有效的情况下继续。
一如既往地感谢你。
解答
非常简短的简单答案是,字符串属于strtype,而 string 前面的“b”现在将使其成为 bytes 对象,属于typebytes。因此,期望是_是_它们实际上应该_不_彼此相等,因为_不同_类型的比较预计会失败。
此外,您使用assertIn的断言是使用in关键字进行测试。为了使用in正确测试,在这种情况下,您_需要_比较字节与字节。
观察这个简单的例子,它会带你复制你正在经历的事情:
>>> s = "this is a string"
>>> t = "this is another string"
>>> type(s) == type(t)
True
>>> sb = b"this is a string"
>>> type(sb) == type(s)
False
>>> s in sb
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: a bytes-like object is required, not 'str'
因此,如您所见,“b”实际上在这里起到了功能性目的,为您提供了不同类型的“对象”。
你_可以_也_解码_到一个字符串:
>>> res = sb.decode()
>>> type(res)
<class 'str'>
但是,建议明确说明您的解码:
>>> res = sb.decode('utf-8')
>>> type(res)
<class 'str'>
最后,这里的是关于bytes的 containment 测试的一个很好的更详细的解释。希望这可以帮助。
更多推荐

所有评论(0)