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
//! Contains responses for Gherkin interpreter (or Wire Protocol).
//!
//! Consumers mostly need to be concerned with
//! [InvokeResponse](./enum.InvokeResponse.html), as it is the
//! return type of all step defintions.

#[cfg(feature = "serde_macros")]
include!("response.rs.in");

#[cfg(not(feature = "serde_macros"))]
include!(concat!(env!("OUT_DIR"), "/event/response.rs"));

use serde;
use serde::ser::impls::TupleVisitor2;
use serde::ser::MapVisitor;
use std::fmt::Debug;

// NOTE: These defined in response.rs.in (as they need to derive Serialize)
// pub struct Step
// pub struct FailMessage

/// Types of responses produced by
/// [runners](../../runner/struct.WorldRunner.html)
#[derive(Eq, PartialEq, Clone, Debug)]
pub enum Response {
  StepMatches(StepMatchesResponse),
  Invoke(InvokeResponse),
  BeginScenario,
  EndScenario,
  SnippetText(String),
}

impl Serialize for Response {
  fn serialize<S: serde::ser::Serializer>(&self, s: &mut S) -> Result<(), S::Error> {
    match self {
      &Response::StepMatches(ref response) => {
        let empty_vec = Vec::new();
        let body = match response {
          &StepMatchesResponse::NoMatch => &empty_vec,
          &StepMatchesResponse::Match(ref steps) => steps,
        };
        s.serialize_seq(TupleVisitor2::new(&("success", body)))
      },
      &Response::Invoke(ref response) => {
        match response {
          &InvokeResponse::Pending(ref message) => {
            s.serialize_seq(TupleVisitor2::new(&("pending", message)))
          },
          &InvokeResponse::Success => s.serialize_seq(Some(&("success"))),
          &InvokeResponse::Fail(ref message) => {
            s.serialize_seq(TupleVisitor2::new(&("fail", message)))
          },
        }
      },
      &Response::BeginScenario => s.serialize_seq(Some(&("success"))),
      &Response::EndScenario => s.serialize_seq(Some(&("success"))),
      &Response::SnippetText(ref text) => {
        s.serialize_seq(TupleVisitor2::new(&("success", text.clone())))
      },
    }
  }
}

#[derive(Eq, PartialEq, Clone, Debug)]
pub struct StepArg {
  pub val: Option<String>,
  pub pos: Option<u32>,
}

impl Serialize for StepArg {
  fn serialize<S: serde::ser::Serializer>(&self, s: &mut S) -> Result<(), S::Error> {
    s.serialize_struct("StepArg",
                       StepArgVisitor {
                         value: self,
                         state: 0,
                       })
  }
}

struct StepArgVisitor<'a> {
  value: &'a StepArg,
  state: u8,
}

impl<'a> MapVisitor for StepArgVisitor<'a> {
  fn visit<S>(&mut self, serializer: &mut S) -> Result<Option<()>, S::Error>
    where S: serde::Serializer
  {
    match self.state {
      0 => {
        self.state += 1;
        match self.value.val {
          Some(ref v) => Ok(Some(try!(serializer.serialize_struct_elt("val", v.clone())))),
          None => Ok(Some(try!(serializer.serialize_struct_elt("val", ())))),
        }
      },
      1 => {
        self.state += 1;
        match self.value.pos {
          Some(ref v) => Ok(Some(try!(serializer.serialize_struct_elt("pos", v.clone())))),
          None => Ok(Some(try!(serializer.serialize_struct_elt("pos", ())))),
        }
      },
      _ => Ok(None),
    }
  }
}

// ["success", []"]
// ["success", []"]
// ["success", [{"id": "1", "args":[]]
// ["success", [{"id": "1", "args":[{"val": "wired", "pos": 10}]}]]
// https://www.relishapp.com/cucumber/cucumber/docs/wire-protocol/invoke-message
#[allow(dead_code)]
#[derive(Eq, PartialEq, Clone, Debug)]
pub enum StepMatchesResponse {
  NoMatch,
  Match(Vec<Step>),
}


/// The low level type capturing the possible outcomes a step invocation may
/// have.
///
/// Typical instantiation of this type will be done using the helpers provided.
///
/// This type is designed to be heavily composable, as it is the form many
/// operations against state
/// will take. If it doesn't suit a particular use case, that use case was
/// probably not conceived of and should be included!
// ["pending", "I'll do it later"]
// ["success"]
// ["fail", {"message": "The wires are down", "exception":
// "Some.Foreign.ExceptionType"}]
#[allow(dead_code)]
#[derive(Eq, PartialEq, Clone, Debug)]
pub enum InvokeResponse {
  Pending(String),
  Success,
  Fail(FailMessage),
}

impl InvokeResponse {
  /// Build an InvokeResponse::Pending with a message
  pub fn pending_from_str(val: &str) -> InvokeResponse {
    InvokeResponse::Pending(val.to_owned())
  }

  /// Build an InvokeResponse::Fail with a message
  pub fn fail_from_str(val: &str) -> InvokeResponse {
    InvokeResponse::Fail(FailMessage::new(val.to_owned()))
  }

  /// Return an InvokeResponse reflecting an equality check
  pub fn check_eq<T: PartialEq + Debug>(first: T, second: T) -> InvokeResponse {
    if first == second {
      InvokeResponse::Success
    } else {
      InvokeResponse::fail_from_str(&format!("Value [{:?}] was not equal to [{:?}]", first, second))
    }
  }

  /// Return an InvokeResponse reflecting a negative equality check
  pub fn check_not_eq<T: PartialEq + Debug>(first: T, second: T) -> InvokeResponse {
    if first == second {
      InvokeResponse::fail_from_str(&format!("Value [{:?}] was equal to [{:?}]", first, second))
    } else {
      InvokeResponse::Success
    }
  }

  /// Return an InvokeResponse reflecting a boolean outcome
  pub fn check(b: bool) -> InvokeResponse {
    if b {
      InvokeResponse::Success
    } else {
      InvokeResponse::fail_from_str("invoke response check failed")
    }
  }

  /// Return an InvokeResponse reflecting a boolean outcome with a custom
  /// message
  pub fn expect(b: bool, fail_msg: &str) -> InvokeResponse {
    if b {
      InvokeResponse::Success
    } else {
      InvokeResponse::fail_from_str(fail_msg)
    }
  }

  /// Compose InvokeResponses with "and" logic, exiting on non-success
  pub fn and(self, other: InvokeResponse) -> InvokeResponse {
    match self {
      InvokeResponse::Success => other,
      _ => self,
    }
  }

  /// Compose InvokeResponses with "or" logic, exiting on success
  pub fn or(self, other: InvokeResponse) -> InvokeResponse {
    match self {
      InvokeResponse::Fail(_) |
      InvokeResponse::Pending(_) => other,
      _ => self,
    }
  }
}

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

  #[test]
  fn invoke_response_check_eq() {
    let eq = InvokeResponse::check_eq(1, 1);
    let not_eq = InvokeResponse::check_eq(1, 2);

    assert_eq!(eq, InvokeResponse::Success);
    assert_eq!(not_eq,
               InvokeResponse::fail_from_str("Value [1] was not equal to [2]"));
  }

  #[test]
  fn invoke_response_check_not_eq() {
    let eq = InvokeResponse::check_not_eq(1, 1);
    let not_eq = InvokeResponse::check_not_eq(1, 2);

    assert_eq!(eq,
               InvokeResponse::fail_from_str("Value [1] was equal to [1]"));
    assert_eq!(not_eq, InvokeResponse::Success);
  }

  #[test]
  fn invoke_response_check() {
    let t = InvokeResponse::check(true);
    let f = InvokeResponse::check(false);

    assert_eq!(t, InvokeResponse::Success);
    assert_eq!(f,
               InvokeResponse::fail_from_str("invoke response check failed"));
  }

  #[test]
  fn invoke_response_expect() {
    let t = InvokeResponse::expect(true, "Unevaluated message");
    let f = InvokeResponse::expect(false, "Evaluated message");

    assert_eq!(t, InvokeResponse::Success);
    assert_eq!(f, InvokeResponse::fail_from_str("Evaluated message"));
  }

  #[test]
  fn invoke_response_and() {
    // T & T = T
    assert_eq!(InvokeResponse::Success,
               InvokeResponse::Success.and(InvokeResponse::Success));

    // T & F = F
    assert_eq!(InvokeResponse::fail_from_str("msg"),
               InvokeResponse::Success.and(InvokeResponse::fail_from_str("msg")));

    // F & T = F
    assert_eq!(InvokeResponse::fail_from_str("msg"),
               InvokeResponse::fail_from_str("msg").and(InvokeResponse::Success));

    // F1 & F2 = F1
    assert_eq!(InvokeResponse::fail_from_str("msg1"),
               InvokeResponse::fail_from_str("msg1").and(InvokeResponse::fail_from_str("msg2")));
  }

  #[test]
  fn invoke_response_or() {
    // T & T = T
    assert_eq!(InvokeResponse::Success,
               InvokeResponse::Success.or(InvokeResponse::Success));

    // T & F = T
    assert_eq!(InvokeResponse::Success,
               InvokeResponse::Success.or(InvokeResponse::fail_from_str("msg")));

    // F & T = T
    assert_eq!(InvokeResponse::Success,
               InvokeResponse::fail_from_str("msg").or(InvokeResponse::Success));

    // F1 & F2 = F2
    assert_eq!(InvokeResponse::fail_from_str("msg2"),
               InvokeResponse::fail_from_str("msg1").or(InvokeResponse::fail_from_str("msg2")));
  }

  #[test]
  fn it_serializes_step_matches_no_match() {
    let response = Response::StepMatches(StepMatchesResponse::NoMatch);
    let string = serde_json::to_string(&response);
    assert_eq!(string.unwrap(), "[\"success\",[]]");
  }

  #[test]
  fn it_serializes_step_matches_match() {
    let response = Response::StepMatches(StepMatchesResponse::Match(vec![Step {
                                                                           id: "1".to_owned(),
                                                                           source: "test"
                                                                             .to_owned(),
                                                                           args: vec![StepArg {
                                                                                   val: Some("arg"
                                                                                       .to_owned()),
                                                                                   pos: Some(0),
                                                                               }],
                                                                         }]));
    let string = serde_json::to_string(&response);
    assert_eq!(string.unwrap(),
               "[\"success\",[{\"id\":\"1\",\"args\":[{\"val\":\"arg\",\"pos\":0}],\"source\":\
                \"test\"}]]");
  }


  #[test]
  fn it_serializes_invoke_pending() {
    let response = Response::Invoke(InvokeResponse::pending_from_str("stuff isn't done"));
    let string = serde_json::to_string(&response);
    assert_eq!(string.unwrap(), "[\"pending\",\"stuff isn't done\"]");
  }

  #[test]
  fn it_serializes_invoke_success() {
    let response = Response::Invoke(InvokeResponse::Success);
    let string = serde_json::to_string(&response);
    assert_eq!(string.unwrap(), "[\"success\"]");
  }

  #[test]
  fn it_serializes_invoke_fail() {
    let response = Response::Invoke(InvokeResponse::fail_from_str("stuff is broken"));
    let string = serde_json::to_string(&response);
    assert_eq!(string.unwrap(),
               "[\"fail\",{\"message\":\"stuff is broken\",\"exception\":\"\"}]");
  }

  #[test]
  fn it_serializes_begin_scenario() {
    let response = Response::BeginScenario;
    let string = serde_json::to_string(&response);
    assert_eq!(string.unwrap(), "[\"success\"]");
  }

  #[test]
  fn it_serializes_end_scenario() {
    let response = Response::EndScenario;
    let string = serde_json::to_string(&response);
    assert_eq!(string.unwrap(), "[\"success\"]");
  }

  #[test]
  fn it_serializes_snippet_text() {
    let response = Response::SnippetText("Snippet".to_owned());
    let string = serde_json::to_string(&response);
    assert_eq!(string.unwrap(), "[\"success\",\"Snippet\"]");
  }
}