Skip to content

Commit

Permalink
Add tests (#79)
Browse files Browse the repository at this point in the history
* added tests to error_logs and pidgtm_compile_times

Signed-off-by: danbugs <[email protected]>

* fix && fmt

Signed-off-by: danbugs <[email protected]>

* added tests to game, player, player_page_views, set, and tournament

Signed-off-by: danbugs <[email protected]>

* fix && fmt

Signed-off-by: danbugs <[email protected]>

* modified CI to run tests

Signed-off-by: danbugs <[email protected]>

* fix CI

Signed-off-by: danbugs <[email protected]>

* fix CI

Signed-off-by: danbugs <[email protected]>

* added codecov, fixed CI

Signed-off-by: danbugs <[email protected]>

* fixing typo

Signed-off-by: danbugs <[email protected]>

* trying cargo test

Signed-off-by: danbugs <[email protected]>

* fixing typo

Signed-off-by: danbugs <[email protected]>

* fixing typo

Signed-off-by: danbugs <[email protected]>

* fixed CI

Signed-off-by: danbugs <[email protected]>

* fix && fmt

Signed-off-by: danbugs <[email protected]>

---------

Signed-off-by: danbugs <[email protected]>
  • Loading branch information
danbugs authored Jan 5, 2024
1 parent 6bddfad commit 0a7edad
Show file tree
Hide file tree
Showing 22 changed files with 748 additions and 67 deletions.
15 changes: 15 additions & 0 deletions .codecov.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
---
codecov:
notify:
after_n_builds: 1
require_ci_to_pass: false

coverage:
precision: 2
round: down
range: 5..20

comment:
layout: "header, diff"
behavior: default
require_changes: false
45 changes: 37 additions & 8 deletions .github/workflows/ci-cd.yml
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ jobs:
name: Install PostgreSQL
uses: ikalnytskyi/action-setup-postgres@v4

# This test is necessary to run cross build
- if: matrix.os == 'ubuntu-latest'
name: Install QEMU user emulation
run: docker run --rm --privileged tonistiigi/binfmt --install all
Expand All @@ -74,7 +75,15 @@ jobs:
profile: minimal
toolchain: stable
override: true
target: ${{ matrix.target }}
target: ${{ matrix.target }}

# We use cargo-llvm-cov for tests rather than cargo test to also evaluate test coverage
- name: Install cargo-llvm-cov
uses: taiki-e/install-action@v1
with:
tool: cargo-llvm-cov
- name: Install llvm-tools-preview for cargo-llvm-cov
run: rustup component add llvm-tools-preview

- name: Cache Rust targets
uses: actions/cache@v3
Expand All @@ -85,7 +94,32 @@ jobs:
target/
key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }}
restore-keys: |
${{ runner.os }}-cargo-
${{ runner.os }}-cargo-
- name: Build
run: cargo build --release --all
env:
SERVER_ADDRESS: 'http://127.0.0.1:8080'
SERVER_ADDRESS_2: ${{ secrets.SERVER_ADDRESS_2 }}
RECAPTCHA_SITE_KEY: ${{ secrets.RECAPTCHA_SITE_KEY }}
# ^^^ the front-end looks for keys at compile time, so we need these in

# We need `--test-threads=1` due to a Diesel/postgres bug
- name: Run tests and get coverage
run: |
cargo llvm-cov clean --workspace
cargo llvm-cov --no-report --package smithe_lib --no-default-features -- --exact --nocapture --test-threads=1
cargo llvm-cov report --lcov --output-path ./coverage.lcov
env:
PIDGTM_DATABASE_URL: ${{ secrets.PIDGTM_DATABASE_URL }}
STARTGG_TOKEN: ${{ secrets.STARTGG_TOKEN }}

- name: Upload Code Coverage Results
uses: codecov/codecov-action@v3
with:
file: ./coverage.lcov
env:
CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}

# Conditional step for standard Rust build for non-arm64 targets
- if: matrix.os == 'ubuntu-latest'
Expand All @@ -95,12 +129,7 @@ jobs:
ls -la target/aarch64-unknown-linux-gnu/
env:
SERVER_ADDRESS: 'http://127.0.0.1:8080'
CROSS_CONTAINER_OPTS: '--platform linux/arm64'

- name: Build
run: cargo build --release --target ${{ matrix.target }}
env:
SERVER_ADDRESS: 'http://127.0.0.1:8080'
CROSS_CONTAINER_OPTS: '--platform linux/arm64'

- if: matrix.os == 'ubuntu-latest'
name: Upload arm64 pidgtm artifact
Expand Down
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,5 @@
test.out
frontend/dist
tokens.txt
id_ranges.txt
id_ranges.txt
coverage.lcov
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ In the future, I hope to make it possible for you to claim your profile (i.e., v
## What Can It Do Right Now?

Smithereens is not yet available as a website, only as a command-line tool. With it, you can:
- ✅ view the hidden seeding for an event,
- ✅ view the hidden seeding for an event (only in the CLI),
- ✅ view a player's overall results,
- ✅ view a 'digested' tournament result, and
- ❎ claim your profile, and make it your own.
Expand Down
16 changes: 0 additions & 16 deletions backend/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -157,19 +157,3 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
let _ = rocket().launch().await?;
Ok(())
}

#[cfg(test)]
mod tests {
use rocket::{http::Status, local::blocking::Client};

use super::rocket;

#[test]
fn get_player_tournaments_test() -> Result<(), Box<dyn std::error::Error>> {
let client = Client::tracked(rocket())?;
let response = client.get("/tournaments/1178271").dispatch();
assert_eq!(response.status(), Status::Ok);

Ok(())
}
}
2 changes: 1 addition & 1 deletion database/src/db_models/set.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use serde::Serialize;
#[derive(Debug, Serialize, Insertable, Queryable, QueryableByName)]
#[diesel(table_name = player_sets)]
pub struct Set {
id: i32,
pub id: i32,
pub completed_at: i64,
requester_id: i32,
requester_tag_with_prefix: String,
Expand Down
1 change: 1 addition & 0 deletions database/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ fn try_connect() -> ConnectionResult<PgConnection> {

#[cfg(test)]
mod tests {
#![allow(unused)]
use super::*;
use anyhow::Result;

Expand Down
5 changes: 4 additions & 1 deletion lib/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ authors = [ "Dan Chiarlone" ]

[lib]
doctest = false
test = false

[dependencies]
anyhow = "1"
Expand All @@ -20,3 +19,7 @@ ctrlc = "3.4"
as-any = "0.3"
tokio = { version = "1.1", features = [ "rt", "macros" ] }
chrono = "0.4"

[features]
default = ["skip_db_tests"]
skip_db_tests = []
114 changes: 107 additions & 7 deletions lib/src/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

use anyhow::Result;
use as_any::Downcast;
use startgg::{
Entrant, Event, PhaseGroup, Player, Score, Seed, Set as SGGSet, SetSlot, Standing,
StandingConnection, StandingStats, Tournament, User, Videogame,
};
use tracing::Level;
use tracing_subscriber::FmtSubscriber;

Expand All @@ -16,6 +20,13 @@ use std::{
time::{Duration, Instant},
};

use startgg::{queries::set_getter::SetGetterVars, GQLData, GQLVars};

use crate::{
error_logs::insert_error_log, game::delete_games_from_requester_id,
set::delete_sets_by_requester_id, tournament::delete_tournaments_from_requester_id,
};

pub fn init_logger() -> Result<()> {
let subscriber = FmtSubscriber::builder()
.with_max_level(Level::INFO)
Expand All @@ -26,13 +37,6 @@ pub fn init_logger() -> Result<()> {
Ok(())
}

use startgg::{queries::set_getter::SetGetterVars, GQLData, GQLVars};

use crate::{
error_logs::insert_error_log, game::delete_games_from_requester_id,
set::delete_sets_by_requester_id, tournament::delete_tournaments_from_requester_id,
};

#[allow(clippy::too_many_arguments)]
pub async fn start_read_all_by_increment_execute_finish_maybe_cancel<V, F, D>(
is_cli: bool,
Expand Down Expand Up @@ -166,3 +170,99 @@ where
finish(gql_vars)?;
Ok(())
}

pub fn get_sggset_test_data() -> SGGSet {
SGGSet {
id: 44887323,
games: None,
slots: vec![
SetSlot {
entrant: Some(Entrant {
id: Some(9412484),
name: Some("Ancient 3 scrub".to_string()),
}),
seed: Some(Seed {
seedNum: Some(2),
entrant: None,
}),
standing: Some(Standing {
entrant: None,
player: None,
stats: Some(StandingStats {
score: Score { value: Some(2.0) },
}),
placement: None,
}),
},
SetSlot {
entrant: Some(Entrant {
id: Some(9410060),
name: Some("tyrese".to_string()),
}),
seed: Some(Seed {
seedNum: Some(10),
entrant: None,
}),
standing: Some(Standing {
entrant: None,
player: None,
stats: Some(StandingStats {
score: Score { value: Some(0.0) },
}),
placement: None,
}),
},
],
completedAt: Some(1645848034),
phaseGroup: Some(PhaseGroup {
bracketType: "DOUBLE_ELIMINATION".to_string(),
}),
event: Some(Event {
id: Some(685122),
slug: Some(
"tournament/vsb-novice-friday-17/event/novice-ultimate-singles-bc-cooler-set"
.to_string(),
),
phases: None,
name: Some("Novice Ultimate Singles (BC Cooler Set 😎)".to_string()),
numEntrants: Some(12),
isOnline: Some(false),
videogame: Some(Videogame {
name: "Super Smash Bros. Ultimate".to_string(),
}),
tournament: Some(Tournament {
id: 423456,
name: "VSB - Novice Friday #17".to_string(),
endAt: Some(1645862340),
}),
standings: Some(StandingConnection {
nodes: vec![Standing {
entrant: Some(Entrant {
id: Some(9410060),
name: None,
}),
player: Some(Player {
id: 2021528,
prefix: None,
gamerTag: None,
user: Some(User {
name: None,
location: None,
bio: None,
birthday: None,
images: None,
slug: Some("user/1f1bee01".to_string()),
genderPronoun: None,
authorizations: None,
}),
rankings: None,
sets: None,
}),
stats: None,
placement: Some(5),
}],
}),
teamRosterSize: None,
}),
}
}
34 changes: 34 additions & 0 deletions lib/src/error_logs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,37 @@ pub fn insert_error_log(err: String) -> Result<()> {
.execute(&mut db_connection)?;
Ok(())
}

#[cfg(test)]
mod tests {
#![allow(unused)]
use super::*;

#[test]
#[cfg(feature = "skip_db_tests")]
fn test_insert_error_log() -> Result<()> {
// get count of all error_logs w/ "test error" message
let mut db_connection = smithe_database::connect().unwrap();
let err_logs = error_logs.filter(error_message.eq("test error"));
let count = err_logs
.count()
.get_result::<i64>(&mut db_connection)
.unwrap();

// insert error
let err = "test error".to_string();
insert_error_log(err.clone())?;

// get count again and check that it increased by 1
let new_count = err_logs
.count()
.get_result::<i64>(&mut db_connection)
.unwrap();
assert_eq!(new_count, count + 1);

// delete all error_logs w/ "test error" message
diesel::delete(err_logs).execute(&mut db_connection)?;

Ok(())
}
}
Loading

0 comments on commit 0a7edad

Please sign in to comment.