Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Enable using ? in tests #25

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
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
14 changes: 14 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,20 @@ Inside `speculate! { ... }`, you can have any "Item", like `static`, `const`,
}
```

You can also declare an error type that the tests can fail with, which implicitly makes those test return `Result<(), E>`:

```rust
use std::fs;
speculate! {
use std::io::Error;
errtype(Error)

it "has i/o setup" {
fs::write("/some/file", "with content")?;
assert_eq!(file_reader()?, "with_content");
}
}
```
* `bench` - contains benchmarks.

For example:
Expand Down
22 changes: 20 additions & 2 deletions src/block.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use proc_macro2::Span;
use syn::{alt, braces, call, custom_keyword, do_parse, many0, named, punct, syn, synom::Synom};
use syn::{alt, braces, call, custom_keyword, do_parse, many0, named, parens, punct, syn, synom::Synom};
use unicode_xid::UnicodeXID;

pub struct Root(pub(crate) Describe);
Expand All @@ -12,17 +12,28 @@ impl Synom for Root {
let mut before = vec![];
let mut after = vec![];
let mut blocks = vec![];
let mut errtype = None;

for block in content {
match block {
DescribeBlock::Regular(block) => blocks.push(block),
DescribeBlock::Before(block) => before.push(block),
DescribeBlock::After(block) => after.push(block)
DescribeBlock::After(block) => after.push(block),
DescribeBlock::Errtype(t) => { errtype.replace(t); }
}
}

for cand in blocks.iter_mut() {
if let Block::Describe(child) = cand {
if child.errtype.is_none() {
child.errtype = errtype.clone();
}
}
}

Root(Describe {
name: syn::Ident::new("speculate", Span::call_site()),
errtype: errtype,
before, after, blocks
})
})
Expand Down Expand Up @@ -53,6 +64,7 @@ enum DescribeBlock {
Regular(Block),
Before(syn::Block),
After(syn::Block),
Errtype(syn::TypePath),
}

impl Synom for DescribeBlock {
Expand All @@ -67,13 +79,19 @@ impl Synom for DescribeBlock {
block: syn!(syn::Block) >>
(DescribeBlock::After(block)) )
|
do_parse!(
custom_keyword!(errtype) >>
errtype: parens!(syn!(syn::TypePath)) >>
(DescribeBlock::Errtype(errtype.1)) )
|
syn!(Block) => { DescribeBlock::Regular }
));
}

#[derive(Clone)]
pub struct Describe {
pub name: syn::Ident,
pub errtype: Option<syn::TypePath>,
pub before: Vec<syn::Block>,
pub after: Vec<syn::Block>,
pub blocks: Vec<Block>,
Expand Down
25 changes: 23 additions & 2 deletions src/generator.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use crate::block::{Bench, Block, Describe, It};
use proc_macro2::{Ident, TokenStream};
use quote::{quote_spanned, ToTokens};
use quote::{quote, quote_spanned, ToTokens};
use syn::spanned::Spanned;

pub trait Generate {
fn generate(self, up: Option<&Describe>) -> TokenStream;
Expand Down Expand Up @@ -65,12 +66,14 @@ impl Generate for It {

let name = Ident::new(&format!("test_{}", self.name), self.name.span());
let attributes = self.attributes;
let (ret_type, ret_val) = return_signature(up.and_then(|d| d.errtype.clone()), &attributes);

quote_spanned!(name.span() =>
#[test]
#(#attributes)*
fn #name() {
fn #name() -> #ret_type {
#(#stmts)*
#ret_val
}
)
}
Expand Down Expand Up @@ -106,3 +109,21 @@ impl Generate for Bench {
fn flatten_blocks(blocks: Vec<syn::Block>) -> impl Iterator<Item = syn::Stmt> {
blocks.into_iter().flat_map(|block| block.stmts)
}

fn return_signature(err: Option<syn::TypePath>, attributes: &Vec<syn::Attribute>) -> (TokenStream, TokenStream) {
let should_panic = attributes.iter()
.find(|attr| attr.path.segments.first()
.filter(|segment| segment.value().ident == "should_panic")
.is_some());

match (err, should_panic) {
(Some(ref errtype), None) => (
quote_spanned!(errtype.span()=> Result<(), #errtype>),
quote_spanned!(errtype.span()=> Ok(()))
),
_ => (
quote!{ () },
quote!{ }
),
}
}
16 changes: 16 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,22 @@ fn get_root_name() -> proc_macro2::Ident {
/// }
/// # }
/// ```
/// You can also declare an error type that the tests can fail with, which implicitly makes those test return `Result<(), E>`:
///
/// ```rust
/// #[macro_use] extern crate speculate as other_speculate;
/// # use std::fs;
/// # fn main() {}
/// # speculate! {
/// use std::io::Error;
/// errtype(Error)
///
/// it "has i/o setup" {
/// fs::write("/some/file", "with content")?;
/// assert_eq!(file_reader()?, "with content");
/// }
/// # }
/// ```
///
/// * `bench` - contains benchmarks (using [`Bencher`](https://doc.rust-lang.org/test/struct.Bencher.html)).
///
Expand Down
63 changes: 63 additions & 0 deletions tests/basic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,69 @@ mod ec5 {
}
}

mod errors {
use other_speculate::speculate;

fn maybe_fail_u8() -> Result<(), u8> { Ok(()) }
fn maybe_fail_string() -> Result<(), String> { Ok(()) }
fn will_fail() -> Result<(), String> { Err("badness".to_owned()) }

speculate! {
errtype(u8)

it "error would be a u8" {
maybe_fail_u8()?;
}

#[should_panic]
it "rust does not allow Ok(()) with should_panic" {
panic!("Completely normal");
}

describe "actually fails" {
errtype(String)

#[ignore]
it "fails with a string" {
will_fail()?;
}

it "good badness" {
assert_eq!("badness", test_fails_with_a_string().unwrap_err());
}
}
}

speculate! {
errtype(u8)

describe "it even propagates" {
it "bar" {
maybe_fail_u8()?;
}
}

describe "and can be overridden" {
errtype(String)

it "foo" {
maybe_fail_string()?;
}
}
}

speculate! {
describe "my before blocks can use ? too" {
errtype(u8)

before {
maybe_fail_u8()?;
}
it "foo" {}
}
}
}

mod attributes {
use other_speculate::speculate;

Expand Down