如何在单元测试中断言变量内容(Flask,Python3,Nose2)

How to assert variable content in unit test (Flask, Python3, Nose2)

我有一个 Flask 应用程序,其中一些页面内容来自全局变量。我正在尝试设置一些单元测试来断言数据,但我似乎连一个局部变量都无法工作:

TEST_STRING = foo

self.assertIn(b['TEST_STRING'], response.data)

失败:

NameError: name 'b' is not defined

如果我引用普通变量:

self.assertIn(TEST_STRING, response.data)

我得到了预期的失败:

TypeError: a bytes-like object is required, not 'str'

如果我将变量数据硬编码到测试中,测试就会成功,但如果变量发生变化,我宁愿不必更新测试。我在这里错过了什么?

问题出在 bytes literal prefix b:

Bytes literals are always prefixed with 'b' or 'B'; they produce an instance of the bytes type instead of the str type. They may only contain ASCII characters; bytes with a numeric value of 128 or greater must be expressed with escapes.

虽然听起来像 bytesprefix = bytes 类型,但如果数据来自变量,这似乎不起作用。

解决方案是将 b 前缀更改为 bytes functionbytes,其中指出:

Bytes objects can also be created with literals, see String and Bytes literals.

所以虽然它们看起来可以互换,但情况并非总是如此!

对于我的用例,我还必须为 bytes 函数指定我的编码类型。

这是我原来的 post 示例的工作语法:

self.assertIn(bytes(TEST_STRING, "utf-8"), response.data)

感谢 John Gordon 在评论中建议切换到 bytes,但从未正式答复。所以几天后,我将继续并立即结束它。