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 tests and refactor #73

Merged
merged 1 commit into from
Mar 1, 2024
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
6 changes: 6 additions & 0 deletions .github/workflows/tests.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,12 @@ jobs:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
TAURI_PRIVATE_KEY: ${{ secrets.TAURI_PRIVATE_KEY }}
TAURI_KEY_PASSWORD: ${{ secrets.TAURI_KEY_PASSWORD }}

- name: Run Rust tests
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd recommend adding check, fmt, and clippy here as well for some general linting of the Rust code. There's an example of the setup here: https://github.com/ryantaylor/vault/blob/master/.github/workflows/checks.yml

Copy link
Member Author

@petrvecera petrvecera Mar 1, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reported as #74

run: |
cd src-tauri
cargo test --package coh3-stats-desktop-app --lib

- name: Upload Tauri app artifacts
uses: actions/upload-artifact@v3
with:
Expand Down
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ yarn-error.log*
pnpm-debug.log*
lerna-debug.log*

!src-tauri/test_assets/**.log

node_modules
dist
dist-ssr
Expand Down
8 changes: 5 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -157,13 +157,15 @@ To build the app and an installer run:
yarn tauri build
```

Running tests:
```
cargo test --package coh3-stats-desktop-app --lib
```

The build output can be found in `src-tauri/target/release`. The installer can be found in `src-tauri/target/release/bundle/msi`.

Don't forget to run prettier with `yarn fix`.

On MacOS you need to comment out this line in main.rs around line 57
```.plugin(tauri_plugin_window_state::Builder::default().build())```

### Release
- Increase the version in files:
- `package.json`
Expand Down
6 changes: 6 additions & 0 deletions src-tauri/src/config.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
// Streamer overlay local PORT
pub const OVERLAY_PORT:&str = "47824";

// COHDB Auth
pub const COHDB_CLIENT_ID:&str = "kHERjpU_rXcvgvLgwPir0w3bqcgETLOH-p95-PVxN-M";
pub const COHDB_REDIRECT_URI:&str = "coh3stats://cohdb.com/oauth/authorize";
1 change: 1 addition & 0 deletions src-tauri/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@ pub mod parse_log_file;
pub mod plugins;
pub mod overlay_server;
pub mod dp_utils;
pub mod config;
33 changes: 21 additions & 12 deletions src-tauri/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,9 @@

extern crate machine_uid;

use coh3_stats_desktop_app::config::{COHDB_CLIENT_ID, COHDB_REDIRECT_URI};
use coh3_stats_desktop_app::dp_utils::load_from_store;
use coh3_stats_desktop_app::{parse_log_file, plugins::cohdb, overlay_server::run_http_server};
use coh3_stats_desktop_app::{overlay_server::run_http_server, parse_log_file, plugins::cohdb};
use log::{error, info};
use std::path::Path;
use std::thread;
Expand All @@ -24,12 +25,15 @@ fn main() {
tauri_plugin_deep_link::prepare("com.coh3stats.desktop");

// Add monitoring using sentry
// Monitoring is disabled on MacOS because we do only development on MacOS
// if you want to recieve sentry events on MacOS, remove the cfg attribute
#[cfg(not(target_os = "macos"))]
let _guard = sentry::init(("https://5a9a5418c06b995fe1c6221c83451612@o4504995920543744.ingest.sentry.io/4506676182646784", sentry::ClientOptions {
release: sentry::release_name!(),
..Default::default()
}));

tauri::Builder::default()
let builder = tauri::Builder::default()
.invoke_handler(tauri::generate_handler![
default_log_file_path,
default_playback_path,
Expand All @@ -56,32 +60,37 @@ fn main() {
}))
.plugin(tauri_plugin_fs_watch::init())
// You need to comment out this line to run the app on MacOS
.plugin(tauri_plugin_window_state::Builder::default().build())
// do not compile on mac
.plugin(tauri_plugin_store::Builder::default().build())
.plugin(cohdb::auth::init(
"kHERjpU_rXcvgvLgwPir0w3bqcgETLOH-p95-PVxN-M".to_string(),
"coh3stats://cohdb.com/oauth/authorize".to_string(),
COHDB_CLIENT_ID.to_string(),
COHDB_REDIRECT_URI.to_string(),
))
.plugin(coh3_stats_desktop_app::plugins::cohdb::sync::init())
.plugin(coh3_stats_desktop_app::plugins::cohdb::sync::init());

#[cfg(not(target_os = "macos"))]
let builder = builder.plugin(tauri_plugin_window_state::Builder::default().build());

builder
.setup(setup)
.run(tauri::generate_context!())
.expect("error while running tauri application");

}

fn setup(app: &mut tauri::App) -> Result<(), Box<dyn std::error::Error>> {
let handle = app.handle();

if load_from_store(handle.clone(), "streamerOverlayEnabled").unwrap_or(false) {
if load_from_store(handle.clone(), "streamerOverlayEnabled").unwrap_or(false) {
info!("Streamer overlay server is enabled");
let mut file_path = handle.path_resolver().app_data_dir().unwrap();
let mut file_path = handle.path_resolver().app_data_dir().unwrap();
file_path.push("streamerOverlay.html");
info!("Expecting the streamerOverlay at {:?}", file_path);

let _handle = thread::spawn(|| {
let _handle = thread::spawn(|| {
run_http_server(file_path);
});
} else {
});

} else {
info!("Streamer overlay server is disabled");
}

Expand Down
55 changes: 26 additions & 29 deletions src-tauri/src/overlay_server.rs
Original file line number Diff line number Diff line change
@@ -1,37 +1,34 @@
use std::fs::File;
use std::panic;
use log::{error, info};
use std::fs::File;
use std::path::PathBuf;

use tiny_http::{Server, Response, StatusCode};

pub fn run_http_server(streamer_overlay_path: PathBuf) {

let result = panic::catch_unwind(|| {
use tiny_http::{Response, Server, StatusCode};

// Ideally we would allow setting up port in the settings
info!("Starting streamer overlay server on port 47824");
let server = Server::http("127.0.0.1:47824").unwrap();
use crate::config::OVERLAY_PORT;

for request in server.incoming_requests() {

let file = match File::open(&streamer_overlay_path) {
Ok(file) => file,
Err(_) => {
let response = Response::new_empty(StatusCode(404));
let _ = request.respond(response);
continue;
}
};

let response = Response::from_file(file);
let _ = request.respond(response);
}

});
pub fn run_http_server(streamer_overlay_path: PathBuf) {
// Ideally we would allow setting up port in the settings
info!("Starting streamer overlay server on port {}", OVERLAY_PORT);

if let Err(err) = result {
let server = match Server::http(format!("127.0.0.1:{}", OVERLAY_PORT)) {
Ok(server) => server,
Err(err) => {
error!("Couldn't start the streamer overlay server: {:?}", err);
}

return;
}
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not necessary to do here I'd say, but it probably makes sense to find all the error! log calls and send them to your monitoring tool too eventually.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yep 👍

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

#75

};

for request in server.incoming_requests() {
let file = match File::open(&streamer_overlay_path) {
Ok(file) => file,
Err(_) => {
let response = Response::new_empty(StatusCode(404));
let _ = request.respond(response);
continue;
}
};

let response = Response::from_file(file);
let _ = request.respond(response);
}
}
31 changes: 8 additions & 23 deletions src-tauri/src/parse_log_file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,30 +2,32 @@ use log::info;
use rev_lines::RawRevLines;
use serde::{Deserialize, Serialize};
use std::fs::File;
#[cfg(test)]
mod tests;

#[derive(Serialize, Deserialize, Clone)]
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
pub enum GameState {
Closed,
Menu,
Loading,
InGame,
}

#[derive(Serialize, Deserialize, Clone)]
#[derive(Serialize, Deserialize, Clone, Debug)]
pub enum GameType {
Classic,
AI,
Custom,
}

#[derive(Serialize, Deserialize, Clone, PartialEq)]
#[derive(Serialize, Deserialize, Clone, PartialEq, Debug)]
pub enum TeamSide {
Axis,
Allies,
Mixed,
}

#[derive(Serialize, Deserialize, Clone)]
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct PlayerData {
pub ai: bool,
pub faction: String,
Expand All @@ -36,13 +38,13 @@ pub struct PlayerData {
pub rank: i64,
}

#[derive(Serialize, Deserialize, Clone)]
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct TeamData {
pub players: Vec<PlayerData>,
pub side: TeamSide,
}

#[derive(Serialize, Deserialize, Clone)]
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct LogFileData {
pub game_state: GameState,
pub game_type: GameType,
Expand Down Expand Up @@ -446,20 +448,3 @@ fn get_without_leading_space(line: &str) -> nom::IResult<&str, ()> {
};
Ok(("without_space", ()))
}*/

#[cfg(test)]
mod tests {
use super::parse_log_file_reverse;

#[test]
fn test_parse_log_file_reverse() {
println!("{}", file!());
parse_log_file_reverse("tests/warnings.log".to_string());
}

#[test]
fn test_parse_log_file_reverse_big_file() {
println!("{}", file!());
parse_log_file_reverse("tests/warnings-2mb.log".to_string());
}
}
45 changes: 45 additions & 0 deletions src-tauri/src/parse_log_file/tests.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
use crate::parse_log_file::{parse_log_file_reverse, GameState};


// TODO: Add more assertions and tests for parsing the log files

#[test]
fn test_parse_log_file_reverse_file_1() {
// println!("{}", file!());
let result = parse_log_file_reverse("./test_assets/warnings-1.log".to_string());
assert_eq!(result.game_state, GameState::Closed);
// can't compare for some reason
// assert_eq!(result.game_type, GameType::Custom);

assert_eq!(result.duration, 2217);
assert_eq!(result.map, "winter_line_8p_mkii");
assert_eq!(result.win_condition, "VictoryPoint");

// assert some results
// assert_eq!(result.len(), 3);
// print!("{:#?}", result);
}

#[test]
fn test_parse_log_file_reverse_file_2() {
println!("{}", file!());
let result = parse_log_file_reverse("./test_assets/warnings-2.log".to_string());
assert_eq!(result.game_state, GameState::Closed);

// TODO: add more assertions

// print!("{:#?}", result);
}

#[test]
fn test_parse_log_file_reverse_file_3() {
println!("{}", file!());
let result = parse_log_file_reverse("./test_assets/warnings-3.log".to_string());
assert_eq!(result.game_state, GameState::Closed);

assert_eq!(result.map, "desert_village_2p_mkiii");
// TODO: add more assertions


// print!("{:#?}", result);
}
Loading
Loading