Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add testing for website code blocks #2014

Merged
merged 10 commits into from
Aug 28, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .github/workflows/pull-request.yml
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,11 @@ jobs:
run: |
cd packages/yew
cargo test --doc --features "doc_test wasm_test"

- name: Run website code snippet tests
run: |
cd packages/website-test
cargo test

integration_tests:
name: Integration Tests on ${{ matrix.toolchain }}
Expand Down
3 changes: 3 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -35,3 +35,6 @@ members = [
# Release tools
"packages/changelog",
]
exclude = [
"packages/website-test",
]
10 changes: 9 additions & 1 deletion Makefile.toml
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ category = "Testing"
description = "Run all tests"
dependencies = ["tests-setup"]
env = { CARGO_MAKE_WORKSPACE_SKIP_MEMBERS = ["**/examples/*", "**/packages/changelog"] }
run_task = { name = ["test-flow", "doc-test-flow"], fork = true }
run_task = { name = ["test-flow", "doc-test-flow", "website-test"], fork = true }

[tasks.benchmarks]
category = "Testing"
Expand Down Expand Up @@ -86,6 +86,14 @@ private = true
command = "cargo"
args = ["test", "--doc"]

[tasks.website-test]
script = [
"""
cd packages/website-test
cargo test
"""
]

[tasks.bench-flow]
private = true
workspace = true
Expand Down
20 changes: 20 additions & 0 deletions packages/website-test/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
[package]
name = "website-test"
version = "0.1.0"
edition = "2018"
build = "build.rs"
publish = false

[dependencies]
yew-agent = { path = "../../packages/yew-agent/" }

[dev-dependencies]
yew = { path = "../../packages/yew/" }
yew-router = { path = "../../packages/yew-router/" }
derive_more = "0.99"
boolinator = "2.4"
weblog = "0.3.0"
wasm-bindgen = "0.2"

[build-dependencies]
glob = "0.3"
5 changes: 5 additions & 0 deletions packages/website-test/Makefile.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
[tasks.doc-test]
command = "cargo"
args = [
"test"
]
100 changes: 100 additions & 0 deletions packages/website-test/build.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
use glob::glob;
use std::collections::HashMap;
use std::env;
use std::fmt::{self, Write};
use std::fs;
use std::path::{Path, PathBuf};

#[derive(Debug, Default)]
struct Level {
nested: HashMap<String, Level>,
files: Vec<PathBuf>,
}

fn main() {
let home = env::var("CARGO_MANIFEST_DIR").unwrap();
let pattern = format!("{}/../../website/docs/**/*.md", home);
let base = format!("{}/../../website", home);
let base = Path::new(&base).canonicalize().unwrap();

let mut level = Level::default();

for entry in glob(&pattern).unwrap() {
let path = entry.unwrap();
let path = Path::new(&path).canonicalize().unwrap();
let rel = path.strip_prefix(&base).unwrap();

let mut parts = vec![];

for part in rel {
parts.push(part.to_str().unwrap());
}

level.insert(path.clone(), &parts[..]);
}

let out = format!("{}/website_tests.rs", env::var("OUT_DIR").unwrap());

fs::write(&out, level.to_contents()).unwrap();
}

impl Level {
fn insert(&mut self, path: PathBuf, rel: &[&str]) {
if rel.len() == 1 {
self.files.push(path);
} else {
let nested = self.nested.entry(rel[0].to_string()).or_default();
nested.insert(path, &rel[1..]);
}
}

fn to_contents(&self) -> String {
let mut dst = String::new();

self.write_inner(&mut dst, 0).unwrap();
dst
}

fn write_into(&self, dst: &mut String, name: &str, level: usize) -> fmt::Result {
self.write_space(dst, level);
let name = name.replace(|c| c == '-' || c == '.', "_");
writeln!(dst, "pub mod {} {{", name)?;

self.write_inner(dst, level + 1)?;

self.write_space(dst, level);
writeln!(dst, "}}")?;

Ok(())
}

fn write_inner(&self, dst: &mut String, level: usize) -> fmt::Result {
for (name, nested) in &self.nested {
nested.write_into(dst, name, level)?;
}

self.write_space(dst, level);

for file in &self.files {
let stem = Path::new(file)
.file_stem()
.unwrap()
.to_str()
.unwrap()
.replace("-", "_");

self.write_space(dst, level);
writeln!(dst, "#[doc = include_str!(\"{}\")]", file.display())?;
self.write_space(dst, level);
writeln!(dst, "pub fn {}_md() {{}}", stem)?;
}

Ok(())
}

fn write_space(&self, dst: &mut String, level: usize) {
for _ in 0..level {
dst.push_str(" ");
}
}
}
50 changes: 50 additions & 0 deletions packages/website-test/src/agents.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
//! Agent types that compile to be used by website code snippets

use yew_agent::{Agent, AgentLink, Context, HandlerId};

pub struct EventBus;

impl Agent for EventBus {
type Reach = Context<Self>;
type Message = ();
type Input = ();
type Output = String;

fn create(_link: AgentLink<Self>) -> Self {
Self
}

fn update(&mut self, _msg: Self::Message) {
// impl
}

fn handle_input(&mut self, _msg: Self::Input, _id: HandlerId) {
// impl
}
}

pub enum WorkerMsg {
Process,
}

pub struct MyWorker;

impl Agent for MyWorker {
type Reach = Context<Self>;

type Message = ();
type Input = WorkerMsg;
type Output = ();

fn create(_link: AgentLink<Self>) -> Self {
Self
}

fn update(&mut self, _msg: Self::Message) {
// impl
}

fn handle_input(&mut self, _msg: Self::Input, _id: HandlerId) {
// impl
}
}
3 changes: 3 additions & 0 deletions packages/website-test/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
pub mod agents;

include!(concat!(env!("OUT_DIR"), "/website_tests.rs"));
2 changes: 1 addition & 1 deletion website/docs/advanced-topics/optimizations.md
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ implementation of the main page and render the component you are working on on t

The slower speed and memory overhead are minor in comparison to the size gains made by not including the default allocator. This smaller file size means that your page will load faster, and so it is generally recommended that you use this allocator over the default, unless your app is doing some allocation-heavy work.

```rust
```rust ,ignore
// Use `wee_alloc` as the global allocator.
#[global_allocator]
static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;
Expand Down
Loading