Skip to content

Commit

Permalink
Avoid copying Cargo.lock
Browse files Browse the repository at this point in the history
  • Loading branch information
alexliesenfeld committed Aug 31, 2024
1 parent a518a93 commit ecbd26f
Show file tree
Hide file tree
Showing 16 changed files with 247 additions and 159 deletions.
37 changes: 37 additions & 0 deletions .github/workflows/deploy-docs.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
name: Deploy to GitHub Pages

on:
# Trigger the workflow every time you push to the `main` branch
# Using a different branch name? Replace `main` with your branch’s name
push:
branches: [ development ]
# Allows you to run this workflow manually from the Actions tab on GitHub.
workflow_dispatch:

# Allow this job to clone the repo and create a page deployment
permissions:
contents: read
pages: write
id-token: write

jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout your repository using git
uses: actions/checkout@v4
- name: Install, build, and upload your site
uses: withastro/action@v2
with:
path: ./docs/website # The root location of your Astro project inside the repository. (optional)

deploy:
needs: build
runs-on: ubuntu-latest
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
steps:
- name: Deploy to GitHub Pages
id: deployment
uses: actions/deploy-pages@v4
5 changes: 2 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -64,16 +64,15 @@ urlencoding = "2.1.2"

[features]
default = ["cookies"]
standalone = ["clap", "env_logger", "static-mock", "http2", "cookies", "remote", "remote-https"] # enables standalone mode
standalone = ["clap", "env_logger", "record", "http2", "cookies", "remote", "remote-https"] # enables standalone mode
color = ["colored"] # enables colorful output in standalone mode
cookies = ["headers"] # enables support for matching cookies
remote = ["hyper-util/client-legacy", "hyper-util/http2"] # allows to connect to remote mock servers
remote-https = ["remote", "rustls", "hyper-rustls", "hyper-rustls/http2"] # allows to connect to remote mock servers via HTTPS
proxy = ["remote-https", "hyper-util/client-legacy", "hyper-util/http2", "hyper-rustls", "hyper-rustls/http2"] # enables proxy functionality
static-mock = ["serde_yaml"] # allows to read mock definitions from the file system
https = ["rustls", "rcgen", "tokio-rustls", "rustls-pemfile", "rustls/ring", "tls-detect"] # enables httpmock server support for TLS/HTTPS
http2 = ["hyper/http2", "hyper-util/http2"] # enables httpmocks server support for HTTP2
record = ["static-mock", "proxy"]
record = ["proxy", "serde_yaml"]
experimental = [] # marker feature for experimental features

[[bin]]
Expand Down
3 changes: 2 additions & 1 deletion docs/website/astro.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@ import starlight from '@astrojs/starlight';

// https://astro.build/config
export default defineConfig({
site: 'https://alexliesenfeld.github.io/httpmock',
site: 'https://alexliesenfeld.github.io',
base: 'httpmock', // so that 'https://alexliesenfeld.github.io/httpmock' will be set as the base path
integrations: [
starlight({
title: 'httpmock Tutorial',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -108,8 +108,7 @@ The crate provides the following Cargo features:

- `cookies`: Enables request matchers for parsing and matching values in cookies
- `proxy`: Enables the mock server to function as a proxy server
- `record`: Enables functionality to record requests and responses (most useful in combination with the `proxy` feature)
- `static-mock`: Enables reading mock specifications from YAML files (e.g., recorded responses)
- `record`: Enables functionality to record requests and responses (most useful in combination with the `proxy` feature). Enables reading mock specifications from YAML files (e.g., recorded responses)
- `https`: Enables the mock server to provide a unified port for both, HTTP and HTTPS. Attention: This feature is experimental. Hence, there are no guarantees that this feature will work.
- `http2`: Enables mock server support for HTTP2
- `standalone`: Enables standalone mode
Expand Down
2 changes: 2 additions & 0 deletions src/api/adapter/local.rs
Original file line number Diff line number Diff line change
Expand Up @@ -164,13 +164,15 @@ impl MockServerAdapter for LocalMockServerAdapter {
Ok(())
}

#[cfg(feature = "record")]
async fn export_recording(&self, id: usize) -> Result<Option<Bytes>, ServerAdapterError> {
Ok(self
.state
.export_recording(id)
.map_err(|err| UpstreamError(err.to_string()))?)
}

#[cfg(feature = "record")]
async fn create_mocks_from_recording<'a>(
&self,
recording_file_content: &'a str,
Expand Down
4 changes: 4 additions & 0 deletions src/api/adapter/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,11 @@ pub trait MockServerAdapter {
) -> Result<ActiveRecording, ServerAdapterError>;
async fn delete_recording(&self, id: usize) -> Result<(), ServerAdapterError>;
async fn delete_all_recordings(&self) -> Result<(), ServerAdapterError>;

#[cfg(feature = "record")]
async fn export_recording(&self, id: usize) -> Result<Option<Bytes>, ServerAdapterError>;

#[cfg(feature = "record")]
async fn create_mocks_from_recording<'a>(
&self,
recording_file_content: &'a str,
Expand Down
6 changes: 5 additions & 1 deletion src/api/adapter/remote.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
use std::{borrow::Borrow, net::SocketAddr, sync::Arc};
use crate::{
common::{
data::{ForwardingRuleConfig, ProxyRuleConfig, RecordingRuleConfig}
},
};

use crate::api::{
adapter::{
Expand All @@ -22,7 +27,6 @@ use crate::{
},
http::HttpClient,
},
ForwardingRuleConfig, ProxyRuleConfig, RecordingRuleConfig,
};

pub struct RemoteMockServerAdapter {
Expand Down
7 changes: 6 additions & 1 deletion src/api/proxy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@ use crate::{
api::server::MockServer,
common::{
data::RequestRequirements,
data::RecordingRuleConfig,
util::{write_file, Join},
},
RecordingRuleConfig, When,
When,
};
use std::{
cell::Cell,
Expand Down Expand Up @@ -163,6 +164,7 @@ impl<'a> Recording<'a> {
///
/// # Errors
/// Errors if the file cannot be written due to issues like directory permissions, unavailable disk space, or other I/O errors.
#[cfg(feature = "record")]
pub fn save_to<PathRef: AsRef<Path>, IntoString: Into<String>>(
&self,
dir: PathRef,
Expand All @@ -179,6 +181,7 @@ impl<'a> Recording<'a> {
///
/// # Returns
/// Returns an `async` `Result` with the `PathBuf` of the saved file or an error if unable to save.
#[cfg(feature = "record")]
pub async fn save_to_async<PathRef: AsRef<Path>, IntoString: Into<String>>(
&self,
dir: PathRef,
Expand Down Expand Up @@ -214,6 +217,7 @@ impl<'a> Recording<'a> {
///
/// # Returns
/// Returns a `Result` with the `PathBuf` to the saved file or an error.
#[cfg(feature = "record")]
pub fn save<IntoString: Into<String>>(
&self,
scenario_name: IntoString,
Expand All @@ -228,6 +232,7 @@ impl<'a> Recording<'a> {
///
/// # Returns
/// Returns an `async` `Result` with the `PathBuf` of the saved file or an error.
#[cfg(feature = "record")]
pub async fn save_async<IntoString: Into<String>>(
&self,
scenario: IntoString,
Expand Down
35 changes: 23 additions & 12 deletions src/api/server.rs
Original file line number Diff line number Diff line change
@@ -1,42 +1,53 @@
#[cfg(feature = "remote")]
use crate::api::RemoteMockServerAdapter;
use crate::api::{
proxy::{
ForwardingRule, ForwardingRuleBuilder, ProxyRule, ProxyRuleBuilder, Recording,
RecordingRuleBuilder,
},
spec::{Then, When},
};
#[cfg(feature = "remote")]
use crate::common::http::HttpMockHttpClient;

use crate::common::data::ForwardingRuleConfig;

use crate::{
api::{LocalMockServerAdapter, MockServerAdapter},
common::{
data::{MockDefinition, MockServerHttpResponse, RequestRequirements},
runtime,
util::{read_env, read_file_async, with_retry, Join},
util::{read_env, with_retry, Join},
},
};

#[cfg(feature = "proxy")]
use crate::{
api::proxy::{ForwardingRuleBuilder, ForwardingRule, ProxyRuleBuilder, ProxyRule},
common::{
util::read_file_async,
data::{ForwardingRuleConfig, ProxyRuleConfig},
},
};

#[cfg(feature = "record")]
use crate::{
api::{
common::data::RecordingRuleConfig,
mock::MockSet,
proxy::{Recording, RecordingRuleBuilder}
},
};

#[cfg(feature = "record")]
use std::{path::PathBuf};

use crate::{
api::mock::MockSet,
server::{state::HttpMockStateManager, HttpMockServerBuilder},
};

#[cfg(feature = "proxy")]
use crate::ProxyRuleConfig;

use crate::{Mock, RecordingRuleConfig};
use crate::Mock;
use async_object_pool::Pool;
use lazy_static::lazy_static;
use std::{
cell::Cell,
future::pending,
net::{SocketAddr, ToSocketAddrs},
path::PathBuf,
rc::Rc,
sync::Arc,
thread,
Expand Down
1 change: 0 additions & 1 deletion src/common/data.rs
Original file line number Diff line number Diff line change
Expand Up @@ -918,7 +918,6 @@ pub struct Mismatch {
// Configs and Builders
// *************************************************************************************************

#[cfg(feature = "record")]
#[derive(Serialize, Deserialize, Clone, Default)]
pub struct RecordingRuleConfig {
pub request_requirements: RequestRequirements,
Expand Down
15 changes: 9 additions & 6 deletions src/server/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,13 @@ use crate::common::http::{HttpClient, HttpMockHttpClient};
use crate::server::server::MockServerHttpsConfig;
#[cfg(feature = "https")]
use crate::server::tls::{CertificateResolverFactory, GeneratingCertificateResolverFactory};
#[cfg(any(feature = "record", feature = "record"))]
use crate::server::{
persistence::read_static_mock_definitions,
};

use crate::server::{
handler::HttpMockHandler,
persistence::read_static_mock_definitions,
server::{MockServer, MockServerConfig},
state::{HttpMockStateManager, StateManager},
HttpMockServer,
Expand Down Expand Up @@ -190,7 +193,7 @@ pub struct HttpMockServerBuilder {
expose: Option<bool>,
print_access_log: Option<bool>,
history_limit: Option<usize>,
#[cfg(feature = "static-mock")]
#[cfg(feature = "record")]
static_mock_dir: Option<PathBuf>,
#[cfg(feature = "https")]
https_config_builder: HttpsConfigBuilder,
Expand All @@ -209,7 +212,7 @@ impl HttpMockServerBuilder {
port: None,
expose: None,
history_limit: None,
#[cfg(feature = "static-mock")]
#[cfg(feature = "record")]
static_mock_dir: None,
#[cfg(feature = "proxy")]
http_client: None,
Expand Down Expand Up @@ -321,7 +324,7 @@ impl HttpMockServerBuilder {
///
/// # Returns
/// A modified `HttpMockServerBuilder` instance for method chaining.
#[cfg(feature = "static-mock")]
#[cfg(feature = "record")]
pub fn static_mock_dir(mut self, path: PathBuf) -> Self {
self.static_mock_dir = Some(path);
self
Expand All @@ -334,7 +337,7 @@ impl HttpMockServerBuilder {
///
/// # Returns
/// A modified `HttpMockServerBuilder` instance for method chaining.
#[cfg(feature = "static-mock")]
#[cfg(feature = "record")]
pub fn static_mock_dir_option(mut self, path: Option<PathBuf>) -> Self {
self.static_mock_dir = path;
self
Expand Down Expand Up @@ -482,7 +485,7 @@ impl HttpMockServerBuilder {
.http_client
.unwrap_or_else(|| Arc::new(HttpMockHttpClient::new(None)));

#[cfg(feature = "static-mock")]
#[cfg(feature = "record")]
if let Some(dir) = self.static_mock_dir {
read_static_mock_definitions(dir, state.as_ref())?;
}
Expand Down
12 changes: 12 additions & 0 deletions src/server/handler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,9 @@ enum RoutePath {
ForwardingRuleCollection,
ProxyRuleCollection,
SingleProxyRule,
#[cfg(feature = "record")]
RecordingCollection,
#[cfg(feature = "record")]
SingleRecording,
}

Expand Down Expand Up @@ -157,11 +159,13 @@ where
Method::DELETE => return self.handle_delete_proxy_rule(params),
_ => {}
},
#[cfg(feature = "record")]
RoutePath::RecordingCollection => match method {
Method::POST => return self.handle_add_recording_matcher(req),
Method::DELETE => return self.handle_delete_all_recording_matchers(),
_ => {}
},
#[cfg(feature = "record")]
RoutePath::SingleRecording => match method {
Method::GET => return self.handle_read_recording(params),
Method::DELETE => return self.handle_delete_recording(params),
Expand Down Expand Up @@ -196,7 +200,10 @@ where
"/__httpmock__/forwarding_rules",
RoutePath::ForwardingRuleCollection,
);

#[cfg(feature = "record")]
path_tree.insert("/__httpmock__/proxy_rules", RoutePath::ProxyRuleCollection);
#[cfg(feature = "record")]
path_tree.insert("/__httpmock__/recordings", RoutePath::RecordingCollection);
}

Expand Down Expand Up @@ -306,12 +313,14 @@ where
return response::<()>(StatusCode::NO_CONTENT, None);
}

#[cfg(feature = "record")]
fn handle_add_recording_matcher(&self, req: Request<Bytes>) -> Result<Response<Bytes>, Error> {
let req_req: RecordingRuleConfig = parse_json_body(req)?;
let active_recording = self.state.create_recording(req_req);
return response(StatusCode::CREATED, Some(active_recording));
}

#[cfg(feature = "record")]
fn handle_delete_recording(&self, params: Path) -> Result<Response<Bytes>, Error> {
let deleted = self.state.delete_proxy_rule(param("id", params)?);
let status_code = if deleted.is_some() {
Expand All @@ -322,11 +331,13 @@ where
return response::<()>(status_code, None);
}

#[cfg(feature = "record")]
fn handle_delete_all_recording_matchers(&self) -> Result<Response<Bytes>, Error> {
self.state.delete_all_recordings();
return response::<()>(StatusCode::NO_CONTENT, None);
}

#[cfg(feature = "record")]
fn handle_read_recording(&self, params: Path) -> Result<Response<Bytes>, Error> {
let rec = self.state.export_recording(param("id", params)?)?;
let status_code = rec
Expand All @@ -335,6 +346,7 @@ where
return response(status_code, rec);
}

#[cfg(feature = "record")]
fn handle_load_recording(&self, req: Request<Bytes>) -> Result<Response<Bytes>, Error> {
let recording_file_content = std::str::from_utf8(&req.body())
.map_err(|err| RequestConversionError(err.to_string()))?;
Expand Down
2 changes: 1 addition & 1 deletion src/server/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ mod server;
pub mod state;
mod util;

#[cfg(feature = "static-mock")]
#[cfg(feature = "record")]
mod persistence;

#[cfg(feature = "https")]
Expand Down
Loading

0 comments on commit ecbd26f

Please sign in to comment.