Uses anyhow context function more often

pull/649/head
Tpt 1 year ago committed by Thomas Tanon
parent 517df6d59e
commit ef429e6d1b
  1. 20
      cli/src/main.rs
  2. 4
      testsuite/src/files.rs
  3. 54
      testsuite/src/parser_evaluator.rs
  4. 76
      testsuite/src/sparql_evaluator.rs

@ -1,5 +1,5 @@
#![allow(clippy::print_stderr, clippy::cast_precision_loss, clippy::use_debug)] #![allow(clippy::print_stderr, clippy::cast_precision_loss, clippy::use_debug)]
use anyhow::{anyhow, bail, ensure, Context}; use anyhow::{bail, ensure, Context};
use clap::{Parser, Subcommand, ValueHint}; use clap::{Parser, Subcommand, ValueHint};
use flate2::read::MultiGzDecoder; use flate2::read::MultiGzDecoder;
use oxhttp::model::{Body, HeaderName, HeaderValue, Method, Request, Response, Status}; use oxhttp::model::{Body, HeaderName, HeaderValue, Method, Request, Response, Status};
@ -387,9 +387,7 @@ pub fn main() -> anyhow::Result<()> {
bulk_load( bulk_load(
&loader, &loader,
stdin().lock(), stdin().lock(),
format.ok_or_else(|| { format.context("The --format option must be set when loading from stdin")?,
anyhow!("The --format option must be set when loading from stdin")
})?,
base.as_deref(), base.as_deref(),
graph, graph,
) )
@ -547,8 +545,9 @@ pub fn main() -> anyhow::Result<()> {
} }
} else if let Some(results_file) = &results_file { } else if let Some(results_file) = &results_file {
format_from_path(results_file, |ext| { format_from_path(results_file, |ext| {
QueryResultsFormat::from_extension(ext) QueryResultsFormat::from_extension(ext).with_context(|| {
.ok_or_else(|| anyhow!("The file extension '{ext}' is unknown")) format!("The file extension '{ext}' is unknown")
})
})? })?
} else { } else {
bail!("The --results-format option must be set when writing to stdout") bail!("The --results-format option must be set when writing to stdout")
@ -587,8 +586,9 @@ pub fn main() -> anyhow::Result<()> {
} }
} else if let Some(results_file) = &results_file { } else if let Some(results_file) = &results_file {
format_from_path(results_file, |ext| { format_from_path(results_file, |ext| {
QueryResultsFormat::from_extension(ext) QueryResultsFormat::from_extension(ext).with_context(|| {
.ok_or_else(|| anyhow!("The file extension '{ext}' is unknown")) format!("The file extension '{ext}' is unknown")
})
})? })?
} else { } else {
bail!("The --results-format option must be set when writing to stdout") bail!("The --results-format option must be set when writing to stdout")
@ -701,7 +701,7 @@ pub fn main() -> anyhow::Result<()> {
if let Some(base) = from_base { if let Some(base) = from_base {
parser = parser parser = parser
.with_base_iri(&base) .with_base_iri(&base)
.with_context(|| anyhow!("Invalid base IRI {base}"))?; .with_context(|| format!("Invalid base IRI {base}"))?;
} }
let to_format = if let Some(format) = to_format { let to_format = if let Some(format) = to_format {
@ -864,7 +864,7 @@ fn format_from_path<T>(
fn rdf_format_from_path(path: &Path) -> anyhow::Result<RdfFormat> { fn rdf_format_from_path(path: &Path) -> anyhow::Result<RdfFormat> {
format_from_path(path, |ext| { format_from_path(path, |ext| {
RdfFormat::from_extension(ext) RdfFormat::from_extension(ext)
.ok_or_else(|| anyhow!("The file extension '{ext}' is unknown")) .with_context(|| format!("The file extension '{ext}' is unknown"))
}) })
} }

@ -1,4 +1,4 @@
use anyhow::{anyhow, bail, Context, Result}; use anyhow::{bail, Context, Result};
use oxigraph::io::{RdfFormat, RdfParser}; use oxigraph::io::{RdfFormat, RdfParser};
use oxigraph::model::{Dataset, Graph}; use oxigraph::model::{Dataset, Graph};
use oxttl::n3::N3Quad; use oxttl::n3::N3Quad;
@ -90,7 +90,7 @@ pub fn load_dataset(url: &str, format: RdfFormat, ignore_errors: bool) -> Result
pub fn guess_rdf_format(url: &str) -> Result<RdfFormat> { pub fn guess_rdf_format(url: &str) -> Result<RdfFormat> {
url.rsplit_once('.') url.rsplit_once('.')
.and_then(|(_, extension)| RdfFormat::from_extension(extension)) .and_then(|(_, extension)| RdfFormat::from_extension(extension))
.ok_or_else(|| anyhow!("Serialization type not found for {url}")) .with_context(|| format!("Serialization type not found for {url}"))
} }
pub fn load_n3(url: &str, ignore_errors: bool) -> Result<Vec<N3Quad>> { pub fn load_n3(url: &str, ignore_errors: bool) -> Result<Vec<N3Quad>> {

@ -2,7 +2,7 @@ use crate::evaluator::TestEvaluator;
use crate::files::{guess_rdf_format, load_dataset, load_n3, read_file_to_string}; use crate::files::{guess_rdf_format, load_dataset, load_n3, read_file_to_string};
use crate::manifest::Test; use crate::manifest::Test;
use crate::report::{dataset_diff, format_diff}; use crate::report::{dataset_diff, format_diff};
use anyhow::{anyhow, bail, ensure, Result}; use anyhow::{bail, ensure, Context, Result};
use oxigraph::io::RdfFormat; use oxigraph::io::RdfFormat;
use oxigraph::model::{BlankNode, Dataset, Quad}; use oxigraph::model::{BlankNode, Dataset, Quad};
use oxttl::n3::{N3Quad, N3Term}; use oxttl::n3::{N3Quad, N3Term};
@ -94,28 +94,19 @@ pub fn register_parser_tests(evaluator: &mut TestEvaluator) {
} }
fn evaluate_positive_syntax_test(test: &Test, format: RdfFormat) -> Result<()> { fn evaluate_positive_syntax_test(test: &Test, format: RdfFormat) -> Result<()> {
let action = test let action = test.action.as_deref().context("No action found")?;
.action load_dataset(action, format, false).context("Parse error")?;
.as_deref()
.ok_or_else(|| anyhow!("No action found"))?;
load_dataset(action, format, false).map_err(|e| anyhow!("Parse error: {e}"))?;
Ok(()) Ok(())
} }
fn evaluate_positive_n3_syntax_test(test: &Test) -> Result<()> { fn evaluate_positive_n3_syntax_test(test: &Test) -> Result<()> {
let action = test let action = test.action.as_deref().context("No action found")?;
.action load_n3(action, false).context("Parse error")?;
.as_deref()
.ok_or_else(|| anyhow!("No action found"))?;
load_n3(action, false).map_err(|e| anyhow!("Parse error: {e}"))?;
Ok(()) Ok(())
} }
fn evaluate_negative_syntax_test(test: &Test, format: RdfFormat) -> Result<()> { fn evaluate_negative_syntax_test(test: &Test, format: RdfFormat) -> Result<()> {
let action = test let action = test.action.as_deref().context("No action found")?;
.action
.as_deref()
.ok_or_else(|| anyhow!("No action found"))?;
let Err(error) = load_dataset(action, format, false) else { let Err(error) = load_dataset(action, format, false) else {
bail!("File parsed without errors even if it should not"); bail!("File parsed without errors even if it should not");
}; };
@ -131,10 +122,7 @@ fn evaluate_negative_syntax_test(test: &Test, format: RdfFormat) -> Result<()> {
} }
fn evaluate_negative_n3_syntax_test(test: &Test) -> Result<()> { fn evaluate_negative_n3_syntax_test(test: &Test) -> Result<()> {
let action = test let action = test.action.as_deref().context("No action found")?;
.action
.as_deref()
.ok_or_else(|| anyhow!("No action found"))?;
ensure!( ensure!(
load_n3(action, false).is_err(), load_n3(action, false).is_err(),
"File parsed without errors even if it should not" "File parsed without errors even if it should not"
@ -143,19 +131,13 @@ fn evaluate_negative_n3_syntax_test(test: &Test) -> Result<()> {
} }
fn evaluate_eval_test(test: &Test, format: RdfFormat, ignore_errors: bool) -> Result<()> { fn evaluate_eval_test(test: &Test, format: RdfFormat, ignore_errors: bool) -> Result<()> {
let action = test let action = test.action.as_deref().context("No action found")?;
.action
.as_deref()
.ok_or_else(|| anyhow!("No action found"))?;
let mut actual_dataset = load_dataset(action, format, ignore_errors) let mut actual_dataset = load_dataset(action, format, ignore_errors)
.map_err(|e| anyhow!("Parse error on file {action}: {e}"))?; .with_context(|| format!("Parse error on file {action}"))?;
actual_dataset.canonicalize(); actual_dataset.canonicalize();
let results = test let results = test.result.as_ref().context("No tests result found")?;
.result
.as_ref()
.ok_or_else(|| anyhow!("No tests result found"))?;
let mut expected_dataset = load_dataset(results, guess_rdf_format(results)?, false) let mut expected_dataset = load_dataset(results, guess_rdf_format(results)?, false)
.map_err(|e| anyhow!("Parse error on file {results}: {e}"))?; .with_context(|| format!("Parse error on file {results}"))?;
expected_dataset.canonicalize(); expected_dataset.canonicalize();
ensure!( ensure!(
expected_dataset == actual_dataset, expected_dataset == actual_dataset,
@ -166,20 +148,14 @@ fn evaluate_eval_test(test: &Test, format: RdfFormat, ignore_errors: bool) -> Re
} }
fn evaluate_n3_eval_test(test: &Test, ignore_errors: bool) -> Result<()> { fn evaluate_n3_eval_test(test: &Test, ignore_errors: bool) -> Result<()> {
let action = test let action = test.action.as_deref().context("No action found")?;
.action
.as_deref()
.ok_or_else(|| anyhow!("No action found"))?;
let mut actual_dataset = n3_to_dataset( let mut actual_dataset = n3_to_dataset(
load_n3(action, ignore_errors).map_err(|e| anyhow!("Parse error on file {action}: {e}"))?, load_n3(action, ignore_errors).with_context(|| format!("Parse error on file {action}"))?,
); );
actual_dataset.canonicalize(); actual_dataset.canonicalize();
let results = test let results = test.result.as_ref().context("No tests result found")?;
.result
.as_ref()
.ok_or_else(|| anyhow!("No tests result found"))?;
let mut expected_dataset = n3_to_dataset( let mut expected_dataset = n3_to_dataset(
load_n3(results, false).map_err(|e| anyhow!("Parse error on file {results}: {e}"))?, load_n3(results, false).with_context(|| format!("Parse error on file {results}"))?,
); );
expected_dataset.canonicalize(); expected_dataset.canonicalize();
ensure!( ensure!(

@ -3,7 +3,7 @@ use crate::files::*;
use crate::manifest::*; use crate::manifest::*;
use crate::report::{dataset_diff, format_diff}; use crate::report::{dataset_diff, format_diff};
use crate::vocab::*; use crate::vocab::*;
use anyhow::{anyhow, bail, ensure, Error, Result}; use anyhow::{bail, ensure, Context, Error, Result};
use oxigraph::model::vocab::*; use oxigraph::model::vocab::*;
use oxigraph::model::*; use oxigraph::model::*;
use oxigraph::sparql::results::QueryResultsFormat; use oxigraph::sparql::results::QueryResultsFormat;
@ -77,22 +77,16 @@ pub fn register_sparql_tests(evaluator: &mut TestEvaluator) {
} }
fn evaluate_positive_syntax_test(test: &Test) -> Result<()> { fn evaluate_positive_syntax_test(test: &Test) -> Result<()> {
let query_file = test let query_file = test.action.as_deref().context("No action found")?;
.action
.as_deref()
.ok_or_else(|| anyhow!("No action found"))?;
let query = Query::parse(&read_file_to_string(query_file)?, Some(query_file)) let query = Query::parse(&read_file_to_string(query_file)?, Some(query_file))
.map_err(|e| anyhow!("Not able to parse with error: {e}"))?; .context("Not able to parse")?;
Query::parse(&query.to_string(), None) Query::parse(&query.to_string(), None)
.map_err(|e| anyhow!("Failure to deserialize \"{query}\" with error: {e}"))?; .with_context(|| format!("Failure to deserialize \"{query}\""))?;
Ok(()) Ok(())
} }
fn evaluate_negative_syntax_test(test: &Test) -> Result<()> { fn evaluate_negative_syntax_test(test: &Test) -> Result<()> {
let query_file = test let query_file = test.action.as_deref().context("No action found")?;
.action
.as_deref()
.ok_or_else(|| anyhow!("No action found"))?;
ensure!( ensure!(
Query::parse(&read_file_to_string(query_file)?, Some(query_file)).is_err(), Query::parse(&read_file_to_string(query_file)?, Some(query_file)).is_err(),
"Oxigraph parses even if it should not." "Oxigraph parses even if it should not."
@ -101,10 +95,7 @@ fn evaluate_negative_syntax_test(test: &Test) -> Result<()> {
} }
fn evaluate_positive_result_syntax_test(test: &Test, format: QueryResultsFormat) -> Result<()> { fn evaluate_positive_result_syntax_test(test: &Test, format: QueryResultsFormat) -> Result<()> {
let action_file = test let action_file = test.action.as_deref().context("No action found")?;
.action
.as_deref()
.ok_or_else(|| anyhow!("No action found"))?;
let actual_results = StaticQueryResults::from_query_results( let actual_results = StaticQueryResults::from_query_results(
QueryResults::read(read_file(action_file)?, format)?, QueryResults::read(read_file(action_file)?, format)?,
true, true,
@ -124,10 +115,7 @@ fn evaluate_positive_result_syntax_test(test: &Test, format: QueryResultsFormat)
} }
fn evaluate_negative_result_syntax_test(test: &Test, format: QueryResultsFormat) -> Result<()> { fn evaluate_negative_result_syntax_test(test: &Test, format: QueryResultsFormat) -> Result<()> {
let action_file = test let action_file = test.action.as_deref().context("No action found")?;
.action
.as_deref()
.ok_or_else(|| anyhow!("No action found"))?;
ensure!( ensure!(
QueryResults::read(Cursor::new(read_file_to_string(action_file)?), format) QueryResults::read(Cursor::new(read_file_to_string(action_file)?), format)
.map_err(Error::from) .map_err(Error::from)
@ -146,18 +134,15 @@ fn evaluate_evaluation_test(test: &Test) -> Result<()> {
for (name, value) in &test.graph_data { for (name, value) in &test.graph_data {
load_graph_to_store(value, &store, name.clone())?; load_graph_to_store(value, &store, name.clone())?;
} }
let query_file = test let query_file = test.query.as_deref().context("No action found")?;
.query
.as_deref()
.ok_or_else(|| anyhow!("No action found"))?;
let options = QueryOptions::default() let options = QueryOptions::default()
.with_service_handler(StaticServiceHandler::new(&test.service_data)?); .with_service_handler(StaticServiceHandler::new(&test.service_data)?);
let query = Query::parse(&read_file_to_string(query_file)?, Some(query_file)) let query = Query::parse(&read_file_to_string(query_file)?, Some(query_file))
.map_err(|e| anyhow!("Failure to parse query with error: {e}"))?; .context("Failure to parse query")?;
// We check parsing roundtrip // We check parsing roundtrip
Query::parse(&query.to_string(), None) Query::parse(&query.to_string(), None)
.map_err(|e| anyhow!("Failure to deserialize \"{query}\" with error: {e}"))?; .with_context(|| format!("Failure to deserialize \"{query}\""))?;
// FROM and FROM NAMED support. We make sure the data is in the store // FROM and FROM NAMED support. We make sure the data is in the store
if !query.dataset().is_default_dataset() { if !query.dataset().is_default_dataset() {
@ -176,7 +161,7 @@ fn evaluate_evaluation_test(test: &Test) -> Result<()> {
} }
let expected_results = load_sparql_query_result(test.result.as_ref().unwrap()) let expected_results = load_sparql_query_result(test.result.as_ref().unwrap())
.map_err(|e| anyhow!("Error constructing expected graph: {e}"))?; .context("Error constructing expected graph")?;
let with_order = if let StaticQueryResults::Solutions { ordered, .. } = &expected_results { let with_order = if let StaticQueryResults::Solutions { ordered, .. } = &expected_results {
*ordered *ordered
} else { } else {
@ -190,7 +175,7 @@ fn evaluate_evaluation_test(test: &Test) -> Result<()> {
} }
let actual_results = store let actual_results = store
.query_opt(query.clone(), options) .query_opt(query.clone(), options)
.map_err(|e| anyhow!("Failure to execute query with error: {e}"))?; .context("Failure to execute query")?;
let actual_results = StaticQueryResults::from_query_results(actual_results, with_order)?; let actual_results = StaticQueryResults::from_query_results(actual_results, with_order)?;
ensure!( ensure!(
@ -205,22 +190,16 @@ fn evaluate_evaluation_test(test: &Test) -> Result<()> {
} }
fn evaluate_positive_update_syntax_test(test: &Test) -> Result<()> { fn evaluate_positive_update_syntax_test(test: &Test) -> Result<()> {
let update_file = test let update_file = test.action.as_deref().context("No action found")?;
.action
.as_deref()
.ok_or_else(|| anyhow!("No action found"))?;
let update = Update::parse(&read_file_to_string(update_file)?, Some(update_file)) let update = Update::parse(&read_file_to_string(update_file)?, Some(update_file))
.map_err(|e| anyhow!("Not able to parse with error: {e}"))?; .context("Not able to parse")?;
Update::parse(&update.to_string(), None) Update::parse(&update.to_string(), None)
.map_err(|e| anyhow!("Failure to deserialize \"{update}\" with error: {e}"))?; .with_context(|| format!("Failure to deserialize \"{update}\""))?;
Ok(()) Ok(())
} }
fn evaluate_negative_update_syntax_test(test: &Test) -> Result<()> { fn evaluate_negative_update_syntax_test(test: &Test) -> Result<()> {
let update_file = test let update_file = test.action.as_deref().context("No action found")?;
.action
.as_deref()
.ok_or_else(|| anyhow!("No action found"))?;
ensure!( ensure!(
Update::parse(&read_file_to_string(update_file)?, Some(update_file)).is_err(), Update::parse(&read_file_to_string(update_file)?, Some(update_file)).is_err(),
"Oxigraph parses even if it should not." "Oxigraph parses even if it should not."
@ -245,20 +224,15 @@ fn evaluate_update_evaluation_test(test: &Test) -> Result<()> {
load_graph_to_store(value, &result_store, name.clone())?; load_graph_to_store(value, &result_store, name.clone())?;
} }
let update_file = test let update_file = test.update.as_deref().context("No action found")?;
.update
.as_deref()
.ok_or_else(|| anyhow!("No action found"))?;
let update = Update::parse(&read_file_to_string(update_file)?, Some(update_file)) let update = Update::parse(&read_file_to_string(update_file)?, Some(update_file))
.map_err(|e| anyhow!("Failure to parse update with error: {e}"))?; .context("Failure to parse update")?;
// We check parsing roundtrip // We check parsing roundtrip
Update::parse(&update.to_string(), None) Update::parse(&update.to_string(), None)
.map_err(|e| anyhow!("Failure to deserialize \"{update}\" with error: {e}"))?; .with_context(|| format!("Failure to deserialize \"{update}\""))?;
store store.update(update).context("Failure to execute update")?;
.update(update)
.map_err(|e| anyhow!("Failure to execute update with error: {e}"))?;
let mut store_dataset: Dataset = store.iter().collect::<Result<_, _>>()?; let mut store_dataset: Dataset = store.iter().collect::<Result<_, _>>()?;
store_dataset.canonicalize(); store_dataset.canonicalize();
let mut result_store_dataset: Dataset = result_store.iter().collect::<Result<_, _>>()?; let mut result_store_dataset: Dataset = result_store.iter().collect::<Result<_, _>>()?;
@ -689,10 +663,7 @@ fn load_dataset_to_store(url: &str, store: &Store) -> Result<()> {
} }
fn evaluate_query_optimization_test(test: &Test) -> Result<()> { fn evaluate_query_optimization_test(test: &Test) -> Result<()> {
let action = test let action = test.action.as_deref().context("No action found")?;
.action
.as_deref()
.ok_or_else(|| anyhow!("No action found"))?;
let actual = (&Optimizer::optimize_graph_pattern( let actual = (&Optimizer::optimize_graph_pattern(
(&if let spargebra::Query::Select { pattern, .. } = (&if let spargebra::Query::Select { pattern, .. } =
spargebra::Query::parse(&read_file_to_string(action)?, Some(action))? spargebra::Query::parse(&read_file_to_string(action)?, Some(action))?
@ -704,10 +675,7 @@ fn evaluate_query_optimization_test(test: &Test) -> Result<()> {
.into(), .into(),
)) ))
.into(); .into();
let result = test let result = test.result.as_ref().context("No tests result found")?;
.result
.as_ref()
.ok_or_else(|| anyhow!("No tests result found"))?;
let spargebra::Query::Select { let spargebra::Query::Select {
pattern: expected, .. pattern: expected, ..
} = spargebra::Query::parse(&read_file_to_string(result)?, Some(result))? } = spargebra::Query::parse(&read_file_to_string(result)?, Some(result))?

Loading…
Cancel
Save