Skip to content

Commit

Permalink
chore: fix linting warnigns and add testing workflow
Browse files Browse the repository at this point in the history
  • Loading branch information
josecelano committed Apr 10, 2024
1 parent 61b256f commit e1eb867
Show file tree
Hide file tree
Showing 15 changed files with 256 additions and 18 deletions.
26 changes: 26 additions & 0 deletions .cargo/config.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
[alias]
cov = "llvm-cov"
cov-lcov = "llvm-cov --lcov --output-path=./.coverage/lcov.info"
cov-html = "llvm-cov --html"
time = "build --timings --all-targets"

[build]
rustflags = [
"-D",
"warnings",
"-D",
"future-incompatible",
"-D",
"let-underscore",
"-D",
"nonstandard-style",
"-D",
"rust-2018-compatibility",
"-D",
"rust-2018-idioms",
"-D",
"rust-2021-compatibility",
"-D",
"unused",
]

1 change: 1 addition & 0 deletions .github/CODEOWNERS
Validating CODEOWNERS rules …
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
@josecelano
19 changes: 19 additions & 0 deletions .github/dependabot.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
version: 2
updates:
- package-ecosystem: github-actions
directory: /
schedule:
interval: daily
target-branch: "develop"
labels:
- "Continuous Integration"
- "Dependencies"

- package-ecosystem: cargo
directory: /
schedule:
interval: daily
target-branch: "develop"
labels:
- "Build | Project System"
- "Dependencies"
126 changes: 126 additions & 0 deletions .github/workflows/testing.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
name: Testing

on:
push:
pull_request:

env:
CARGO_TERM_COLOR: always

jobs:
format:
name: Formatting
runs-on: ubuntu-latest

steps:
- id: checkout
name: Checkout Repository
uses: actions/checkout@v4

- id: setup
name: Setup Toolchain
uses: dtolnay/rust-toolchain@stable
with:
toolchain: nightly
components: rustfmt

- id: cache
name: Enable Workflow Cache
uses: Swatinem/rust-cache@v2

- id: format
name: Run Formatting-Checks
run: cargo fmt --check

check:
name: Static Analysis
runs-on: ubuntu-latest
needs: format

strategy:
matrix:
toolchain: [nightly, stable]

steps:
- id: checkout
name: Checkout Repository
uses: actions/checkout@v4

- id: setup
name: Setup Toolchain
uses: dtolnay/rust-toolchain@stable
with:
toolchain: ${{ matrix.toolchain }}
components: clippy

- id: cache
name: Enable Workflow Cache
uses: Swatinem/rust-cache@v2

- id: tools
name: Install Tools
uses: taiki-e/install-action@v2
with:
tool: cargo-machete

- id: check
name: Run Build Checks
run: cargo check --tests --benches --examples --workspace --all-targets --all-features

- id: lint
name: Run Lint Checks
run: cargo clippy --tests --benches --examples --workspace --all-targets --all-features -- -D clippy::correctness -D clippy::suspicious -D clippy::complexity -D clippy::perf -D clippy::style -D clippy::pedantic

- id: docs
name: Lint Documentation
env:
RUSTDOCFLAGS: "-D warnings"
run: cargo doc --no-deps --bins --examples --workspace --all-features

- id: clean
name: Clean Build Directory
run: cargo clean

- id: deps
name: Check Unused Dependencies
run: cargo machete


unit:
name: Units
runs-on: ubuntu-latest
needs: check

strategy:
matrix:
toolchain: [nightly, stable]

steps:
- id: checkout
name: Checkout Repository
uses: actions/checkout@v4

- id: setup
name: Setup Toolchain
uses: dtolnay/rust-toolchain@stable
with:
toolchain: ${{ matrix.toolchain }}
components: llvm-tools-preview

- id: cache
name: Enable Job Cache
uses: Swatinem/rust-cache@v2

- id: tools
name: Install Tools
uses: taiki-e/install-action@v2
with:
tool: cargo-llvm-cov, cargo-nextest

- id: test-docs
name: Run Documentation Tests
run: cargo test --doc

- id: test
name: Run Unit Tests
run: cargo test --tests --benches --examples --workspace --all-targets --all-features
8 changes: 8 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,9 @@
.env
**/*.rs.bk
/.coverage/
/.idea/
/.vscode/launch.json
/flamegraph.svg
/target
callgrind.out
perf.data*
7 changes: 7 additions & 0 deletions .vscode/extensions.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"recommendations": [
"streetsidesoftware.code-spell-checker",
"rust-lang.rust-analyzer",
"tamasfe.even-better-toml"
]
}
35 changes: 35 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
{
"[rust]": {
"editor.formatOnSave": true
},
"[ignore]": { "rust-analyzer.cargo.extraEnv" : {
"RUSTFLAGS": "-Z profile -C codegen-units=1 -C inline-threshold=0 -C link-dead-code -C overflow-checks=off -C panic=abort -Z panic_abort_tests",
"RUSTDOCFLAGS": "-Z profile -C codegen-units=1 -C inline-threshold=0 -C link-dead-code -C overflow-checks=off -C panic=abort -Z panic_abort_tests",
"CARGO_INCREMENTAL": "0",
"RUST_BACKTRACE": "1"
}},
"rust-analyzer.checkOnSave": true,
"rust-analyzer.check.command": "clippy",
"rust-analyzer.check.allTargets": true,
"rust-analyzer.check.extraArgs": [
"--",
"-D",
"clippy::correctness",
"-D",
"clippy::suspicious",
"-W",
"clippy::complexity",
"-W",
"clippy::perf",
"-W",
"clippy::style",
"-W",
"clippy::pedantic"
],
"evenBetterToml.formatter.allowedBlankLines": 1,
"evenBetterToml.formatter.columnWidth": 130,
"evenBetterToml.formatter.trailingNewline": true,
"evenBetterToml.formatter.reorderKeys": true,
"evenBetterToml.formatter.reorderArrays": true,

}
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ A collection of articles about testing in Rust.
## Links

- ["Unit Testing" book](https://www.manning.com/books/unit-testing) by [Vladimir Khorikov](https://github.com/vkhorikov).
- [Mockall](https://github.com/asomers/mockall). A powerful mock object library for Rust().
- [Mockall](https://github.com/asomers/mockall). A powerful mock object library for Rust.
- [Rust book. "A Use Case for Interior Mutability: Mock Objects"](https://doc.rust-lang.org/book/ch15-05-interior-mutability.html#a-use-case-for-interior-mutability-mock-objects) by [Steve Klabnik](https://steveklabnik.com/) and [Carol Nichols](http://carol-nichols.com/).
- [Mock Objects (manually) in Rust](https://paytonrules.com/post/mock-objects-in-rust/) by [Eric Smith](https://github.com/paytonrules).
- [A guide to mocking in Rust using Mockall](https://blog.logrocket.com/guide-mocking-rust-mockall/) by Manish Shivanandhan.
9 changes: 5 additions & 4 deletions src/bin/custom-mocks-in-rust.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
//! ```text
//! cargo run --bin custom-mocks-in-rust

use std::{rc::Rc, sync::Arc};
//! ```
use std::rc::Rc;

use testing_in_rust::example01::{
events::TrackerEventSender, handlers::handle_connect, tracker::Tracker,
};

fn main() {
let event_sender = Rc::new(TrackerEventSender {});
let tracker = Arc::new(Tracker::new(event_sender));
let tracker = Rc::new(Tracker::new(event_sender));

handle_connect(tracker)
handle_connect(&tracker);
}
5 changes: 3 additions & 2 deletions src/bin/testing-apis-in-rust.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
//! ```text
//! cargo run --bin testing-apis-in-rust
//!
//! ````
use std::net::{IpAddr, Ipv4Addr, SocketAddr};

use testing_in_rust::example02::api::start_server;
Expand All @@ -8,5 +9,5 @@ use testing_in_rust::example02::api::start_server;
async fn main() {
let bind_address = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 3030);

start_server(bind_address).await
start_server(bind_address).await;
}
5 changes: 4 additions & 1 deletion src/example01/events.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@ pub enum Event {
}

pub trait EventSender {
/// # Errors
///
/// Will return an error if the event can't be sent.
fn send_event(&self, event: Event) -> Result<(), Box<dyn Error>>;
}

Expand All @@ -16,7 +19,7 @@ pub struct TrackerEventSender {}

impl EventSender for TrackerEventSender {
fn send_event(&self, event: Event) -> Result<(), Box<dyn Error>> {
println!("Event::{:?} sent.", event);
println!("Event::{event:?} sent.");
Ok(())
}
}
8 changes: 6 additions & 2 deletions src/example01/handlers.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
use std::sync::Arc;
use std::rc::Rc;

use crate::example01::tracker::Tracker;

/// Controller for the UDP connect request
pub fn handle_connect(tracker: Arc<Tracker>) {
///
/// # Panics
///
/// Will panic if the tracker can't connect.
pub fn handle_connect(tracker: &Rc<Tracker>) {
tracker.connect().unwrap();
}
15 changes: 11 additions & 4 deletions src/example01/tracker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use std::{error::Error, rc::Rc};

use crate::example01::events::{Event, EventSender};

/// BitTorrent tracker
/// `BitTorrent` tracker
pub struct Tracker {
event_sender: Rc<dyn EventSender>,
}
Expand All @@ -12,6 +12,13 @@ impl Tracker {
Self { event_sender }
}

/// # Errors
///
/// Returning an error does never happen.
///
/// # Panics
///
/// Will panic if it can't send the event.
pub fn connect(&self) -> Result<(), Box<dyn Error>> {
println!("Tracker::connect.");

Expand All @@ -24,7 +31,7 @@ impl Tracker {

#[cfg(test)]
mod tests {
use std::{cell::RefCell, error::Error, rc::Rc, sync::Arc};
use std::{cell::RefCell, error::Error, rc::Rc};

use crate::example01::{
events::{Event, EventSender, TrackerEventSender},
Expand All @@ -35,7 +42,7 @@ mod tests {
fn the_tracker_should_allow_connections() {
// This is just a dummy test to show how we use the real struct instead of the mock
let event_sender = Rc::new(TrackerEventSender {});
let tracker = Arc::new(Tracker::new(event_sender));
let tracker = Rc::new(Tracker::new(event_sender));

assert!(tracker.connect().is_ok());
}
Expand Down Expand Up @@ -67,7 +74,7 @@ mod tests {
// Test using a custom mock for the TrackerEventSender

let event_sender = Rc::new(TrackerEventSenderMock::new());
let tracker = Arc::new(Tracker::new(event_sender.clone()));
let tracker = Rc::new(Tracker::new(event_sender.clone()));

tracker.connect().unwrap();

Expand Down
6 changes: 3 additions & 3 deletions src/example02/api.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
use std::net::SocketAddr;

use colored::*;
use colored::Colorize;
use warp::Filter;

pub async fn start_server(addr: SocketAddr) {
// GET /hello/warp => 200 OK with body "Hello, warp!"
let hello = warp::path!("hello" / String).map(|name| format!("Hello, {}!", name));
let hello = warp::path!("hello" / String).map(|name| format!("Hello, {name}!"));

let api_base_url = "http://127.0.0.1:3030/";

Expand All @@ -15,5 +15,5 @@ pub async fn start_server(addr: SocketAddr) {
"hello/warp".yellow()
);

warp::serve(hello).run(addr).await
warp::serve(hello).run(addr).await;
}
2 changes: 1 addition & 1 deletion tests/testing-apis-in-rust.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ async fn it_should_greeting_you() {

start_server_and_wait_until_is_ready_to_accept_requests(bind_address).await;

let url = format!("http://{}/hello/{}", &bind_address, "warp");
let url = format!("http://{}/hello/{}", &bind_address, "warp"); // DevSkim: ignore DS137138

let content = reqwest::get(url).await.unwrap().text().await.unwrap();

Expand Down

0 comments on commit e1eb867

Please sign in to comment.