Skip to content

Commit

Permalink
Documentation draft
Browse files Browse the repository at this point in the history
  • Loading branch information
alexliesenfeld committed Jun 20, 2023
1 parent 62a648b commit f1555e7
Show file tree
Hide file tree
Showing 27 changed files with 599 additions and 24 deletions.
8 changes: 8 additions & 0 deletions doc/docs/advanced/_category_.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"label": "Advanced",
"position": 5,
"link": {
"type": "generated-index",
"description": "5 minutes to learn the most important Docusaurus concepts."
}
}
36 changes: 36 additions & 0 deletions doc/docs/advanced/composition.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/// A semantic convenience for applying multiple operations
/// on a given `When` instance via an discrete encapsulating
/// function.
///
/// ## Example:
///
/// ```
/// # use httpmock::When;
/// // Assuming an encapsulating function like:
///
/// fn is_authorized_json_post_request(when: When) -> When {
/// when.method(httpmock::Method::POST)
/// .header("authorization", "SOME API KEY")
/// .header("content-type", "application/json")
/// }
///
/// // It can be applied without breaking the usual `When`
/// // semantic style. Meaning instead of:
/// #
/// # fn counter_example(when: When) -> When {
/// is_authorized_json_post_request(when.json_body_partial(r#"{"key": "value"}"#))
/// # }
///
/// // the `and` method can be used to preserve the
/// // legibility of the method chain:
/// # fn semantic_example(when: When) -> When {
/// when.query_param("some-param", "some-value")
/// .and(is_authorized_json_post_request)
/// .json_body_partial(r#"{"key": "value"}"#)
/// # }
///
/// // is still intuitively legible as "when some query
/// // parameter equals "some-value", the request is an
/// // authorized POST request, and the request body
/// // is the literal JSON object `{"key": "value"}`.
///
Empty file.
97 changes: 97 additions & 0 deletions doc/docs/advanced/simulating_network_latency.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
# Getting Started
This crate in Rust allows you to create mocks for HTTP requests and responses.
Follow the steps below to create mocks using this crate:

1. Add the httpmock crate as a dependency in your Cargo.toml file:
```toml
[dependencies]
httpmock = "0.6"
```
2. Import the necessary modules in your Rust code:
```rust
use httpmock::{MockServer, Method, Mock, MockRef, Regex};
```
3. Create a MockServer instance. This server will handle all the mock requests and responses:
```rust
let server = MockServer::start();
```
4. Define a mock by creating a Mock instance. You can specify the HTTP method, URL pattern,
request headers, request body, and response details:
```rust
let mock = Mock::new()
.expect_method(Method::GET)
.expect_path("/api/users")
.expect_query_param("page", "1")
.return_status(200)
.return_header("Content-Type", "application/json")
.return_body("{\"message\": \"Mock response\"}")
.create_on(&server);
```
In this example, the mock is set up to expect a GET request with the URL pattern "/api/users" and
the query parameter "page" with the value "1". It will return a 200 status code, set the "Content-Type"
header to "application/json", and respond with a JSON body.
5. Make requests to the mock server using the reqwest crate or any other HTTP client library:
```rust
let url = server.url("/api/users?page=1");
let response = reqwest::blocking::get(&url).unwrap();
```
Here, we're using the reqwest crate to send a GET request to the mock server. The response will be the one defined in the mock.
6. Verify the mock was called and perform assertions on it if needed:
```rust
assert_eq!(mock.times_called(), 1);
```
You can check the number of times the mock was called using the times_called method and perform assertions on it or other properties.
Remember to clean up the mock server after you're done by calling server.stop() to avoid port conflicts.
That's how you can create mocks using the httpmock crate in Rust.

# Full Code Files

### `Cargo.toml`
```toml
[package]
name = "my-httpmock-project"
version = "0.1.0"
edition = "2021"

[dev-dependencies]
httpmock = "0.6"
reqwest = "0.11"
```



### test.rs
```rust
use httpmock::{MockServer, Method, Mock, Regex};
use reqwest::blocking::get;

#[test]
fn test_mocked_request() {
// Create a MockServer instance
let server = MockServer::start();

// Define a mock
let mock = Mock::new()
.expect_method(Method::GET)
.expect_path("/api/users")
.expect_query_param("page", "1")
.return_status(200)
.return_header("Content-Type", "application/json")
.return_body("{\"message\": \"Mock response\"}")
.create_on(&server);

// Send a request to the mock server
let url = server.url("/api/users?page=1");
let response = get(&url).unwrap();

// Verify the mock was called and perform assertions
assert_eq!(mock.times_called(), 1);
assert_eq!(response.status().as_u16(), 200);
assert_eq!(
response.headers().get("Content-Type").unwrap(),
"application/json"
);
assert_eq!(response.text().unwrap(), "{\"message\": \"Mock response\"}");
}
```

97 changes: 97 additions & 0 deletions doc/docs/advanced/starting_multiple_servers.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
# Getting Started
This crate in Rust allows you to create mocks for HTTP requests and responses.
Follow the steps below to create mocks using this crate:

1. Add the httpmock crate as a dependency in your Cargo.toml file:
```toml
[dependencies]
httpmock = "0.6"
```
2. Import the necessary modules in your Rust code:
```rust
use httpmock::{MockServer, Method, Mock, MockRef, Regex};
```
3. Create a MockServer instance. This server will handle all the mock requests and responses:
```rust
let server = MockServer::start();
```
4. Define a mock by creating a Mock instance. You can specify the HTTP method, URL pattern,
request headers, request body, and response details:
```rust
let mock = Mock::new()
.expect_method(Method::GET)
.expect_path("/api/users")
.expect_query_param("page", "1")
.return_status(200)
.return_header("Content-Type", "application/json")
.return_body("{\"message\": \"Mock response\"}")
.create_on(&server);
```
In this example, the mock is set up to expect a GET request with the URL pattern "/api/users" and
the query parameter "page" with the value "1". It will return a 200 status code, set the "Content-Type"
header to "application/json", and respond with a JSON body.
5. Make requests to the mock server using the reqwest crate or any other HTTP client library:
```rust
let url = server.url("/api/users?page=1");
let response = reqwest::blocking::get(&url).unwrap();
```
Here, we're using the reqwest crate to send a GET request to the mock server. The response will be the one defined in the mock.
6. Verify the mock was called and perform assertions on it if needed:
```rust
assert_eq!(mock.times_called(), 1);
```
You can check the number of times the mock was called using the times_called method and perform assertions on it or other properties.
Remember to clean up the mock server after you're done by calling server.stop() to avoid port conflicts.
That's how you can create mocks using the httpmock crate in Rust.

# Full Code Files

### `Cargo.toml`
```toml
[package]
name = "my-httpmock-project"
version = "0.1.0"
edition = "2021"

[dev-dependencies]
httpmock = "0.6"
reqwest = "0.11"
```



### test.rs
```rust
use httpmock::{MockServer, Method, Mock, Regex};
use reqwest::blocking::get;

#[test]
fn test_mocked_request() {
// Create a MockServer instance
let server = MockServer::start();

// Define a mock
let mock = Mock::new()
.expect_method(Method::GET)
.expect_path("/api/users")
.expect_query_param("page", "1")
.return_status(200)
.return_header("Content-Type", "application/json")
.return_body("{\"message\": \"Mock response\"}")
.create_on(&server);

// Send a request to the mock server
let url = server.url("/api/users?page=1");
let response = get(&url).unwrap();

// Verify the mock was called and perform assertions
assert_eq!(mock.times_called(), 1);
assert_eq!(response.status().as_u16(), 200);
assert_eq!(
response.headers().get("Content-Type").unwrap(),
"application/json"
);
assert_eq!(response.text().unwrap(), "{\"message\": \"Mock response\"}");
}
```

20 changes: 20 additions & 0 deletions doc/docs/advanced/synchronous_ans_asynchronous_api.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# Using httpmock

## Using httpmock as a test library
* [Getting Started](library_usage/getting_started.md)
* [Deleting Mocks](library_usage/deleting_mocks.md)
* [Custom Request Matcher](library_usage/custom_request_matcher.md)
* [Simulating Network Latency](library_usage/simulating_network_latency.md)
* [Matching JSON](library_usage/matching_json.md)
* [Matching Files and Binary Content](library_usage/matching_files_and_binary.md)
* [Starting Multiple Servers](library_usage/starting_multiple_servers.md)

# Technical Details
* [Synchronous and asynchronous API](synchronous_ans_asynchronous_api.md)
* [How Request Matching Works](page3.md)
* [Test Execution, Parallelism and Resource Usage](page3.md)

## httpmock Standalone
* [Why Standalone?](page3.md)
* [Static Mocks using YAML files](page3.md)
* [Limitations of the Standalone Mode](page3.md)
Empty file.
8 changes: 8 additions & 0 deletions doc/docs/basics/_category_.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"label": "Basics",
"position": 2,
"link": {
"type": "generated-index",
"description": "5 minutes to learn the most important Docusaurus concepts."
}
}
5 changes: 5 additions & 0 deletions doc/docs/basics/deleting_mocks.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
sidebar_position: 1
---

# Deleting Mocks
5 changes: 5 additions & 0 deletions doc/docs/responses/1-method.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
sidebar_position: 1
---

# Method
5 changes: 5 additions & 0 deletions doc/docs/responses/2-path.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
sidebar_position: 2
---

# URL Path
5 changes: 5 additions & 0 deletions doc/docs/responses/3-query-params.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
sidebar_position: 3
---

# Query Parameters
5 changes: 5 additions & 0 deletions doc/docs/responses/4-header.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
sidebar_position: 4
---

# Headers
5 changes: 5 additions & 0 deletions doc/docs/responses/5-cookie.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
sidebar_position: 5
---

# Cookies
14 changes: 14 additions & 0 deletions doc/docs/responses/6-body.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
---
sidebar_position: 6
---
# Body

## String Body


## JSON Body


## JSON Body Object

## Binary Body Object
37 changes: 37 additions & 0 deletions doc/docs/responses/7-custom.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
---
sidebar_position: 9
---

# Custom Matchers

With `httpmock`, you have the flexibility to define your own custom request matchers using closures.
These matchers are functions that return `true` if a request matches the desired criteria or constraints you specify
and `false` otherwise. `httpmock` seamlessly integrates these custom matchers into its request matching process,
allowing you to create more specific and tailored request expectations. You can specify a custom matcher using the
`Mock::matches` method.

```rust
use httpmock::prelude::*;
use isahc::get;

#[test]
fn custom_request_matcher_test() {
// Arrange
let server = MockServer::start();

let mock = server.mock(|when, then| {
when.matches(|req| req.path.to_lowercase().ends_with("test"));
then.status(200);
});

// Act: Send the HTTP request
let response = get(server.url("/thisIsMyTest")).unwrap();

// Assert
mock.assert();
assert_eq!(response.status(), 200);
}
```

Please note that custom request matchers **cannot be used
in standalone mode.**
5 changes: 5 additions & 0 deletions doc/docs/responses/8-form-urlencoded.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
sidebar_position: 10
---

# Form www-urlencoded
8 changes: 8 additions & 0 deletions doc/docs/responses/_category_.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"label": "Sending Responses",
"position": 4,
"link": {
"type": "generated-index",
"description": "5 minutes to learn the most important Docusaurus concepts."
}
}
8 changes: 8 additions & 0 deletions doc/docs/standalone/_category_.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"label": "Standalone Mode",
"position": 6,
"link": {
"type": "generated-index",
"description": "5 minutes to learn the most important Docusaurus concepts."
}
}
Loading

0 comments on commit f1555e7

Please sign in to comment.