Skip to content

Commit

Permalink
Adding testing to web
Browse files Browse the repository at this point in the history
  • Loading branch information
eckz committed May 30, 2024
1 parent b5898fb commit 8c25c4c
Show file tree
Hide file tree
Showing 7 changed files with 157 additions and 56 deletions.
3 changes: 3 additions & 0 deletions .cargo/config.toml
Original file line number Diff line number Diff line change
@@ -1,2 +1,5 @@
[build]
rustflags = ["--cfg=web_sys_unstable_apis"]

[target.wasm32-unknown-unknown]
runner = "wasm-server-runner"
98 changes: 58 additions & 40 deletions .github/workflows/ci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,33 @@ name: CI

on:
push:
branches: [main]
branches: ["*"]
pull_request:
branches: [main]

env:
CARGO_TERM_COLOR: always

jobs:
# Run cargo clippy -- -D warnings
check:
strategy:
matrix:
include:
- name: Linux x86_64
os: ubuntu-latest
target: x86_64-unknown-linux-gnu

# Run cargo test
test:
name: Test Suite
runs-on: ubuntu-latest
- name: Wasm
os: ubuntu-latest
target: wasm32-unknown-unknown

- name: MacOS aarch64
os: macos-14
target: aarch64-apple-darwin

name: Clippy ${{ matrix.name }}
runs-on: ${{ matrix.os }}
steps:
- name: Checkout sources
uses: actions/checkout@v4
Expand All @@ -27,15 +41,35 @@ jobs:
~/.cargo/registry/cache/
~/.cargo/git/db/
target/
key: ${{ runner.os }}-cargo-test-${{ hashFiles('**/Cargo.toml') }}
key: ${{ runner.os }}-${{ matrix.target }}-cargo-clippy-${{ hashFiles('**/Cargo.toml') }}
- name: Install stable toolchain
uses: dtolnay/rust-toolchain@stable
- name: Run cargo test
run: cargo test
with:
components: clippy
targets: ${{ matrix.target }}
- name: Run cargo check
run: cargo check --target ${{ matrix.target }}
- name: Run clippy
run: cargo clippy --target ${{ matrix.target }} --tests -- -D warnings

# Run cargo fmt --all -- --check
format:
name: Format
runs-on: ubuntu-latest
steps:
- name: Checkout sources
uses: actions/checkout@v4
- name: Install stable toolchain
uses: dtolnay/rust-toolchain@stable
with:
components: rustfmt
- name: Run cargo fmt
run: cargo fmt --all -- --check


# Run cargo test
builds_on_wasm:
name: Builds on wasm
test:
name: Test Suite
runs-on: ubuntu-latest
steps:
- name: Checkout sources
Expand All @@ -49,17 +83,15 @@ jobs:
~/.cargo/registry/cache/
~/.cargo/git/db/
target/
key: ${{ runner.os }}-cargo-buikd-wasm-${{ hashFiles('**/Cargo.toml') }}
key: ${{ runner.os }}-cargo-test-${{ hashFiles('**/Cargo.toml') }}
- name: Install stable toolchain
uses: dtolnay/rust-toolchain@stable
with:
targets: wasm32-unknown-unknown
- name: Run cargo build
run: cargo build --target wasm32-unknown-unknown
- name: Run cargo test
run: cargo test

# Run cargo clippy -- -D warnings
clippy_check:
name: Clippy
# Run wasm-pack test
test_wasm:
name: Test Wasm
runs-on: ubuntu-latest
steps:
- name: Checkout sources
Expand All @@ -73,28 +105,14 @@ jobs:
~/.cargo/registry/cache/
~/.cargo/git/db/
target/
key: ${{ runner.os }}-cargo-clippy-${{ hashFiles('**/Cargo.toml') }}
- name: Install stable toolchain
uses: dtolnay/rust-toolchain@stable
with:
components: clippy
- name: Install Dependencies
run: sudo apt-get update; sudo apt-get install --no-install-recommends libasound2-dev libudev-dev
- name: Run cargo check
run: cargo check
- name: Run clippy
run: cargo clippy -- -D warnings

# Run cargo fmt --all -- --check
format:
name: Format
runs-on: ubuntu-latest
steps:
- name: Checkout sources
uses: actions/checkout@v4
key: ${{ runner.os }}-cargo-test-wasm-${{ hashFiles('**/Cargo.toml') }}
- name: Install stable toolchain
uses: dtolnay/rust-toolchain@stable
with:
components: rustfmt
- name: Run cargo fmt
run: cargo fmt --all -- --check
targets: wasm32-unknown-unknown
- name: Install wasm-pack
run: curl https://rustwasm.github.io/wasm-pack/installer/init.sh -sSf | sh
- name: Tests headless chrome
run: wasm-pack test --headless --chrome
- name: Tests headless firefox
run: wasm-pack test --headless --firefox
8 changes: 7 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@ name = "bevy_simple_preferences"
version = "0.0.1-dev"
edition = "2021"

[lints.rust]
unsafe_code = "forbid"

[dependencies]
serde = { version = "1.0" }
thiserror = "1.0"
Expand All @@ -25,7 +28,10 @@ bevy = { version = "0.13", default-features = false, features = [
"webgl2",
"x11"
] }
bevy-inspector-egui = "0.24"
bevy-inspector-egui = { version = "0.24", default-features = false }
rand = "0.8"
serde_test = "1.0"
serde_assert = "0.7"

[target.'cfg(target_arch = "wasm32")'.dev-dependencies]
wasm-bindgen-test = "0.3"
1 change: 1 addition & 0 deletions src/param.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ impl<'w, 's, T: Clone + Reflect + TypePath + Send + Sync + 'static> Preferences<
}
}

#[cfg(not(target_family = "wasm"))]
#[cfg(test)]
mod tests {
use bevy::prelude::*;
Expand Down
20 changes: 15 additions & 5 deletions src/plugin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -160,14 +160,15 @@ pub fn save_preferences(preferences: Res<PreferencesMap>, storage: Res<Preferenc
}
}

#[cfg(not(target_family = "wasm"))]
#[cfg(test)]
mod tests {
use bevy::prelude::*;
use bevy::utils::HashMap;
use rand::random;
use tempfile::tempdir;

use crate::map::PreferencesMap;
use crate::map::{PreferencesMap, PreferencesMapDeserializeSeed};
use crate::storage::PreferencesStorage;
use crate::{PreferencesPlugin, PreferencesRegistry, RegisterPreferences};

#[derive(Reflect, Debug, Default)]
Expand All @@ -181,9 +182,18 @@ mod tests {
some_map: HashMap<String, MyPreferences>,
}

fn load_preferences_from_world(
storage: &PreferencesStorage,
world: &World,
) -> crate::Result<PreferencesMap> {
let type_registry_arc = world.get_resource::<AppTypeRegistry>().unwrap().0.clone();
let seed = PreferencesMapDeserializeSeed::new(type_registry_arc);
storage.load_preferences(seed)
}

#[test]
fn preferences_plugin_reads_from_disk() {
let temp_dir = tempdir().unwrap();
let temp_dir = tempfile::tempdir().unwrap();

let mut app = App::new();
let type_registry = app.world.resource::<AppTypeRegistry>().0.clone();
Expand Down Expand Up @@ -224,7 +234,7 @@ mod tests {

#[test]
fn preferences_plugin_saves_to_disk() {
let temp_dir = tempdir().unwrap();
let temp_dir = tempfile::tempdir().unwrap();

let mut app = App::new();

Expand Down Expand Up @@ -253,7 +263,7 @@ mod tests {
// We verify the preferences were stored to disk
{
let storage = storage_builder.create_storage().unwrap();
let mut preferences = storage.load_preferences_from_world(&app.world).unwrap();
let mut preferences = load_preferences_from_world(&storage, &app.world).unwrap();
let registry = app.world.get_resource::<PreferencesRegistry>().unwrap();
registry.apply_from_reflect_and_add_defaults(&mut preferences);

Expand Down
76 changes: 73 additions & 3 deletions src/storage/gloo.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use crate::map::PreferencesMapDeserializeSeed;
use bevy::log::{debug, info};
use bevy::log::*;
use serde::de::DeserializeSeed;

use crate::storage::PreferencesStorageImpl;
Expand Down Expand Up @@ -92,10 +92,80 @@ where
.expect("unreachable: get_item does not throw an exception")
.ok_or_else(|| gloo_storage::errors::StorageError::KeyNotFound(key.to_string()))?;

let mut deserializer =
serde_json::de::Deserializer::from_reader(item_string.as_str().as_bytes());
let mut deserializer = serde_json::de::Deserializer::from_reader(item_string.as_bytes());
let item = seed.deserialize(&mut deserializer)?;

Ok(item)
}
}

#[cfg(test)]
mod tests {
use crate::storage::gloo::GlooStorage;
use crate::storage::PreferencesStorageImpl;
use crate::PreferencesMap;
use bevy::prelude::Reflect;
use bevy::reflect::TypeRegistryArc;
use std::borrow::Cow;
use wasm_bindgen_test::{wasm_bindgen_test as test, wasm_bindgen_test_configure};

wasm_bindgen_test_configure!(run_in_browser);

#[derive(Reflect, PartialEq, Debug)]
struct Foo {
a: u32,
b: u32,
}

#[derive(Reflect, PartialEq, Debug)]
struct Bar(Cow<'static, str>);

impl Bar {
fn new(value: impl Into<Cow<'static, str>>) -> Self {
Self(value.into())
}
}

fn get_registry() -> TypeRegistryArc {
let type_registry_arc = TypeRegistryArc::default();

{
let mut type_registry = type_registry_arc.write();

type_registry.register::<Foo>();
type_registry.register::<Bar>();
type_registry.register::<Cow<'static, str>>();
}

type_registry_arc
}

const PREFERENCES_KEY: &str = "TEST_PREFERENCES_KEY";

fn write_and_read_storage(storage: GlooStorage) {
let registry = get_registry();

let mut map = PreferencesMap::new(registry.clone());

map.set(Foo { a: 1, b: 2 });
map.set(Bar::new("BarValue"));

storage.save_preferences(&map).unwrap();

let new_map = storage
.load_preferences(PreferencesMap::deserialize_seed(registry))
.unwrap();

assert_eq!(new_map, map);
}

#[test]
fn write_and_read_from_local_storage() {
write_and_read_storage(GlooStorage::local(PREFERENCES_KEY));
}

#[test]
fn write_and_read_from_session_storage() {
write_and_read_storage(GlooStorage::session(PREFERENCES_KEY));
}
}
7 changes: 0 additions & 7 deletions src/storage/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,6 @@ pub trait PreferencesStorageImpl: Send + Sync + 'static {
deserialize_seed: PreferencesMapDeserializeSeed,
) -> Result<PreferencesMap>;

#[cfg(test)]
fn load_preferences_from_world(&self, world: &World) -> Result<PreferencesMap> {
let type_registry_arc = world.get_resource::<AppTypeRegistry>().unwrap().0.clone();
let seed = PreferencesMapDeserializeSeed::new(type_registry_arc);
self.load_preferences(seed)
}

fn save_preferences(&self, map: &PreferencesMap) -> Result<()>;
}

Expand Down

0 comments on commit 8c25c4c

Please sign in to comment.