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
//! A bundle of data that represents a students work.

// std uses
use std::collections::HashMap;

// external uses
use chrono::{DateTime, Local};
use serde::{Deserialize, Serialize};

// internal uses
use crate::prompt;
use crate::results_file::AsCsv;
use crate::criterion::Criterion;
use crate::server;

/// A submission is a bundle of data that represents
/// one student's submission. They will do some sort of work
/// for a lab, then run a rust script that builds some criteria,
/// runs those criteria with some data from the student, and submits
/// a Submission to a central webserver where the instructor can
/// collect the graded submissions.
#[derive(Debug, PartialEq, Deserialize, Serialize)]
pub struct Submission {
    /// A local timestamp when the submission was created
    pub time: DateTime<Local>,
    /// The students name
    pub name: String,
    /// The students institutional ID
    pub id: u32,
    /// Numerical grade for the submission.
    /// Each criterion will add to this grade if it passes.
    pub grade: i16,
    /// A hashmap of extra data that may be sent by the submission.
    /// Leave it empty if you don't need it
    pub data: HashMap<String, String>,
    /// The criteria (name) that this submission passed
    pub passed: Vec<String>,
    /// The citeria (name) that this submission failed
    pub failed: Vec<String>
}

impl Submission {
    /// Creates a new submission with a name and id.
    ///
    /// The `data` field is set to an empty HashMap, and `grade` is set to 0.
    ///
    /// *Hint*: If you want to start with a grade and bring the grade
    /// down for every criterion not passed, set the grade manually here and
    /// set the point value for each criterion to be a negative number.
    ///
    /// ## Example
    /// ```rust
    /// use lab_grader::submission::Submission;
    ///
    /// // You probably want it to be mutable so
    /// // you can attach data and change the grade
    /// let mut sub = Submission::new("Luke", 1234);
    ///
    /// assert_eq!(sub.name, "Luke");
    /// assert_eq!(sub.id, 1234);
    /// assert_eq!(sub.grade, 0);
    /// assert_eq!(sub.data.len(), 0);
    /// ```
    pub fn new<S: AsRef<str>>(name: S, id: u32) -> Submission {
        Submission {
            time: Local::now(),
            name: name.as_ref().to_string(),
            id,
            grade: 0,
            data: HashMap::new(),
            passed: Vec::new(),
            failed: Vec::new()
        }
    }


    /// Prompts the user for a name and ID number
    /// and returns a Submission. Equivalent to getting
    /// a name and ID from the console and calling
    /// `Submission::new()` with those values
    ///
    /// Warning: If the user doesn't enter valid values for name and id,
    /// this will **terminate the program**. Be sure that's what you want to do
    /// before using it.
    ///
    /// ## Example
    /// **Rust:**
    /// ```no_run
    /// # use lab_grader::submission::Submission;
    /// let mut sub = Submission::from_cli();
    /// ```
    /// **In the terminal:**
    /// ```text
    /// Name: Luke
    /// ID: 123
    /// ```
    /// **With invalid input:**
    /// ```text
    /// Name: Luke
    /// ID: not a number
    /// Could not parse input
    /// ```
    pub fn from_cli() -> Submission {
        let name = prompt!("Name: ", String);
        let id = prompt!("ID: ", u32);
        Submission::new(name, id)
    }

    /// Attaches data to a submission
    ///
    /// The data must be a [`HashMap<String, String>`](std::collections::HashMap).
    /// You may want to use the [`data!`](../macro.data.html) macro to make it
    /// easier to establish your data.
    ///
    /// ## Example
    /// ```rust
    /// # use lab_grader::data;
    /// # use lab_grader::submission::Submission;
    /// #
    /// let data = data! {
    ///     "key" => "value",
    ///     "key2" => "value2"
    /// };
    ///
    /// let mut sub = Submission::new("Luke", 1234);
    /// sub.use_data(data);
    ///
    /// assert_eq!(sub.data["key"], "value");
    /// assert_eq!(sub.data["key2"], "value2");
    /// ```
    pub fn use_data(&mut self, data: HashMap<String, String>) {
        self.data = data
    }

    /// Marks a criterion as passed. Provide the name of the criterion.
    ///
    /// This struct does not include an actual [`Criterion`](crate::criterion::Criterion)
    /// struct in it's `passed` and `failed` fields, because it's impossible to
    /// serialize a `Criterion`. `Submission`s must be serializable.
    ///
    /// ## Example
    /// ```rust
    /// # use lab_grader::submission::Submission;
    /// let mut sub = Submission::new("Luke", 1234);
    /// sub.pass("Some criterion name");
    ///
    /// assert!(sub.passed.contains(&"Some criterion name".to_string()));
    /// ```
    pub fn pass<C: AsRef<str>>(&mut self, criterion: C) {
        self.passed.push(criterion.as_ref().to_string());
    }

    /// Same as `pass`, but adds to the `failed` vector
    pub fn fail<C: AsRef<str>>(&mut self, criterion: C) {
        self.failed.push(criterion.as_ref().to_string());
    }

    /// Tests a submission against a list of criterion
    ///
    /// The submissions grade will change for every passed criterion,
    /// and every criterion will add it's name and message to the submissions
    /// `passed` or `failed` vectors.
    ///
    /// ## Example
    /// ```rust
    /// # use lab_grader::data;
    /// # use lab_grader::criterion::Criterion;
    /// # use lab_grader::submission::Submission;
    /// # use std::collections::HashMap;
    /// let mut sub = Submission::new("Luke", 1234);
    /// sub.use_data(data! {
    ///     "key" => "value"
    /// });
    /// // Just one criterion here to save space
    /// let mut crits: Vec<Criterion> = vec![
    ///     Criterion::new("Test Criterion", 10, ("passed", "failed"), Box::new(
    ///         |data: &HashMap<String, String>| {
    ///             data["key"] == "value"
    ///         }
    ///     ))
    /// ];
    /// sub.grade_against(&mut crits);
    /// assert_eq!(crits[0].status, Some(true));
    /// assert_eq!(sub.grade, 10);
    /// assert_eq!(sub.passed.len(), 1);
    /// assert_eq!(sub.failed.len(), 0);
    /// ```
    pub fn grade_against(&mut self, criteria: &mut Vec<Criterion>) {
        for crit in criteria {
            crit.test_with_data(&self.data);

            if crit.status.unwrap() {
                self.grade += crit.worth;
                self.pass(format!("{}: {}", crit.name, crit.success_message()));
            } else {
                self.fail(format!("{}: {}", crit.name, crit.failure_message()));
            }
        }
    }


    /// Spins up a webserver to accept submission.
    ///
    /// Accepted submissions will be written to a [`ResultsFile`](crate::results_file::ResultsFile).
    /// The web server will run on the provided port.
    ///
    /// The results file will be placed in the directory you execute the code in,
    /// and be called `results.csv`.
    ///
    /// Support for custom results file locations is coming...
    /// ```no_run
    /// use lab_grader::Submission;
    /// Submission::server(8080);
    /// ```
    pub fn server(port: u16) {
        server::run(port);
    }
}

impl AsCsv for Submission {
    fn as_csv(&self) -> String {
        let data_string = self.data.keys().map(|k| {
            format!("{}=>{}", k, self.data[k])
        }).collect::<Vec<String>>().join(";");

        format!(
            "{},{},{},{},{},{},{}",
            self.time.to_rfc3339(),
            self.name,
            self.id,
            self.grade,
            self.passed.join(";"),
            self.failed.join(";"),
            data_string
        )
    }

    fn filename(&self) -> String {
        String::from("submissions.csv")
    }

    fn header(&self) -> &'static str {
        "time,name,id,grade,passed,failed,data\n"
    }
}

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


    #[test]
    fn test_new_submission() {
        let sub = Submission::new("Luke", 1234);
        assert_eq!(sub.name, "Luke");
        assert_eq!(sub.id, 1234);
        assert!(sub.data.len() == 0);
    }

    #[test]
    fn test_submission_use_data() {
        let data = data! {
            "key" => "value"
        };
        let mut sub = Submission::new("Luke", 123);
        sub.use_data(data);
        assert!(sub.data.len() == 1);
        assert_eq!(sub.data["key"], "value");
    }

    #[test]
    fn test_submission_as_csv() {
        let mut sub = Submission::new("Luke", 1234);
        sub.use_data(data! { "k" => "v", "k2" => "v2" });

        // We can't directly compare it because the order of the
        // hashmap items will change arbitrarily
        assert!((&sub).as_csv().contains("Luke,1234,0,"));

        // Submission with no data, passes, or failures
        let sub2 = Submission::new("Luke", 1234);
        let expected = "Luke,1234,0,,,";
        assert!((&sub2).as_csv().contains(expected));
    }

    #[test]
    fn test_serialize_deserialize_json() {
        let mut sub = Submission::new("Luke", 1234);
        sub.use_data(data! { "k2" => "v2", "k" => "v" });
        sub.pass("something");
        sub.fail("something");

        let expected = r#"{"time":"2020-05-01T22:23:21.180875-05:00","name":"Luke","id":1234,"grade":0,"passed":["something"],"failed":["something"],"data":{"k2":"v2","k":"v"}}"#;
        assert!(serde_json::to_string(&sub).unwrap().contains(r#""name":"Luke""#));
        let built_sub: Submission = serde_json::from_str(expected).unwrap();
        assert_eq!(built_sub.name, sub.name);
        assert_eq!(built_sub.id, sub.id);
        assert_eq!(built_sub.grade, sub.grade);
    }

    #[test]
    fn test_grade_against_criteria() {
        let mut sub = Submission::new("Luke", 1234);
        sub.use_data(data! {
            "key" => "value"
        });

        // Just one criterion here to save space
        let mut crits: Vec<Criterion> = vec![
            Criterion::new("Test Criterion", 10, ("passed", "failed"), Box::new(
                |data: &HashMap<String, String>| {
                    data["key"] == "value"
                }
            ))
        ];

        sub.grade_against(&mut crits);
        assert_eq!(crits[0].status, Some(true));
        assert_eq!(sub.grade, 10);
        assert_eq!(sub.passed.len(), 1);
        assert_eq!(sub.failed.len(), 0);
    }
}