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
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
//! Definitions for creating and running criteria
//!
//! A criterion is one specific item in a series of items that form a grade.
//! Each criterion has a name, point value, and a related function.
//! Testing the criterion is running the function, which will return true
//! or false. A final grade can be calculated by adding up all the values
//! of the criteria, if they passed.
//!
//! The aim of this application is the make the definition of Criteria
//! as easy as possible, and the make that definition most of the work involved.
//! You shouldn't have to worry about students submitting, or persisting results.
//! Just define the criteria and distribute the program to your students.
use std::collections::HashMap;
use std::fmt;

use ansi_term::ANSIGenericString;
use ansi_term::Color::{Green, Red, White};

/// A macro to easily create a `HashMap<String, String>`
///
/// ## Example
/// ```rust
/// # #[macro_use] extern crate lab_grader;
/// # use std::collections::HashMap;
///
/// // The long way
/// let mut map = HashMap::new();
/// map.insert(String::from("key"), String::from("value"));
///
/// // the macro way
/// let data = data! { "key" => "value" };
/// assert_eq!(map, data);
/// ```
#[macro_export]
macro_rules! data(
    { $($key:expr => $value:expr),+ } => {
        {
            let mut m = ::std::collections::HashMap::new();
            $(
                m.insert(String::from($key), String::from($value));
            )+
            m
        }
     };
);

/// A criterion
///
/// This is the heart of the application. Each criterion is responsible for
/// checking one thing, and *one thing only*. You should build a list of criteria.
///
/// ## A lone `Criterion`
/// A Criterion has some informational fields (`name`, `messages`), a point value (`worth`),
/// a `status`, and most importantly a `test`. The test takes in a `HashMap<String, String>`
/// and returns a `bool`. The signature of every criterion's test is always the same.
///
///
/// ```rust
/// use std::collections::HashMap;
/// use lab_grader::*;
///
/// let mut crit = Criterion::new(
///     // Name
///     "My First Criterion",
///     // Worth
///     10,
///     // Pass/Fail messages, a tuple
///     ("passed", "failed"),
///     // Test function, contained in a Box
///     Box::new(|_: &HashMap<String, String>| -> bool {
///         // test code goes here
///         // determine if this should pass or fail
///         true
///     })
/// );
///
/// assert!(crit.status.is_none());
/// crit.test();
/// assert_eq!(crit.status, Some(true));
/// ```
///
///
/// We can also extract the test into a function defined elsewhere. This just helps with organization.
/// ```rust
/// # use std::collections::HashMap;
/// # use lab_grader::*;
/// fn my_test(_: &HashMap<String, String>) -> bool {
///     // code here...
///     true
/// }
///
/// fn main() {
///     let mut crit = Criterion::new(
///         "My Second Criterion",
///         10,
///         ("passed", "failed"),
///         Box::new(my_test)
///     );
///
///     crit.test();
///     // ...
/// }
/// ```
///
///
/// We can also pass data to a criterion. This data *must* be a `&HashMap<String, String>`
/// ```rust
/// # use std::collections::HashMap;
/// # use lab_grader::*;
///
/// fn my_test(data: &HashMap<String, String>) -> bool {
///     if let Some(value) = data.get("key") {
///         return value == "value"
///     }
///     false
/// }
///
/// fn main() {
///     let mut crit = Criterion::new(
///         "My Third Criterion",
///         10,
///         ("passed", "failed"),
///         Box::new(my_test)
///     );
///
///     // Now we need some data to pass to the criterion
///     // this crate provides a data macro that builds a HashMap
///     let data = data! {
///         "key" => "value"
///     };
///     crit.test_with_data(&data);
///     assert_eq!(crit.status, Some(true));
/// }
/// ```
pub struct Criterion {
    /// A short (< 30 characters), descriptive name
    pub name: String,
    /// Point value of this criterion. If it passes, this value
    /// will be added to the [`Submission`](crate::submission::Submission) grade.
    ///
    /// Can be negative if you wish to subtract points. Be sure to get your logic right.
    /// This value is added to the submission grade *if the test returns true*.
    pub worth: i16,
    /// Pass or fail messages, respectively
    ///
    /// When printing a criterion, the appropriate message
    /// will be printed. Not much use other than that.
    pub messages: (&'static str, &'static str),
    /// The criterion's test
    ///
    /// Determines if the criterion passes or fails. This signature is
    /// required.
    pub test: Box<dyn Fn(&HashMap<String, String>) -> bool>,
    /// If the test passed, failed, or hasn't been run.
    ///
    /// `None` if it hasn't been run, Some(`true`) or Some(`false`) otherwise.
    /// If this value is `Some`, the test has been run.
    pub status: Option<bool>,
    /// Currently does nothing because i'm lazy
    pub hide: bool,
}

impl Criterion {
    /// Creates a new Criterion with the given parameters.
    ///
    /// The `messages` parameter should be a tuple of
    /// `&str` containing a success then failure message, respectively.
    /// These messages will be printed when printing the criterion.
    ///
    /// The `test` parameter is a [`Box`][box] around a closure accepting
    /// a [HashMap][hashmap] returning a bool. This can get a bit confusing.
    /// The `test` closure should return true if the criterion passes, otherwise false.
    /// The `&HashMap` parameter allows data from outside the closure to be passed in. The signature
    /// of the `&HashMap` is `&HashMap<String, String>`, so all keys and values must be `String`s.
    /// This is done to generalize the `test` field, as all criteria must have the same signature.
    ///
    /// [hashmap]: std::collections::HashMap
    /// [box]: std::boxed::Box
    ///
    /// ## Example
    /// **A basic criterion**
    /// ```rust
    /// use std::collections::HashMap;
    /// use lab_grader::criterion::Criterion;
    ///
    /// let mut c = Criterion::new(
    ///     "A test criterion",
    ///     10,
    ///     ("Success!", "Failure!"),
    ///     Box::new(|_: &HashMap<String, String>| {
    ///         // Code to test criterion goes here,
    ///         // and should return false or...
    ///         true
    ///     })
    /// );
    /// assert!(c.test());
    /// ```
    ///
    /// **A criterion with data**
    /// ```rust
    /// # #[macro_use] extern crate lab_grader;
    /// # use lab_grader::criterion::Criterion;
    /// # use std::collections::HashMap;
    ///
    /// let mut c = Criterion::new(
    ///     "A test criterion with data!",
    ///     10,
    ///     ("Success!", "Failure!"),
    ///     Box::new(|data: &HashMap<String, String>| {
    ///         return data["my_key"] == "my_value";
    ///     })
    /// );
    ///
    /// // The above criterion takes a HashMap into it's closure,
    /// // so we must establish the data to send into the closure
    /// let my_data = data! {
    ///     "my_key" => "my_value"
    /// };
    ///
    /// assert!(c.test_with_data(&my_data));
    /// ```
    pub fn new<S: AsRef<str>>(
        name: S,
        worth: i16,
        messages: (&'static str, &'static str),
        test: Box<dyn Fn(&HashMap<String, String>) -> bool>,
    ) -> Self {
        Criterion {
            name: String::from(name.as_ref()),
            worth,
            messages,
            test,
            status: None,
            hide: false,
        }
    }

    /// Returns the success message, ie. the first message in the [`messages`][msg] tuple
    ///
    /// [msg]: Criterion::new
    pub fn success_message(&self) -> &'static str {
        self.messages.0
    }

    /// Returns the failure message, ie. the second message in the [`messages`][msg] tuple
    ///
    /// [msg]: Criterion::new
    pub fn failure_message(&self) -> &'static str {
        self.messages.1
    }


    /// Toggles the `hide` field on a criterion
    ///
    /// If hide is true, printing the criterion with the default
    /// formatter will print nothing. Good if you want a secret criterion
    /// that the students don't know about
    pub fn hide(&mut self) {
        self.hide = !self.hide;
    }

    /// Runs the criterion's test function with the data provided.
    ///
    /// This is almost equivilent to calling `(criterion.test)(data)`, but this
    /// method also sets the status of the criterion to the result of the test.
    /// You should avoid calling the test directly, and call this or the
    /// [`test`](Criterion::test) method instead.
    ///
    /// The criterion must be mutable to call this method, as the status is changed
    /// to the result of the test.
    ///
    /// ## Example
    /// ```rust
    /// # #[macro_use] extern crate lab_grader;
    /// # use lab_grader::criterion::Criterion;
    /// # use std::collections::HashMap;
    ///
    /// let mut c = Criterion::new(
    ///     "A test criterion with data!",
    ///     10,
    ///     ("Success!", "Failure!"),
    ///     Box::new(|data: &HashMap<String, String>| {
    ///         return data["my_key"] == "my_value";
    ///     })
    /// );
    ///
    /// let my_data = data! {
    ///     "my_key" => "my_value"
    /// };
    ///
    /// c.test_with_data(&my_data);
    /// // It's either Some(true) or Some(false) since we've tested
    /// assert!(c.status.is_some());
    /// ```
    pub fn test_with_data(&mut self, data: &HashMap<String, String>) -> bool {
        self.status = Some((self.test)(data));
        self.status.unwrap()
    }

    /// Runs the criterions test and assigns the result to `criterion.status`.
    ///
    /// This is equivilent to running [`test_with_data`](Criterion::test_with_data) with
    /// an empty `HashMap`.
    ///
    /// Criterion must be mutable.
    ///
    /// ## Example
    /// ```rust
    /// # use lab_grader::criterion::Criterion;
    /// # use std::collections::HashMap;
    ///
    /// let mut c = Criterion::new(
    ///     "A test criterion with data!",
    ///     10,
    ///     ("Success!", "Failure!"),
    ///     Box::new(|_: &HashMap<String, String>| {
    ///         true
    ///     })
    /// );
    ///
    /// assert!(c.test());
    /// assert!(c.status.is_some());
    /// ```
    pub fn test(&mut self) -> bool {
        self.test_with_data(&HashMap::new())
    }
}

/// Displays the results of the criterion.
/// You should test the criterion before printing it.
///
/// Output will be aligned, as you'll normally be printing
/// a lot of these at once.
///
/// Given a configuration with the name `Test criterion`,
/// success message `passed!`, and failure message `failed!`,
/// this is what would print:
///
/// **Printed before testing**
/// ```text
/// My first criterion  +**  not tested
/// ```
/// **Printed after a successful test**
/// ```text
/// My first criterion  +10  passed!
/// ```
/// **Printed after a failed test**
/// ```text
/// My first criterion  + 0  failed!
/// ```
impl fmt::Display for Criterion {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let name: ANSIGenericString<str>;
        let worth: ANSIGenericString<str>;
        let reason: ANSIGenericString<str>;
        if let Some(status) = self.status {
            if status {
                // success
                name = Green.paint(format!("{:>30}", &self.name));
                worth = Green.paint(format!("{:>2}", self.worth));
                reason = White.paint(self.success_message().to_string());
            } else {
                name = Red.paint(format!("{:>30}", &self.name));
                worth = Red.paint(format!("{:>2}", 0));
                reason = White.paint(self.failure_message().to_string());
                // Error
            }
        } else {
            // not yet run
            name = White.paint(format!("{:>30}", &self.name));
            worth = White.paint("**");
            reason = White.paint(format!("not tested"));
        }
        write!(f, "{}  +{}  {}", name, worth, reason)
    }
}

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

    #[test]
    fn test_new_criterion() {
        let mut c = Criterion::new(
            "A test criterion",
            10,
            ("passed!", "failed!"),
            Box::from(|_: &HashMap<String, String>| true),
        );
        assert_eq!(c.name, "A test criterion");
        assert_eq!(c.worth, 10);
        assert!(c.status.is_none());
        assert!(c.test());
        assert!(c.status.is_some());
    }

    #[test]
    fn test_a_criterion_with_data_passes() {
        let mut c = Criterion::new(
            "A test criterion",
            10,
            ("succes!", "failure!"),
            Box::from(|data: &HashMap<String, String>| {
                return data["my_var"] == "value";
            }),
        );

        let data = data! {
            "my_var" => "value"
        };

        assert!(c.test_with_data(&data));
    }

    #[test]
    fn test_success_and_failure_messages() {
        let c = Criterion::new(
            "A test criterion",
            10,
            ("passed!", "failed!"),
            Box::from(|_: &HashMap<String, String>| true),
        );
        assert_eq!(c.success_message(), "passed!");
        assert_eq!(c.failure_message(), "failed!");
    }

    #[test]
    fn test_display() {
        // This criterion will always pass
        let mut c = Criterion::new(
            "Test criterion",
            10,
            ("passed!", "failed!"),
            Box::from(|_: &HashMap<String, String>| true),
        );

        // Lots of hiddent characters following...
        // You need to test it before it will print successfully
        assert_eq!(format!("{}", c), "\u{1b}[37m                Test criterion\u{1b}[0m  +\u{1b}[37m**\u{1b}[0m  \u{1b}[37mnot tested\u{1b}[0m");

        // Test it first
        c.test();
        assert_eq!(format!("{}", c), "\u{1b}[32m                Test criterion\u{1b}[0m  +\u{1b}[32m10\u{1b}[0m  \u{1b}[37mpassed!\u{1b}[0m");

        // and this one will always fail
        let mut c2 = Criterion::new(
            "Test criterion",
            10,
            ("passed!", "failed!"),
            Box::from(|_: &HashMap<String, String>| false),
        );
        // Test it first
        c2.test();
        assert_eq!(format!("{}", c2), "\u{1b}[31m                Test criterion\u{1b}[0m  +\u{1b}[31m 0\u{1b}[0m  \u{1b}[37mfailed!\u{1b}[0m");
    }

    #[test]
    fn test_data_macro() {
        // The long way
        let mut map = HashMap::new();
        map.insert(String::from("key"), String::from("value"));

        // the macro way
        let data = data! { "key" => "value" };
        assert_eq!(map, data);
    }
}