Fix concurrency bug while testing

This commit is contained in:
2022-01-17 17:09:54 +01:00
parent c43dc135ac
commit 5c6471aea9
9 changed files with 67 additions and 44 deletions

View File

@@ -38,7 +38,7 @@ jobs:
- uses: actions-rs/clippy-check@v1
with:
token: ${{ secrets.GITHUB_TOKEN }}
args: -- -D warnings
args: --tests -- -D warnings
- name: Run cargo-tarpaulin
uses: ./.github/actions/cargo-tarpaulin-action/

15
Cargo.lock generated
View File

@@ -332,9 +332,9 @@ dependencies = [
"lazy_static",
"listenfd",
"mktemp",
"once_cell",
"regex",
"reqwest",
"rstest",
"serde",
"serde_json",
"tokio",
@@ -1214,6 +1214,19 @@ dependencies = [
"winreg",
]
[[package]]
name = "rstest"
version = "0.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d912f35156a3f99a66ee3e11ac2e0b3f34ac85a07e05263d05a7e2c8810d616f"
dependencies = [
"cfg-if",
"proc-macro2",
"quote",
"rustc_version",
"syn",
]
[[package]]
name = "rustc_version"
version = "0.4.0"

View File

@@ -33,5 +33,5 @@ lazy_static = "1.4.0"
tracing-bunyan-formatter = "0.3.2"
[dev-dependencies]
once_cell = "1.0"
reqwest = { version = "0.11.0", features = ["json"] }
rstest = "0.12.0"

View File

@@ -44,6 +44,6 @@ pub fn export(filters: Vec<&str>) -> Result<Vec<Task>, Error> {
tasks
}
pub fn add(add_args: Vec<&str>) -> Result<u64, Error> {
taskwarrior::add(add_args)
pub async fn add(add_args: Vec<&str>) -> Result<u64, Error> {
taskwarrior::add(add_args).await
}

View File

@@ -1,7 +1,7 @@
use actix_web::{dev::Server, http, middleware, web, App, HttpResponse, HttpServer};
use contextswitch_types::TaskDefinition;
use listenfd::ListenFd;
use serde::{Deserialize, Serialize};
use serde::Deserialize;
use serde_json::json;
use std::env;
use std::io::Error;
@@ -35,7 +35,7 @@ async fn list_tasks(task_query: web::Query<TaskQuery>) -> Result<HttpResponse, E
#[tracing::instrument(level = "debug", skip_all, fields(definition = %task_definition.definition))]
async fn add_task(task_definition: web::Json<TaskDefinition>) -> Result<HttpResponse, Error> {
let task_id = contextswitch::add(task_definition.definition.split(' ').collect())?;
let task_id = contextswitch::add(task_definition.definition.split(' ').collect()).await?;
Ok(HttpResponse::Ok()
.content_type("application/json")

View File

@@ -8,6 +8,7 @@ use std::io::{Error, ErrorKind};
use std::path::Path;
use std::process::Command;
use std::str;
use tokio::sync::Mutex;
use tracing::debug;
use uuid::Uuid;
@@ -109,14 +110,17 @@ pub fn export(filters: Vec<&str>) -> Result<Vec<Task>, Error> {
}
#[tracing::instrument(level = "debug")]
pub fn add(add_args: Vec<&str>) -> Result<u64, Error> {
pub async fn add(add_args: Vec<&str>) -> Result<u64, Error> {
lazy_static! {
static ref RE: Regex = Regex::new(r"Created task (?P<id>\d+).").unwrap();
static ref LOCK: Mutex<u32> = Mutex::new(0);
}
let _lock = LOCK.lock().await;
let mut args = vec!["add"];
args.extend(add_args);
let add_output = Command::new("task").args(args).output()?;
let output = String::from_utf8(add_output.stdout).unwrap();
lazy_static! {
static ref RE: Regex = Regex::new(r"Created task (?P<id>\d+).").unwrap();
}
let task_id_capture = RE.captures(&output).ok_or_else(|| {
Error::new(
ErrorKind::Other,

View File

@@ -1,12 +1,12 @@
pub mod test_helper;
use rstest::*;
use test_helper::app_address;
#[rstest]
#[tokio::test]
async fn health_check_works() {
let address = test_helper::spawn_app();
let client = reqwest::Client::new();
let response = client
.get(&format!("{}/ping", &address))
async fn health_check_works(app_address: &str) {
let response = reqwest::Client::new()
.get(&format!("{}/ping", &app_address))
.send()
.await
.expect("Failed to execute request.");

View File

@@ -3,15 +3,19 @@ pub mod test_helper;
use contextswitch_api::taskwarrior;
use contextswitch_types::Task;
use contextswitch_types::TaskDefinition;
use rstest::*;
use test_helper::app_address;
#[rstest]
#[tokio::test]
async fn list_tasks() {
let address = test_helper::spawn_app();
let task_id =
taskwarrior::add(vec!["test", "list_tasks", "contextswitch:'{\"test\": 1}'"]).unwrap();
async fn list_tasks(app_address: &str) {
let task_id = taskwarrior::add(vec!["test", "list_tasks", "contextswitch:'{\"test\": 1}'"])
.await
.unwrap();
println!("LIST TASKS ID: {}", task_id);
let tasks: Vec<Task> = reqwest::Client::new()
.get(&format!("{}/tasks?filter={}", &address, task_id))
.get(&format!("{}/tasks?filter={}", &app_address, task_id))
.send()
.await
.expect("Failed to execute request")
@@ -25,13 +29,11 @@ async fn list_tasks() {
assert_eq!(cs_metadata.test, 1);
}
#[rstest]
#[tokio::test]
async fn add_task() {
let address = test_helper::spawn_app();
println!("add_task address: {}", address);
async fn add_task(app_address: &str) {
let response: serde_json::Value = reqwest::Client::new()
.post(&format!("{}/tasks", &address))
.post(&format!("{}/tasks", &app_address))
.json(&TaskDefinition {
definition: "test add_task contextswitch:{\"test\":1}".to_string(),
})
@@ -41,8 +43,10 @@ async fn add_task() {
.json()
.await
.expect("Cannot parse JSON result");
println!("ADD RESPONSE: {:?}", response);
let new_task_id = response["id"].as_u64().unwrap();
let tasks = taskwarrior::export(vec![&new_task_id.to_string()]).unwrap();
println!("TASKS={:?}", tasks);
assert_eq!(tasks.len(), 1);
assert_eq!(tasks[0].id, new_task_id);

View File

@@ -1,42 +1,44 @@
use contextswitch_api::observability::{get_subscriber, init_subscriber};
use contextswitch_api::taskwarrior;
use mktemp::Temp;
use once_cell::sync::Lazy;
use rstest::*;
use std::fs;
use std::net::TcpListener;
use tracing::info;
static TRACING: Lazy<()> = Lazy::new(|| {
let subscriber = get_subscriber("info".to_string());
fn setup_tracing() {
info!("Setting up tracing");
let subscriber = get_subscriber("debug".to_string());
init_subscriber(subscriber);
});
}
static SERVER_ADDRESS: Lazy<String> = Lazy::new(|| {
fn setup_server() -> String {
info!("Setting up server");
let listener = TcpListener::bind("127.0.0.1:0").expect("Failed to bind random port");
let port = listener.local_addr().unwrap().port();
let server = contextswitch_api::run(listener).expect("Failed to bind address");
let _ = tokio::spawn(server);
format!("http://127.0.0.1:{}", port)
});
}
static TASK_DATA_LOCATION: Lazy<String> = Lazy::new(|| {
fn setup_taskwarrior() -> String {
info!("Setting up TW");
let tmp_dir = Temp::new_dir().unwrap();
let task_data_location = taskwarrior::load_config(tmp_dir.to_str());
tmp_dir.release();
task_data_location
});
pub fn spawn_app() -> String {
Lazy::force(&TRACING);
setup_tasks();
Lazy::force(&SERVER_ADDRESS).to_string()
}
pub fn setup_tasks() -> String {
Lazy::force(&TASK_DATA_LOCATION).to_string()
}
pub fn clear_tasks(task_data_location: String) {
fs::remove_dir_all(task_data_location).unwrap();
}
#[fixture]
#[once]
pub fn app_address() -> String {
setup_tracing();
setup_taskwarrior();
setup_server()
}