Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
event system docs: Explain how to write event tests.
Steve Howell3e23c3b52c86
diff --git a/docs/subsystems/events-system.md b/docs/subsystems/events-system.mdindex b5c654827bd..d4316752afd 100644--- a/docs/subsystems/events-system.md+++ b/docs/subsystems/events-system.md@@ -215,31 +215,138 @@ request; the logic is in `zerver/views/events_register.py` and### Testing-The design above achieves everything we desire, at the cost that we-need to write a correct `apply_events` function. This is a difficult-function to implement correctly, because the situations that it tests-for almost never happen (being race conditions). So we have a special-helper test class, `BaseAction`, that is specifically designed to-test this function by ensuring the possible race condition always-happens. In particular, it does the following:+The design above achieves everything we desire, at the cost that we need to+write a correct `apply_events` function. This is a difficult function to+implement correctly, because the situations that it handles almost never+happen (being race conditions) during manual testing. Fortunately, we have+a protocol for testing `apply_events` in our automated backend tests.++#### Overview++Once you are completely confident that an "action function" works correctly+in terms of "normal" operation (which typically involves writing a+full-stack test for the corresponding POST/GET operation), then you will be+ready to write a test in `test_events.py`.++The actual code for a `test_events` test can be quite concise:++ def test_default_streams_events(self) -> None:+ stream = get_stream("Scotland", self.user_profile.realm)+ events = self.verify_action(lambda: do_add_default_stream(stream))+ check_default_streams("events[0]", events[0])+ # (some details omitted)++The real trick is debugging these tests.++The test example above has three things going on:++* Set up some data (`get_stream`)+* Call `verify_action` with an action function (`do_add_default_stream`)+* Use a schema checker to validate data (`check_default_streams`)++#### verify_action++All the heavy lifting that pertains to `apply_events` happens within the+call to `verify_action`, which is a test helper in the `BaseAction` class+within `test_events.py`.++The `verify_action` effectively simulates the possible race condition in+order to verify that the `apply_events` logic works correctly in the+context of some action function. To use our concrete example above, we are+seeing that applying the events from the `do_remove_default_stream` action+inside of `apply_events` to a stale copy of your state has the same effect+as doing the same action and computing a fresh copy of the state.++In particular, `verify_action` does the following:* Call `fetch_initial_state_data` to get the current state.-* Call a state change function that issues an event,-e.g. `do_change_full_name`, and capture any events that are generated.-* Call `apply_events(state, events)`, and compare the resulting- "hybrid state" to what one would get from calling- `fetch_initial_state_data` again now.--The `apply_events` code is correct if those two results are identical.-The `BaseAction` tests in `test_events` will print a diff+* Call the action function (e.g. `do_add_default_stream`).+* Capture the events generated by the action function.+* Call `apply_events(state, events)`, to get the resulting "hybrid state".+* Call `fetch_initial_state_data` again to get the "normal state".+* Compare the two results.++In the unlikely event that you write the `apply_events` logic correctly the+first time, then the two states will be identical, and the `verify_action`+call will succeed and return the events that came from the action.++Often you will get the `apply_events` logic wrong at first, which will+cause `verify_action` to fail. To help you debug, it will print a diffbetween the "hybrid state" and the "normal state" obtained from-calling `fetch_initial_state_data` after the changes. Those tests-also inspect the events generated to ensure they have the expected-format. Also, `verify_action` has the `state_change_expected` and `num_events`-arguments that configure how many events that it asserts were-generated and whether it expects the state after applying the events-to differ what what it was before (which help catch common classes of-bugs).+calling `fetch_initial_state_data` after the changes. If you encounter a+diff like this, you may be in for a challenging debugging exercise. It+will be helpful to re-read this documentation to understand the rationale+behind the `apply_events` function. It may also be helpful to read the code+for `verify_action` itself. Finally, you may want to ask for help on chat.++Before we move on to the next step, it's worth noting that `verify_action`+only has one required parameter, which is the action function. We+typically express the action function as a lambda, so that we+can pass in arguments:++ events = self.verify_action(lambda: do_add_default_stream(stream))++There are some notable optional parameters for `verify_action`:++ * `state_change_expected` must be set to `False` if your action+ doesn't actually require state changes for some reason; otherwise,+ `verify_action` will complain that your test doesn't really+ exercise any `apply_events` logic++ * `num_events` will tell `verify_action` how many events you+ expect to get from an action (the default is 1)++ * parameters such as `client_gravatar` and `slim_presence` get+ passed along to `fetch_initial_state_data` (and it's important+ to test both boolean values of these parameters for relevant+ actions)++For advanced use cases of `verify_action` we highly recommend reading+the code itself in `BaseAction` (in `test_events.py`).++#### Schema checking++Let's look at the last line of our example test snippet:++ # ...+ events = self.verify_action(lambda: do_add_default_stream(stream))+ check_default_streams("events[0]", events[0])++We have discussed `verify_action` in some detail, and you will+note that it returns the actual events generated by the action+function. It is part of our test discipline in `test_events` to+verify that the events are formatted in a predictable way.++Ideally, we would test that events match the exact data that we+expect, but it can be difficult to do this due to unpredictable+things like database ids. So instead, we just verify the "schema"+of the event(s). We use a schema checker like `check_default_streams`+to validate the types of the data.++If you are creating a new event format, then you will have to+write your own schema checker in `event_schema.py`. Here is+the example relevant to our example:++ default_streams_event = event_dict_type(+ required_keys=[+ ("type", Equals("default_streams")),+ ("default_streams", ListType(DictType(basic_stream_fields))),+ ]+ )+ check_default_streams = make_checker(default_streams_event)++Note that `basic_stream_fields` is not shown in these docs. The+best way to understand how to write schema checkers is to read+`event_schema.py`. There is a large block comment at the top of+the file, and then you can skim the rest of the file to see the+patterns.++When you create a new schema checker for a new event, you not+only make the `test_events` test more rigorous, you also allow+our other tools to use the same schema checker to validate data+in our node test fixtures and our OpenAPI documentation.++#### Code coverageThe final detail we need to ensure that `apply_events` always workscorrectly is to make sure that we have relevant tests for@@ -249,6 +356,8 @@ checking that all the calls to `send_event` are covered. Somedaywe'll add automation that verifies this directly by inspecting thecoverage data.+#### page_params+In the Zulip webapp, the data returned by the `register` API isavailable via the `page_params` parameter.