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

State management tests #116

Closed
wants to merge 8 commits into from
Closed
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
11 changes: 9 additions & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ pre-release-hook = ["cargo", "fmt"]
dependent-version = "upgrade"

[workspace.dependencies]
atspi = { version = "0.14.1", features = ["tokio", "unstable-traits"] }
atspi = { version = "0.15.1", features = ["tokio", "unstable-traits"] }
odilia-common = { version = "0.3.0", path = "./common" }
odilia-cache = { version = "0.3.0", path = "./cache" }
eyre = "0.6.8"
Expand Down
1 change: 1 addition & 0 deletions cache/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ zbus.workspace = true
async-trait = "0.1.64"
fxhash = "0.2.1"
smartstring = { version = "1.0.1", features = ["serde"] }
arrayvec = "0.7.2"

[dev-dependencies]
criterion = { version = "0.4.0", features = ["async_tokio", "html_reports"] }
Expand Down
21 changes: 15 additions & 6 deletions cache/benches/load_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use std::{

use atspi::{accessible::Accessible, AccessibilityConnection};
use criterion::{criterion_group, criterion_main, BatchSize, BenchmarkId, Criterion};
use odilia_cache::{clone_arc_mutex, AccessiblePrimitive, Cache, CacheItem};
use odilia_cache::{AccessiblePrimitive, Cache, CacheItem};

use odilia_common::errors::{CacheError, OdiliaError};
use tokio::select;
Expand Down Expand Up @@ -42,7 +42,7 @@ async fn traverse_up_refs(children: Vec<Arc<RwLock<CacheItem>>>) {
loop {
let item_ref_copy = Arc::clone(&item_ref);
let mut item = item_ref_copy.write().expect("Could not lock item");
let root_ = ROOT_A11Y.clone();
let root_ = ROOT_A11Y.clone();
if matches!(&item.object.id, root_) {
break;
}
Expand Down Expand Up @@ -70,8 +70,8 @@ async fn traverse_up(children: Vec<CacheItem>) {
panic!("Odilia error {:?}", e);
}
};
let root_ = ROOT_A11Y.clone();
if matches!(item.object.id, root_) {
let root_ = ROOT_A11Y.clone();
if matches!(item.object.id.clone(), root_) {
break;
}
}
Expand Down Expand Up @@ -219,7 +219,16 @@ fn cache_benchmark(c: &mut Criterion) {

group.bench_function(BenchmarkId::new("traverse_up", "wcag-items"), |b| {
b.to_async(&rt).iter_batched(
|| children.iter().map(clone_arc_mutex).collect(),
|| {
children.iter()
.map(|a_rw_item| {
Arc::clone(a_rw_item)
.read()
.expect("Could not read a cache item.")
.clone()
})
.collect()
},
|cs| async { traverse_up(cs).await },
BatchSize::SmallInput,
);
Expand All @@ -229,7 +238,7 @@ fn cache_benchmark(c: &mut Criterion) {
b.iter_batched(
|| {
cache.get(&AccessiblePrimitive {
id: "/org/a11y/atspi/accessible/root".to_string(),
id: "/org/a11y/atspi/accessible/root".into(),
sender: ":1.22".into(),
})
.unwrap()
Expand Down
53 changes: 25 additions & 28 deletions cache/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,18 +44,18 @@ type ThreadSafeCache = Arc<InnerCache>;
/// This makes some *possibly eronious* assumptions about what the sender is.
pub struct AccessiblePrimitive {
/// The accessible ID, which is an arbitrary string specified by the application.
/// It is guarenteed to be unique per application.
/// Examples:
/// * /org/a11y/atspi/accessible/1234
/// * /org/a11y/atspi/accessible/null
/// * /org/a11y/atspi/accessible/root
/// * /org/Gnome/GTK/abab22-bbbb33-2bba2
pub id: String,
/// It is guarenteed to be unique per application.
/// Examples:
/// * /org/a11y/atspi/accessible/1234
/// * /org/a11y/atspi/accessible/null
/// * /org/a11y/atspi/accessible/root
/// * /org/Gnome/GTK/abab22-bbbb33-2bba2
pub id: smartstring::alias::String,
/// Assuming that the sender is ":x.y", this stores the (x,y) portion of this sender.
/// Examples:
/// * :1.1 (the first window has opened)
/// * :2.5 (a second session exists, where at least 5 applications have been lauinched)
/// * :1.262 (many applications have been started on this bus)
/// Examples:
/// * :1.1 (the first window has opened)
/// * :2.5 (a second session exists, where at least 5 applications have been lauinched)
/// * :1.262 (many applications have been started on this bus)
pub sender: smartstring::alias::String,
}
impl AccessiblePrimitive {
Expand All @@ -68,7 +68,7 @@ impl AccessiblePrimitive {
) -> zbus::Result<AccessibleProxy<'a>> {
let id = self.id;
let sender = self.sender.clone();
let path: ObjectPath<'a> = id.try_into()?;
let path: OwnedObjectPath = OwnedObjectPath::try_from(id.as_str())?;
ProxyBuilder::new(conn)
.path(path)?
.destination(sender.as_str().to_owned())?
Expand All @@ -82,7 +82,7 @@ impl AccessiblePrimitive {
pub async fn into_text<'a>(self, conn: &zbus::Connection) -> zbus::Result<TextProxy<'a>> {
let id = self.id;
let sender = self.sender.clone();
let path: ObjectPath<'a> = id.try_into()?;
let path: OwnedObjectPath = OwnedObjectPath::try_from(id.as_str())?;
ProxyBuilder::new(conn)
.path(path)?
.destination(sender.as_str().to_owned())?
Expand All @@ -101,7 +101,7 @@ impl AccessiblePrimitive {
.map_err(|_| AccessiblePrimitiveConversionError::ErrSender)?
.ok_or(AccessiblePrimitiveConversionError::NoSender)?;
let path = event.path().ok_or(AccessiblePrimitiveConversionError::NoPathId)?;
let id = path.to_string();
let id = path.as_str().into();
Ok(Self { id, sender: sender.as_str().into() })
}
}
Expand All @@ -121,28 +121,30 @@ impl TryFrom<(OwnedUniqueName, OwnedObjectPath)> for AccessiblePrimitive {
fn try_from(
so: (OwnedUniqueName, OwnedObjectPath),
) -> Result<AccessiblePrimitive, Self::Error> {
let accessible_id= so.1;
Ok(AccessiblePrimitive { id: accessible_id.to_string(), sender: so.0.as_str().into() })
let accessible_id = so.1;
Ok(AccessiblePrimitive {
id: accessible_id.as_str().into(),
sender: so.0.as_str().into(),
})
}
}
impl From<(String, OwnedObjectPath)> for AccessiblePrimitive {

fn from(so: (String, OwnedObjectPath)) -> AccessiblePrimitive {
let accessible_id = so.1;
AccessiblePrimitive { id: accessible_id.to_string(), sender: so.0.into() }
AccessiblePrimitive { id: accessible_id.as_str().into(), sender: so.0.into() }
}
}
impl<'a> From<(String, ObjectPath<'a>)> for AccessiblePrimitive {
fn from(so: (String, ObjectPath<'a>)) -> AccessiblePrimitive {
AccessiblePrimitive { id: so.1.to_string(), sender: so.0.into() }
AccessiblePrimitive { id: so.1.as_str().into(), sender: so.0.into() }
}
}
impl<'a> TryFrom<&AccessibleProxy<'a>> for AccessiblePrimitive {
type Error = AccessiblePrimitiveConversionError;

fn try_from(accessible: &AccessibleProxy<'_>) -> Result<AccessiblePrimitive, Self::Error> {
let sender = accessible.destination().as_str().into();
let id = accessible.path().as_str().into();
let id = accessible.path().as_str().into();
Ok(AccessiblePrimitive { id, sender })
}
}
Expand All @@ -151,7 +153,7 @@ impl<'a> TryFrom<AccessibleProxy<'a>> for AccessiblePrimitive {

fn try_from(accessible: AccessibleProxy<'_>) -> Result<AccessiblePrimitive, Self::Error> {
let sender = accessible.destination().as_str().into();
let id = accessible.path().as_str().into();
let id = accessible.path().as_str().into();
Ok(AccessiblePrimitive { id, sender })
}
}
Expand Down Expand Up @@ -237,9 +239,7 @@ impl CacheItem {
.get_children()
.await?
.into_iter()
.map(|child_object_pair| {
CacheRef::new(child_object_pair.into())
})
.map(|child_object_pair| CacheRef::new(child_object_pair.into()))
.collect();
Ok(Self {
object: atspi_cache_item.object.try_into()?,
Expand Down Expand Up @@ -902,10 +902,7 @@ pub async fn accessible_to_cache_item(
role,
states,
text,
children: children
.into_iter()
.map(|k| CacheRef::new(k.into()))
.collect(),
children: children.into_iter().map(|k| CacheRef::new(k.into())).collect(),
cache,
})
}
4 changes: 4 additions & 0 deletions common/src/settings/invalid-config.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
[speech]
rate=100

[log]
4 changes: 2 additions & 2 deletions common/src/settings/log.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
use serde::{Deserialize, Serialize};
///structure used for all the configurable options related to logging
#[derive(Debug, Serialize, Deserialize)]
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq)]
#[allow(clippy::module_name_repetitions)]
pub struct LogSettings {
level: String,
pub level: String,
}
impl LogSettings {
pub fn new(level: String) -> Self {
Expand Down
52 changes: 47 additions & 5 deletions common/src/settings/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,26 +11,44 @@ use crate::errors::ConfigError;
///type representing a *read-only* view of the odilia screenreader configuration
/// this type should only be obtained as a result of parsing odilia's configuration files, as it containes types for each section responsible for controlling various parts of the screenreader
/// the only way this config should change is if the configuration file changes, in which case the entire view will be replaced to reflect the fact
#[derive(Debug, Serialize, Deserialize)]
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq)]
pub struct ApplicationConfig {
speech: SpeechSettings,
log: LogSettings,
}

impl ApplicationConfig {
/// Opens a new config file with a certain path.
/// Uses a [`tini`] structure to build the config. This is only used internally to create a common function.
///
/// # Errors
///
/// This can return `Err(_)` if the path doesn't exist, or if not all the key/value pairs are defined.
pub fn new(path: &str) -> Result<Self, ConfigError> {
let ini = Ini::from_file(path)?;
/// This can return `Err(_)` if not all the key/value pairs are defined.
fn from_ini(ini: &Ini) -> Result<Self, ConfigError> {
let rate: i32 = ini.get("speech", "rate").ok_or(ConfigError::ValueNotFound)?;
let level: String = ini.get("log", "level").ok_or(ConfigError::ValueNotFound)?;
let speech = SpeechSettings::new(rate);
let log = LogSettings::new(level);
Ok(Self { speech, log })
}
/// Opens a new config file with a certain path.
///
/// # Errors
///
/// This can return `Err(_)` if the path doesn't exist, or if not all the key/value pairs are defined.
pub fn from_path(path: &str) -> Result<Self, ConfigError> {
let ini = Ini::from_file(path)?;
Self::from_ini(&ini)
}

/// Uses the text given to create a config structure.
///
/// # Errors
///
/// This can return `Err(_)` if not all the key/value pairs are defined.
pub fn from_string(config_str: &str) -> Result<Self, ConfigError> {
let ini = Ini::from_string(config_str)?;
Self::from_ini(&ini)
}

#[must_use]
pub fn log(&self) -> &LogSettings {
Expand All @@ -42,3 +60,27 @@ impl ApplicationConfig {
&self.speech
}
}

#[cfg(test)]
mod tests {
use crate::settings::{ApplicationConfig, LogSettings, SpeechSettings};

#[test]
fn check_valid_config() {
let config =
ApplicationConfig::from_string(include_str!("../../../odilia/config.toml"));
assert_eq!(
config.unwrap(),
ApplicationConfig {
speech: SpeechSettings { rate: 100 },
log: LogSettings { level: "debug".to_string() },
}
)
}

#[test]
fn check_invalid_config() {
let config = ApplicationConfig::from_string(include_str!("./invalid-config.toml"));
assert_eq!(config.is_err(), true)
}
}
2 changes: 1 addition & 1 deletion common/src/settings/speech.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use serde::{Deserialize, Serialize};
///structure for all the speech related configuration options available in odilia
#[derive(Debug, Serialize, Deserialize)]
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq)]
#[allow(clippy::module_name_repetitions)]
pub struct SpeechSettings {
pub rate: i32,
Expand Down
2 changes: 1 addition & 1 deletion odilia/config.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@
rate=100

[log]
level="debug"
level=debug
Loading