1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
// Copyright (c) 2018  Brendan Molloy <brendan@bbqsrc.net>
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

pub extern crate gherkin_rust as gherkin;
pub extern crate regex;

use gherkin::{Step, StepType, Feature};
use regex::Regex;
use std::collections::HashMap;
use std::fs::{self, File};
use std::hash::{Hash, Hasher};
use std::io::prelude::*;
use std::ops::Deref;
use std::panic;
use std::path::Path;
use std::sync::Mutex;

pub trait World: Default {}

pub struct HashableRegex(pub Regex);

impl Hash for HashableRegex {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.0.as_str().hash(state);
    }
}

impl PartialEq for HashableRegex {
    fn eq(&self, other: &HashableRegex) -> bool {
        self.0.as_str() == other.0.as_str()
    }
}

impl Eq for HashableRegex {}

impl Deref for HashableRegex {
    type Target = Regex;

    fn deref(&self) -> &Regex {
        &self.0
    }
}

pub struct TestCase<T: Default> {
    pub test: fn(&mut T) -> ()
}

impl<T: Default> TestCase<T> {
    #[allow(dead_code)]
    pub fn new(test: fn(&mut T) -> ()) -> TestCase<T> {
        TestCase {
            test: test
        }
    }
}

pub struct RegexTestCase<T: Default> {
    pub test: fn(&mut T, &[String]) -> ()
}

impl<T: Default> RegexTestCase<T> {
    #[allow(dead_code)]
    pub fn new(test: fn(&mut T, &[String]) -> ()) -> RegexTestCase<T> {
        RegexTestCase {
            test: test
        }
    }
}

pub struct Steps<T: Default> {
    pub given: HashMap<&'static str, TestCase<T>>,
    pub when: HashMap<&'static str, TestCase<T>>,
    pub then: HashMap<&'static str, TestCase<T>>,
    pub regex: RegexSteps<T>
}

pub struct RegexSteps<T: Default> {
    pub given: HashMap<HashableRegex, RegexTestCase<T>>,
    pub when: HashMap<HashableRegex, RegexTestCase<T>>,
    pub then: HashMap<HashableRegex, RegexTestCase<T>>,
}

pub enum TestCaseType<'a, T> where T: 'a, T: Default {
    Normal(&'a TestCase<T>),
    Regex(&'a RegexTestCase<T>, Vec<String>)
}

impl<T: Default> Steps<T> {
    #[allow(dead_code)]
    pub fn new() -> Steps<T> {
        let regex_tests = RegexSteps {
            given: HashMap::new(),
            when: HashMap::new(),
            then: HashMap::new()
        };

        let tests = Steps {
            given: HashMap::new(),
            when: HashMap::new(),
            then: HashMap::new(),
            regex: regex_tests
        };

        tests
    }

    #[allow(dead_code)]
    fn test_type<'a>(&'a self, step: &Step, value: &str) -> Option<TestCaseType<'a, T>> {
        let test_bag = match step.ty {
            StepType::Given => &self.given,
            StepType::When => &self.when,
            StepType::Then => &self.then
        };

        match test_bag.get(value) {
            Some(v) => Some(TestCaseType::Normal(v)),
            None => {
                let regex_bag = match step.ty {
                    StepType::Given => &self.regex.given,
                    StepType::When => &self.regex.when,
                    StepType::Then => &self.regex.then
                };

                let result = regex_bag.iter()
                    .find(|(regex, _)| regex.is_match(&value));

                match result {
                    Some((regex, tc)) => {
                        let thing = regex.0.captures(&value).unwrap();
                        let matches: Vec<String> = thing.iter().map(|x| x.unwrap().as_str().to_string()).collect();
                        Some(TestCaseType::Regex(tc, matches))
                    },
                    None => {
                        None
                    }
                }
            }
        }
    }

    #[allow(dead_code)]
    pub fn run(&self, feature_path: &Path) {
        use std::sync::Arc;

        let last_panic: Arc<Mutex<Option<String>>> = Arc::new(Mutex::new(None));
        let feature_path = fs::read_dir(feature_path).expect("feature path to exist");

        let mut scenarios = 0;
        let mut steps = 0;

        for entry in feature_path {
            let mut file = File::open(entry.unwrap().path()).expect("file to open");
            let mut buffer = String::new();
            file.read_to_string(&mut buffer).unwrap();
            let feature = Feature::from(&*buffer);
            
            println!("Feature: {}\n", feature.name);

            for scenario in feature.scenarios {
                scenarios += 1;

                println!("  Scenario: {}", scenario.name);

                let mut world = Mutex::new(T::default());

                for step in scenario.steps {
                    steps += 1;

                    let value = step.value.to_string();
                    
                    let test_type = match self.test_type(&step, &value) {
                        Some(v) => v,
                        None => {
                            println!("    {}\n      # No test found", &step.to_string());
                            continue;
                        }
                    };
                    
                    let last_panic_hook = last_panic.clone();
                    panic::set_hook(Box::new(move |info| {
                        let mut state = last_panic_hook.lock().expect("last_panic unpoisoned");
                        *state = info.location().map(|x| format!("{}:{}:{}", x.file(), x.line(), x.column()));
                    }));

                    let result = panic::catch_unwind(|| {
                        match world.lock() {
                            Ok(mut world) => {
                                match test_type {
                                    TestCaseType::Normal(t) => (t.test)(&mut *world),
                                    TestCaseType::Regex(t, c) => (t.test)(&mut *world, &c)
                                }
                            },
                            Err(e) => {
                                return Err(e);
                            }
                        };

                        return Ok(())
                    });

                    let _ = panic::take_hook();

                    println!("    {:<40}", &step.to_string());

                    match result {
                        Ok(inner) => {
                            match inner {
                                Ok(_) => {},
                                Err(_) => println!("      # Skipped due to previous error")
                            }
                        }
                        Err(any) => {
                            println!("      # Step failed:");
                            let mut state = last_panic.lock().expect("unpoisoned");

                            {
                                let loc = match &*state {
                                    Some(v) => &v,
                                    None => "unknown"
                                };

                                if let Some(s) = any.downcast_ref::<String>() {
                                    println!("      # {}  [{}]", &s, loc);
                                } else if let Some(s) = any.downcast_ref::<&str>() {
                                    println!("      # {}  [{}]", &s, loc);
                                }
                            }

                            *state = None;
                        }
                    };
                }

                println!("");
            }
        }

        println!("# Scenarios: {}", scenarios);
        println!("# Steps: {}", steps);
    }
}

#[macro_export]
macro_rules! cucumber {
    (
        features: $featurepath:tt;
        world: $worldtype:path;
        steps: $vec:expr
    ) => {
        #[allow(unused_imports)]
        fn main() {
            use std::path::Path;
            use std::process;
            use $crate::{Steps, World};

            let path = match Path::new($featurepath).canonicalize() {
                Ok(p) => p,
                Err(e) => {
                    eprintln!("{}", e);
                    eprintln!("There was an error parsing \"{}\"; aborting.", $featurepath);
                    process::exit(1);
                }
            };

            if !&path.exists() {
                eprintln!("Path {:?} does not exist; aborting.", &path);
                process::exit(1);
            }

            let tests = {
                let step_groups: Vec<Steps<$worldtype>> = $vec.iter().map(|f| f()).collect();
                let mut combined_steps = Steps::new();

                for step_group in step_groups.into_iter() {
                    combined_steps.given.extend(step_group.given);
                    combined_steps.when.extend(step_group.when);
                    combined_steps.then.extend(step_group.then);

                    combined_steps.regex.given.extend(step_group.regex.given);
                    combined_steps.regex.when.extend(step_group.regex.when);
                    combined_steps.regex.then.extend(step_group.regex.then);
                }

                combined_steps
            };
            
            tests.run(&path);
        }
    }
}

#[macro_export]
macro_rules! steps {
    (
        @gather_steps, $tests:tt,
        $ty:ident regex $name:tt $body:expr;
    ) => {
        $tests.regex.$ty.insert(
            HashableRegex(Regex::new($name).expect(&format!("{} is a valid regex", $name))),
                RegexTestCase::new($body));
    };

    (
        @gather_steps, $tests:tt,
        $ty:ident regex $name:tt $body:expr; $( $items:tt )*
    ) => {
        $tests.regex.$ty.insert(
            HashableRegex(Regex::new($name).expect(&format!("{} is a valid regex", $name))),
                RegexTestCase::new($body));

        steps!(@gather_steps, $tests, $( $items )*);
    };

    (
        @gather_steps, $tests:tt,
        $ty:ident $name:tt $body:expr;
    ) => {
        $tests.$ty.insert($name, TestCase::new($body));
    };

    (
        @gather_steps, $tests:tt,
        $ty:ident $name:tt $body:expr; $( $items:tt )*
    ) => {
        $tests.$ty.insert($name, TestCase::new($body));

        steps!(@gather_steps, $tests, $( $items )*);
    };

    (
        $( $items:tt )*
    ) => {
        #[allow(unused_imports)]
        pub fn steps<T: Default>() -> $crate::Steps<T> {
            use std::path::Path;
            use std::process;
            use $crate::regex::Regex;
            use $crate::{Steps, TestCase, RegexTestCase, HashableRegex};

            let mut tests: Steps<T> = Steps::new();
            steps!(@gather_steps, tests, $( $items )*);
            tests
        }
    };
}


#[cfg(test)]
mod tests {
    use std::default::Default;

    pub struct World {
        pub thing: bool
    }

    impl ::World for World {}

    impl Default for World {
        fn default() -> World {
            World {
                thing: false
            }
        }
    }
}

#[cfg(test)]
mod tests2 {
    use std::default::Default;

    pub struct World {
        pub thing2: bool
    }

    impl ::World for World {}

    impl Default for World {
        fn default() -> World {
            World {
                thing2: true
            }
        }
    }

    steps! {
        when "nothing" |world| {
            assert!(true);
        };
        when regex "^nothing$" |world, matches| {
            assert!(true)
        };
    }
}

#[cfg(test)]
mod tests1 {
    steps! {
        when regex "^test (.*) regex$" |world, matches| {
            println!("{}", matches[1]);
        };

        given "a thing" |world| {
            assert!(true);
        };

        when "another thing" |world| {
            assert!(false);
        };

        when "something goes right" |world| { 
            assert!(true);
        };

        then "another thing" |world| {
            assert!(true)
        };
    }
}

#[cfg(test)]
cucumber! {
    features: "./features";
    world: tests::World;
    steps: &[
        tests1::steps,
        tests2::steps
    ]
}