【发布时间】:2020-03-29 11:16:53
【问题描述】:
我需要编写一个完全可重现的 Word2Vec 测试,并且需要将 PYTHONHASHSEED 设置为固定值。这是我目前的设置-yp
# conftest.py
@pytest.fixture(autouse=True)
def env_setup(monkeypatch):
monkeypatch.setenv("PYTHONHASHSEED", "123")
# test_w2v.py
def test_w2v():
assert os.getenv("PYTHONHASHSEED") == "123"
expected_words_embeddings = np.array(...)
w2v = Word2Vec(my_tokenized_sentences, workers=1, seed=42, hashfxn=hash)
words_embeddings = np.array([w2v.wv.get_vector(word) for word in sentence for sentence in my_tokenized_sentences)])
np.testing.assert_array_equal(expected_words_embeddings, words_embeddings)
这是奇怪的事情。
如果我通过PYTHONHASHSEED=123 python3 -m pytest test_w2v.py 从终端运行测试,则测试通过,没有任何问题。但是,如果我从 PyCharm 运行测试(使用 pytest,从编辑配置 -> 模板 -> Python 测试 -> pytest 设置),那么它会失败。最有趣的是,它不会在assert os.getenv("PYTHONHASHSEED") == "123" 失败,但它会在np.testing.assert_array_equal(expected_words_embeddings, words_embeddings) 失败
为什么会出现这种情况,有没有办法解决这个问题?
【问题讨论】:
-
根据this question中的答案可能是PyCharm中设置的env var太晚了。一种解决方法是在 PyCharm 启动脚本中设置变量。
标签: python unit-testing testing pytest word2vec