starknet-rs icon indicating copy to clipboard operation
starknet-rs copied to clipboard

feat: mock transport for tests

Open shramee opened this issue 1 year ago • 1 comments

Testing functionality based on RPC response

Tests require setting up an RPC server with appropriate state to test different cases. This makes tests slow and setup tedious.

This PR adds a mock transport mode to mock certain requests.

Features

Flow

JsonRpcTransport::send_request is implemented to,

  1. Tries to find mocked response for request_json in self.mocked_requests.
  2. Tries to find mocked response for request method mock in self.mocked_methods.
  3. Otherwise, Falls back to http_transport if available.
  4. Else throws an error (all requests must be resolved).

Optional HttpTransport fallback

Adding an http_transport allows falling back to HttpTransport for requests not mocked.

Mocking

Responses can be mocked for

  1. specific request json string (high priority) or
  2. all requests if w specific JsonRpcMethod.

Dev Experience

Helpful prints are added to stdout to help build mocks for the requests received and responses from fallback HTTP.

Use this code to mock this request

mock_transport.mock_request(
    "{\"id\":1,\"jsonrpc\":\"2.0\",\"method\":\"starknet_getBlo...}".into(),
    "{\"jsonrpc\":\"2.0\",\"result\":{\"block_hash\":\"0x5cc6b9...}".into()
);

image

shramee avatar Nov 26 '23 23:11 shramee