Для начала я следовал этому руководству, в котором объясняется, как утверждать фиктивные вызовы. Затем я попытался отладить сообщения печати в разных местах теста, чтобы посмотреть, какую информацию я могу получить от имитируемого объекта, но получил пустой массив.
Как отличить макетные объекты, которые я вызываю, когда запускаю тест? Как мне следует отладить этот тест, запустив Pdb или распечатав сообщения?
Мой тест
Код: Выделить всё
import unittest
from unittest.mock import patch, call
from ..piperouter import route
from ..pipewriter import PipelineWriter
class PipeRouterTests(unittest.TestCase):
def test_debug_pipeline_file(self):
pipeline = PipelineWriter.generate_debug_pipe()
with patch("builtins.open") as m:
route()
print("Debugging calls", m)
m.assert_has_calls(
[
call("capture_pipeline.yml", "w+"),
call().__enter__().write(pipeline),
call().__exit__(None, None, None)
]
)
Код: Выделить всё
class PipelineWriter:
@staticmethod
def generate_debug_pipe():
return """
default:
image: alpine:latest
before-script:
- |
apk add curl
debug:
script:
- |
cd ci
chmod +x logwriter.sh
./logwriter.sh
artifacts:
path:
- pipeline_logs/
"""
Код: Выделить всё
import argparse
from .pipewriter import PipelineWriter
def route(*args: dict):
with open("capture_pipeline.yml", "w+") as f:
if args:
f.write(PipelineWriter.generate_store_pipe(args))
print("Data type in piperouter.py", type(args[0]))
else:
f.write(PipelineWriter.generate_debug_pipe())
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("level", help="ctf level", type=str)
parser.add_argument("flag", help="lab flag", type=str)
args = parser.parse_args()
route()
Код: Выделить всё
Debugging calls
F
======================================================================
FAIL: test_debug_pipeline_file (ci.tests.test_piperouter.PipeRouterTests.test_debug_pipeline_file)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/wavesinaroom/dev/overthewire_bandit_py/ci/tests/test_piperouter.py", line 12, in test_debug_pipeline_file
m.assert_has_calls(
~~~~~~~~~~~~~~~~~~^
[
^
......
]
^
)
^
File "/nix/store/c104simypy6nd11g7mncz8yqwyrirfxz-python3-3.13.11-env/lib/python3.13/unittest/mock.py", line 1016, in assert_has_calls
raise AssertionError(
......
) from cause
AssertionError: Calls not found.
Expected: [call('capture_pipeline.yml', 'w+'),
call().__enter__().write('\ndefault:\n image: alpine:latest\n before-script:\n - |\n apk add curl \ndebug:\n script:\n - | \n cd ci\n chmod +x logwriter.sh\n ./logwriter.sh\n artifacts:\n path:\n - pipeline_logs/\n'),
call().__exit__(None, None, None)]
Actual: [call('capture_pipeline.yml', 'w+'),
call().__enter__(),
call().__enter__().write('\ndefault:\n image: alpine:latest\n before-script:\n - |\n apk add curl \ndebug:\n script:\n - | \n cd ci\n chmod +x logwriter.sh\n ./logwriter.sh\n artifacts:\n path:\n - pipeline_logs/\n'),
call().__exit__(None, None, None),
call.__str__()]
----------------------------------------------------------------------
Ran 1 test in 0.002s
FAILED (failures=1)
Подробнее здесь: https://stackoverflow.com/questions/798 ... cted-calls
Мобильная версия