async-graphql-test 1.0.0

A test framework for Rust GraphQL servers.
Documentation
use std::fmt::{Display, Formatter};

use async_graphql::async_trait::async_trait;
use async_graphql::{Any, Context, CustomDirective, Directive, ResolveFut, ServerResult, Value};

use super::MatcherError;

#[Directive(location = "Field", name = "shouldEqual")]
pub fn should_equal(to: Any) -> impl CustomDirective {
    ShouldEqual { val: to.0 }
}

struct ShouldEqual {
    val: Value,
}

impl Display for ShouldEqual {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        self.val.fmt(f)
    }
}

#[async_trait]
impl CustomDirective for ShouldEqual {
    async fn resolve_field(
        &self,
        ctx: &Context<'_>,
        resolve: ResolveFut<'_>,
    ) -> ServerResult<Option<Value>> {
        match resolve.await {
            Ok(None) => Ok(None),
            Ok(Some(value)) => {
                if value == self.val {
                    Ok(Some(value))
                } else {
                    Err(MatcherError::new(
                        ctx.item.pos,
                        format!("Expected: {self}\nReceived: {value}"),
                    ))
                }
            }
            Err(err) => Err(MatcherError::unexpected_error(err)),
        }
    }
}