我的代码在 pytest 中得到空白输出,不知道如何解决这个问题

Getting blank output in pytest for my code, not sure how to resolve this

在第 1 部分中,有 3 个变量(攻击、防御和生命值)。如果攻击小于或等于防御,则意味着没有造成伤害。但是,如果攻击大于防御,就会造成伤害。

# part 1
def main():
    defense = 5
    attack = 8
    hp = 10

    if attack <= defense:
        return 'No damage, since the defense stat is too high.'
    
    if attack > defense:
       damage = attack - defense
       hp = hp - damage
       return f'{damage} damage inflicted, enemy HP is now {hp}.'

print(main())

在我的代码的第 2 部分中,有一个宠物名称列表。我的代码计算列表中名称的数量和列表中每个单词的长度。

# part 2
pets = ['Spot', 'Boots', 'Mrs. Fluffington', 'Lenny', 'Bowser', 'Gina']
count = 0
word_lengths = []

def list_count(pets):
    count = 0
    for names in pets:
        count += 1
    return count

print(f'There are {list_count(pets)} pets in the list.')

def length_counter():
    x = 0
    while x < list_count(pets):
        length = 0
        for character in pets[x]:
            length += 1
        word_lengths.append(length)
        x += 1
    return f'The word lengths of each word are {word_lengths}.'
print(length_counter())

我在下面的 pytest 结果中添加了一张图片 link。 enter image description here

(更新)文本中的 Pytest:

Microsoft Windows [Version 10.0.19043.1237]
(c) Microsoft Corporation. All rights reserved.

(base) C:\Users\aksha>cd C:\Users\aksha\lab-02-akshayanbalathas

(base) C:\Users\aksha\lab-02-akshayanbalathas>pytest --capture=sys
============================= test session starts =============================
platform win32 -- Python 3.8.8, pytest-6.2.3, py-1.10.0, pluggy-0.13.1
rootdir: C:\Users\aksha\lab-02-akshayanbalathas
plugins: anyio-2.2.0
collected 1 item

lab02_test.py F                                                          [100%]

================================== FAILURES ===================================
__________________________________ test_main __________________________________

capsys = <_pytest.capture.CaptureFixture object at 0x0000016FF996D670>

    def test_main(capsys):
        lab02.main() # run the student's code
        captured = capsys.readouterr()
        sys.stderr.write('actual output:\n')
        sys.stderr.write(captured.out + '\n')
        correct_output = '3 damage inflicted, enemy HP is now 7.\nThere are 6 pets in the list.\nThe word lengths of each word are [4, 5, 16, 5, 6, 4].\n'

        sys.stderr.write('correct output:\n')
        sys.stderr.write(correct_output + '\n')
>       assert captured.out == correct_output # verify that the output is a match
E       AssertionError: assert '3 damage inf...16, 5, 6, 4].' == '3 damage inf..., 5, 6, 4].\n'
E         Skipping 112 identical leading characters in diff, use -v to show
E         - , 5, 6, 4].
E         ?            -
E         + , 5, 6, 4].

lab02_test.py:14: AssertionError
---------------------------- Captured stderr call -----------------------------
actual output:
3 damage inflicted, enemy HP is now 7.
There are 6 pets in the list.
The word lengths of each word are [4, 5, 16, 5, 6, 4].
correct output:
3 damage inflicted, enemy HP is now 7.
There are 6 pets in the list.
The word lengths of each word are [4, 5, 16, 5, 6, 4].

============================== warnings summary ===============================
..\anaconda3\lib\site-packages\pyreadline\py3k_compat.py:8
  C:\Users\aksha\anaconda3\lib\site-packages\pyreadline\py3k_compat.py:8: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated since Python 3.3, and in 3.9 it will stop working
    return isinstance(x, collections.Callable)

-- Docs: https://docs.pytest.org/en/stable/warnings.html
=========================== short test summary info ===========================
FAILED lab02_test.py::test_main - AssertionError: assert '3 damage inf...16, ...
======================== 1 failed, 1 warning in 0.39s =========================

(base) C:\Users\aksha\lab-02-akshayanbalathas>

好的,正如您在测试代码中看到的那样:

def test_main(capsys):
        lab02.main() # run the student's code

它会调用您的 main() 函数,因此所有打印都应在该函数内完成,而不是在全局范围内完成。此时,测试将忽略 main() 之外的所有代码。

我稍微修改了你的代码,现在它通过了测试:

# part 1
def main():
    defense = 5
    attack = 8
    hp = 10

    if attack <= defense:
        print('No damage, since the defense stat is too high.')
    
    if attack > defense:
       damage = attack - defense
       hp = hp - damage
       print(f'{damage} damage inflicted, enemy HP is now {hp}.')

    # part 2
    pets = ['Spot', 'Boots', 'Mrs. Fluffington', 'Lenny', 'Bowser', 'Gina']
    count = 0
    word_lengths = []

    def list_count(pets):
        count = 0
        for names in pets:
            count += 1
        return count

    print(f'There are {list_count(pets)} pets in the list.')

    def length_counter():
        x = 0
        while x < list_count(pets):
            length = 0
            for character in pets[x]:
                length += 1
            word_lengths.append(length)
            x += 1
        return f'The word lengths of each word are {word_lengths}.'
    print(length_counter())

我只是将您 main() 中的前两个 return 更改为 print(),并将您的其余代码移至 main() 中。随心所欲地重构它;] 如果我是你,我会将所有函数定义移到 main() 之外,然后从中调用它们。这是一种常见且好的做法。函数应该 return strmain() 应该打印输出。

如有任何问题,请告诉我。