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

Background support #2

Open
wants to merge 3 commits into
base: devel
Choose a base branch
from
Open
Changes from 1 commit
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
Prev Previous commit
Next Next commit
Change TestCase from trait objects to enum
Previously, TestCase was a trait, and features were composed of boxed TestCase
trait objects. This changes it to an enum, since we expect to have only a small
number of TestCase types, and users are not expected to provide new ones.

This also changes the module layout; previously, the scenario and feature
parsers and AST structs were each in their own modules. This makes less sense
when using the enum at the TestCase level. Now all the AST structs are in the
AST module, and the parsers are in the parser module.
Russell Mull committed Jul 10, 2018

Verified

This commit was created on GitHub.com and signed with GitHub’s verified signature.
commit ceb0c6c07d0cca489c211be7cc85f192f3f1745d
77 changes: 77 additions & 0 deletions src/ast.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
/// A test context is used to pass state between different steps of a test case.
/// It may also be initialized at the feature level via a Background (TODO)
pub trait TestContext {
fn new() -> Self;
}


pub enum TestCase<C: TestContext> {
Background(Scenario<C>),
Scenario(Scenario<C>),
}

impl<C: TestContext> TestCase<C> {
pub fn name(&self) -> String {
match self {
TestCase::Background(s) => s.name.clone(),
TestCase::Scenario(s) => s.name.clone()
}
}


pub fn eval(&self, context: &mut C) -> bool {
match self {
TestCase::Background(s) => s.eval(context),
TestCase::Scenario(s) => s.eval(context)
}
}
}

/// A feature is a collection of test cases.
pub struct Feature<C: TestContext> {
pub name: String,
pub comment: String,
pub test_cases: Vec<TestCase<C>>,
}

impl<C: TestContext> Feature<C> {
pub fn eval(&self) -> (bool, C) {
let mut context = C::new();

for tc in self.test_cases.iter() {
let pass = tc.eval(&mut context);

if !pass {
return (false, context);
}
}

(true, context)
}
}

pub struct Scenario<TC: TestContext> {
pub name: String,
pub steps: Vec<Box<Step<TC>>>,
}

impl<C: TestContext> Scenario<C> {
/// Execute a scenario by running each step in order, with mutable access to
/// the context.
pub fn eval(&self, context: &mut C) -> bool {
for s in self.steps.iter() {
if !s.eval(context) {
return false;
}
}

true
}
}

/// A specific step which makes up a scenario. Users should create their own
/// implementations of this trait, which are returned by their step parsers.

Choose a reason for hiding this comment

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

For rustdoc, I think the first line is supposed to be a summary of the functionality and then more details get added after a blank line. I think so it renders nicer?

pub trait Step<C: TestContext> {
fn eval(&self, &mut C) -> bool;
}

163 changes: 0 additions & 163 deletions src/feature.rs

This file was deleted.

4 changes: 2 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -3,8 +3,8 @@ extern crate combine;

extern crate itertools;

pub mod feature;
pub mod scenario;
pub mod parser;
pub mod ast;
pub mod parse_utils;


151 changes: 93 additions & 58 deletions src/scenario.rs → src/parser.rs
Original file line number Diff line number Diff line change
@@ -1,46 +1,19 @@
use combine::{ParseError, Parser, Stream, many, token, optional};
use combine::char::string;
use parse_utils::{eol, until_eol};

use ast::{Step, TestContext, TestCase, Feature, Scenario};
use itertools;

use feature::{BoxedTestCase, TestCase, TestContext};

struct Scenario<TC: TestContext> {
name: String,
steps: Vec<Box<Step<TC>>>,
}
use combine::ParseError;
use combine::Parser;
use combine::Stream;

/// A specific step which makes up a test context. Users should create there own
/// implementations of this trait, which are returned by their step parsers.
pub trait Step<C: TestContext> {
fn eval(&self, &mut C) -> bool;
}

impl<C: TestContext> TestCase<C> for Scenario<C> {
fn name(&self) -> String {
self.name.clone()
}

/// Execute a scenario by creating a new test context, then running each
/// step in order with mutable access to the context.
fn eval(&self, mut context: C) -> (bool, C) {
// let mut ctx = TC::new();
for s in self.steps.iter() {
if !s.eval(&mut context) {
return (false, context);
}
}

(true, context)
}
}
use combine::char::{newline, string};
use combine::{many, many1, sep_by, optional, token};
use parse_utils::{line_block, until_eol, eol};

pub struct BoxedStep<C: TestContext> {
pub val: Box<Step<C>>,
}

fn scenario_block_parser<I, TC, P>(
fn scenario_block<I, TC, P>(
prefix: &'static str,
inner: P,
) -> impl Parser<Input = I, Output = Vec<BoxedStep<TC>>>
@@ -58,18 +31,19 @@ where
})
}


/// A `TestCase` parser for classic Cucumber-style Scenarios; this parser (or a
/// composition thereof) should be passed to feature::parser.
///
/// # Arguments
///
/// * `given`, `when`, `then` : User-defined parsers to parse and produce
/// `Step`s out of the text after `Given`, `When`, and `Then`, respectively.
pub fn parser<I, TC, GP, WP, TP>(
pub fn scenario<I, TC, GP, WP, TP>(
given: GP,
when: WP,
then: TP,
) -> impl Parser<Input = I, Output = BoxedTestCase<TC>>
) -> impl Parser<Input = I, Output = TestCase<TC>>
where
TC: TestContext + 'static,
GP: Parser<Input = I, Output = BoxedStep<TC>> + Clone,
@@ -78,9 +52,9 @@ where
I: Stream<Item = char>,
I::Error: ParseError<I::Item, I::Range, I::Position>,
{
let givens = scenario_block_parser("Given", given);
let whens = scenario_block_parser("When", when);
let thens = scenario_block_parser("Then", then);
let givens = scenario_block("Given", given);
let whens = scenario_block("When", when);
let thens = scenario_block("Then", then);

let steps = (
optional(givens).map(|o| o.unwrap_or(vec![])),
@@ -96,14 +70,39 @@ where
}
};

scenario.map(|sc| BoxedTestCase { val: Box::new(sc) })
scenario.map(|s| TestCase::Scenario(s))
}


/// Construct a feature file parser, built around a test-case parser.
pub fn feature<I, C, TP>(test_case_parser: TP) -> impl Parser<Input = I, Output = Feature<C>>
where
C: TestContext,
TP: Parser<Input = I, Output = TestCase<C>>,
I: Stream<Item = char>,
I::Error: ParseError<I::Item, I::Range, I::Position>,
{
let blank_lines = || many1::<Vec<_>, _>(newline());

let test_cases = sep_by(test_case_parser, blank_lines());

struct_parser! {
Feature {
_: optional(blank_lines()),
_: string("Feature: "),
name: until_eol(),
comment: line_block(),
_: blank_lines(),
test_cases: test_cases
}
}
}



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

use feature;
use combine::stream::state::State;

/// The sample test case just records each step as it runs
@@ -130,20 +129,7 @@ mod tests {
}
}

#[test]
fn scenario() {
let s = "Feature: my feature\n\
\n\
Scenario: One\n\
Given G1\n\
When W1\n\
Then T1\n\
\n\
Scenario: Two\n\
Given G2\n\
When W2\n\
Then T2\n";

fn do_parse(s: &str) -> Feature<SampleTestContext> {
use combine::char::digit;
use combine::token;

@@ -152,14 +138,62 @@ mod tests {
let when = struct_parser! { SampleStep { _: token('W'), num: num_digit() } };
let then = struct_parser! { SampleStep { _: token('T'), num: num_digit() } };

let (feat, remaining) = feature::parser(parser(
let (feat, remaining) = feature(scenario(
given.map(|x| BoxedStep { val: Box::new(x) }),
when.map(|x| BoxedStep { val: Box::new(x) }),
then.map(|x| BoxedStep { val: Box::new(x) }),
)).easy_parse(State::new(s))
.unwrap();

println!("End state: {:#?}", remaining);

feat
}

#[test]
fn test_parse() {
let feat = do_parse(r"
Feature: my feature
one
two
Scenario: One
Given G1
When W1
Then T1
Scenario: Two
Given G2
When W2
Then T2");

assert_eq!(feat.name, "my feature".to_string());
assert_eq!(feat.comment, "one\ntwo".to_string());
assert_eq!(feat.test_cases.len(), 2);
assert_eq!(feat.test_cases[0].name(), "One".clone());
assert_eq!(feat.test_cases[1].name(), "Two".clone());

let (pass, ctx) = feat.eval();
assert!(pass);
assert_eq!(ctx.executed_steps, vec![1, 1, 1, 2, 2, 2]);
}

#[test]
fn test_parse_extra_whitespace() {
let feat = do_parse(r"
Feature: my feature
Scenario: One
Given G1
When W1
Then T1
Scenario: Two
Given G2
When W2
Then T2
");

assert_eq!(feat.name, "my feature".to_string());
assert_eq!(feat.comment, "".to_string());
assert_eq!(feat.test_cases.len(), 2);
@@ -170,4 +204,5 @@ mod tests {
assert!(pass);
assert_eq!(ctx.executed_steps, vec![1, 1, 1, 2, 2, 2]);
}

}
41 changes: 30 additions & 11 deletions tests/calculator.rs
Original file line number Diff line number Diff line change
@@ -6,8 +6,9 @@ use combine::stream::state::State;
use combine::char::{string, digit};

extern crate rherkin;
use rherkin::feature::{self, TestContext};
use rherkin::scenario::{self, Step, BoxedStep};
//use rherkin::feature;
//use rherkin::scenario::{self, Step, BoxedStep, TestContext};
use rherkin::{ast, parser};

// An rpn calculator, something we can write tests for.
#[derive(Debug)]
@@ -80,7 +81,7 @@ impl Calculator {
}
}

impl TestContext for Calculator {
impl ast::TestContext for Calculator {
fn new() -> Calculator {
Calculator {
current: vec!(),
@@ -93,7 +94,7 @@ mod steps {
use super::*;

pub struct Clear { }
impl Step<Calculator> for Clear {
impl ast::Step<Calculator> for Clear {
fn eval(&self, calc: &mut Calculator) -> bool {
println!("Clear");
calc.current = vec!();
@@ -103,15 +104,15 @@ mod steps {
}

pub struct Press { pub button: Button }
impl Step<Calculator> for Press {
impl ast::Step<Calculator> for Press {
fn eval(&self, calc: &mut Calculator) -> bool {
println!("Press {:?}", self.button);
calc.press(&self.button)
}
}

pub struct CheckDisplay { pub expected: String }
impl Step<Calculator> for CheckDisplay {
impl ast::Step<Calculator> for CheckDisplay {
fn eval(&self, calc: &mut Calculator) -> bool {
let actual = calc.stack.last();
println!("Check display: expected {:?}, actual {:#?}", self.expected, actual);
@@ -177,15 +178,33 @@ Then the display should read 2
let then = choice! { check_display };

let mut p =
feature::parser(
scenario::parser(
given.map(|x| BoxedStep { val: Box::new(x) }),
when.map(|x| BoxedStep { val: Box::new(x) }),
then.map(|x| BoxedStep { val: Box::new(x) })));
parser::feature(
parser::scenario(
given.map(|x| parser::BoxedStep { val: Box::new(x) }),
when.map (|x| parser::BoxedStep { val: Box::new(x) }),
then.map (|x| parser::BoxedStep { val: Box::new(x) })));

let (f, remaining) = p.easy_parse(State::new(spec)).unwrap();

let (success, _) = f.eval();
assert!(success);
}


// fn proptests() {
// let spec = r#"
// Feature: RPN Calculator Property Specs

// PropSpec: arbitrary addition
// Given a fresh calculator
// And a number A less than 10000
// And a number B less than 10000
// When I enter the number A
// And I press enter
// And I enter the number B
// And I press plus
// Then the displayed value should be less than 20000
// "#;

// assert!(true)
// }

Choose a reason for hiding this comment

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

Dead code?