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
use darling::FromMeta;
use proc_macro2::TokenStream;
use quote::{quote, ToTokens};
use syn::parse::{Parse, ParseStream};
use syn::{
Attribute, Block, FnArg, Generics, Ident, Item, ItemFn, Result, ReturnType, Type, Visibility,
};
/// The arguments that the `test` annotation macro takes.
#[derive(Debug, FromMeta)]
pub struct TestArgs {
// We'll fall back to a sensible default if no URL is given for the WebDriver
#[darling(default)]
webdriver_url: Option<String>,
}
/// A function that can be wrapped in the Perseus test sub-harness.
pub struct TestFn {
/// The body of the function.
pub block: Box<Block>,
/// The single argument for the Fantoccini client.
pub arg: FnArg,
/// The visibility of the function.
pub vis: Visibility,
/// Any attributes the function uses.
pub attrs: Vec<Attribute>,
/// The actual name of the function.
pub name: Ident,
/// The return type of the function.
pub return_type: Box<Type>,
/// Any generics the function takes (shouldn't be any, but it could in
/// theory).
pub generics: Generics,
}
impl Parse for TestFn {
fn parse(input: ParseStream) -> Result<Self> {
let parsed: Item = input.parse()?;
match parsed {
Item::Fn(func) => {
let ItemFn {
attrs,
vis,
sig,
block,
} = func;
// Validate each part of this function to make sure it fulfills the requirements
// Must be async
if sig.asyncness.is_none() {
return Err(syn::Error::new_spanned(
sig.asyncness,
"tests must be async",
));
}
// Can't be const
if sig.constness.is_some() {
return Err(syn::Error::new_spanned(
sig.constness,
"const functions can't be used as tests",
));
}
// Can't be external
if sig.abi.is_some() {
return Err(syn::Error::new_spanned(
sig.abi,
"external functions can't be used as tests",
));
}
// Must return `std::result::Result<(), fantoccini::error::CmdError>`
let return_type = match sig.output {
ReturnType::Default => {
return Err(syn::Error::new_spanned(
sig,
"test function must return `std::result::Result<(), fantoccini::error::CmdError>`",
))
}
ReturnType::Type(_, ty) => ty,
};
// Must accept a single argument for the Fantoccini client
let mut inputs = sig.inputs.into_iter();
let arg = inputs.next().unwrap_or_else(|| syn::parse_quote! { _: () });
match &arg {
FnArg::Typed(_) => (),
// Can't accept `self`
FnArg::Receiver(arg) => {
return Err(syn::Error::new_spanned(
arg,
"test functions can't take `self`",
))
}
};
if inputs.len() > 0 {
let params: TokenStream = inputs.map(|it| it.to_token_stream()).collect();
return Err(syn::Error::new_spanned(
params,
"test functions must accept a single argument for the Fantoccini client",
));
}
Ok(Self {
block,
arg,
vis,
attrs,
name: sig.ident,
return_type,
generics: sig.generics,
})
}
item => Err(syn::Error::new_spanned(
item,
"only functions can be used as tests",
)),
}
}
}
pub fn test_impl(input: TestFn, args: TestArgs) -> TokenStream {
let TestFn {
block,
arg,
generics,
vis,
attrs,
name,
return_type,
} = input;
// Get the WebDriver URL to use from the macro arguments, or use a sensible
// default
let webdriver_url = args
.webdriver_url
.unwrap_or_else(|| "http://localhost:4444".to_string());
// We create a wrapper function that handles errors and the Fantoccini client
let output = quote! {
#[::tokio::test]
#vis async fn #name() {
// The user's function
#(#attrs)*
async fn fn_internal #generics(#arg) -> #return_type {
#block
}
// Only run the test if the environment variable is specified (avoids having to do exclusions for workspace `cargo test`)
if ::std::env::var("PERSEUS_RUN_WASM_TESTS").is_ok() {
let headless = ::std::env::var("PERSEUS_RUN_WASM_TESTS_HEADLESS").is_ok();
// Set the capabilities of the client
// If the user wants different capabilities, they should break out of this macro and use Fantoccini directly
let mut capabilities = ::serde_json::Map::new();
let firefox_opts;
let chrome_opts;
if headless {
firefox_opts = ::serde_json::json!({ "args": ["--headless"] });
chrome_opts = ::serde_json::json!({ "args": ["--headless"] });
} else {
firefox_opts = ::serde_json::json!({ "args": [] });
chrome_opts = ::serde_json::json!({ "args": [] });
}
capabilities.insert("moz:firefoxOptions".to_string(), firefox_opts);
capabilities.insert("goog:chromeOptions".to_string(), chrome_opts);
let mut client = ::fantoccini::ClientBuilder::native()
.capabilities(capabilities)
.connect(&#webdriver_url).await.expect("failed to connect to WebDriver");
let output = fn_internal(&mut client).await;
// Close the client no matter what
client.close().await.expect("failed to close Fantoccini client");
// Panic if the test failed
if let Err(err) = output {
panic!("test failed: '{}'", err.to_string())
}
}
}
};
output
}