Pytestfs写入然后读取不返回预期值。

huangapple go评论51阅读模式
英文:

Pytestfs write then read doesn't return expected value

问题

我正在尝试编写一个涉及文件系统的测试。我选择使用pyfakefspytest来编写这些测试。当我尝试在虚拟文件系统中写入然后读取时,似乎无法使任何测试工作。因此,我编写了一个简单的测试来确保pyfakefs读取了正确的值:

def test_filesystem(fs):
    with open("fooey.txt", "w+") as my_file:
        my_file.write("Hello")
        read = my_file.read(-1)
        assert os.path.exists("fooey.txt")
        assert "Hello" in read

第一个断言通过了,但第二个断言失败了。当我调试时,read 的值是 ''。我正在努力理解这里发生了什么。文件写入或读取在pyfakefs中是否不起作用?我做错了什么吗?

英文:

I'm trying to write a test involving the filesystem. I chose to use pyfakefs and pytest for writing these tests. When I was trying to write and then read from the fake filesystem, I couldn't seem to get any tests to work. So, I wrote a simple test to ensure that pyfakefs was reading the right value:

def test_filesystem(fs):
    with open("fooey.txt", "w+") as my_file:
        my_file.write("Hello")
        read = my_file.read(-1)
        assert os.path.exists("fooey.txt")
        assert "Hello" in read

The first assertion passes. The second one fails. When I debug, read has a value of ''. I'm struggling to understand what's going on here. Does file writing or reading not work within pyfakefs? Am I doing something wrong?

答案1

得分: 1

def test_filesystem(fs):
    with open("fooey.txt", "w") as my_file:
        my_file.write("Hello")
        
    with open("fooey.txt", "r") as my_file:
        read = my_file.read()
        assert os.path.exists("hoklh\\fooey.txt")
        assert "Hello" in read

This should do it!
英文:
def test_filesystem(fs):
    with open("fooey.txt", "w") as my_file:
        my_file.write("Hello")
        
    with open("fooey.txt", "r") as my_file:
        read = my_file.read()
        assert os.path.exists("hoklh\\fooey.txt")
        assert "Hello" in read

This should do it!

huangapple
  • 本文由 发表于 2023年6月1日 22:36:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/76383038.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定