|
| 1 | +Story that rewrites given preconditions: |
| 2 | + docs: engine/rewrite-given |
| 3 | + about: | |
| 4 | + These examples show how to build stories that rewrite themselves |
| 5 | + from program output (in-test snapshot testing) but that rewrite |
| 6 | + the given preconditions. |
| 7 | + |
| 8 | + This is useful for changing |
| 9 | + |
| 10 | + ``` |
| 11 | + self.current_step.rewrite("argument").to("new output") |
| 12 | + ``` |
| 13 | + |
| 14 | + given: |
| 15 | + files: |
| 16 | + example.story: | |
| 17 | + Call API: |
| 18 | + given: |
| 19 | + mock api: |
| 20 | + request: | |
| 21 | + {"greeting": "hello"} |
| 22 | + response: | |
| 23 | + {"greeting": "hi"} |
| 24 | + steps: |
| 25 | + - Call API |
| 26 | + engine.py: | |
| 27 | + from hitchstory import BaseEngine, GivenDefinition, GivenProperty |
| 28 | + from strictyaml import Map, Str |
| 29 | + |
| 30 | + class Engine(BaseEngine): |
| 31 | + given_definition = GivenDefinition( |
| 32 | + mock_api=GivenProperty( |
| 33 | + schema=Map({"request": Str(), "response": Str()}), |
| 34 | + inherit_via=GivenProperty.OVERRIDE, |
| 35 | + ), |
| 36 | + ) |
| 37 | + |
| 38 | + def __init__(self, rewrite=True): |
| 39 | + self._rewrite = rewrite |
| 40 | + |
| 41 | + def call_api(self): |
| 42 | + if self._rewrite: |
| 43 | + self.given.rewrite("Mock API", "response").to("""{"greeting": "bye"}""") |
| 44 | + |
| 45 | + setup: | |
| 46 | + from hitchstory import StoryCollection |
| 47 | + from pathlib import Path |
| 48 | + from engine import Engine |
| 49 | + |
| 50 | + steps: |
| 51 | + - Run: |
| 52 | + code: | |
| 53 | + StoryCollection(Path(".").glob("*.story"), Engine(rewrite=True)).ordered_by_name().play() |
| 54 | + will output: |- |
| 55 | + RUNNING Call API in /path/to/working/example.story ... SUCCESS in 0.1 seconds. |
| 56 | + |
| 57 | + - File contents will be: |
| 58 | + filename: example.story |
| 59 | + contents: |- |
| 60 | + Call API: |
| 61 | + given: |
| 62 | + mock api: |
| 63 | + request: | |
| 64 | + {"greeting": "hello"} |
| 65 | + response: | |
| 66 | + {"greeting": "bye"} |
| 67 | + steps: |
| 68 | + - Call API |
0 commit comments