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
use std::collections::HashMap;

use anyhow::{anyhow, Result};
use serde::{Deserialize, Serialize};

use crate::{helpers::Connection, metric::Metric, Formalize};

#[derive(PartialEq, Eq, Debug, Serialize, Deserialize, Clone)]
pub struct MinScore {
    pub absolute: Option<u32>,
    pub percentage: Option<u32>,
}

#[derive(PartialEq, Eq, Debug, Serialize, Deserialize, Clone)]
#[serde(untagged)]
pub enum HelperScore {
    MinScore(MinScore),
    ShortMinScore(u32),
}

impl From<HelperScore> for MinScore {
    fn from(helper_source: HelperScore) -> Self {
        match helper_source {
            HelperScore::MinScore(score) => score,
            HelperScore::ShortMinScore(source) => MinScore {
                percentage: Some(source),
                absolute: None,
            },
        }
    }
}

#[derive(PartialEq, Eq, Debug, Serialize, Deserialize, Clone)]
pub struct Evaluation {
    #[serde(default, alias = "Name", alias = "NAME")]
    pub name: Option<String>,
    #[serde(alias = "Description", alias = "DESCRIPTION")]
    pub description: Option<String>,
    #[serde(alias = "Metrics", alias = "METRICS")]
    pub metrics: Vec<String>,
    #[serde(
        default,
        rename = "min-score",
        alias = "Min-score",
        alias = "MIN-SCORE",
        skip_serializing
    )]
    pub _helper_min_score: Option<HelperScore>,
    #[serde(rename = "min-score", default, skip_deserializing)]
    pub min_score: Option<MinScore>,
}

impl Connection<Metric> for (&String, &Evaluation) {
    fn validate_connections(&self, potential_metric_names: &Option<Vec<String>>) -> Result<()> {
        if let Some(metric_names) = potential_metric_names {
            for metric_name in &self.1.metrics {
                if !metric_names.contains(metric_name) {
                    return Err(anyhow::anyhow!(
                        "Evaluation \"{evaluation_name}\" Metric \"{metric_name}\" not found under Scenario Metrics",
                        evaluation_name = self.0
                    ));
                }
            }
        } else {
            return Err(anyhow::anyhow!(
                "Evaluation \"{evaluation_name}\" requires Metrics but none found under Scenario",
                evaluation_name = self.0
            ));
        }
        Ok(())
    }
}

pub type Evaluations = HashMap<String, Evaluation>;

impl Formalize for Evaluation {
    fn formalize(&mut self) -> Result<()> {
        if let Some(helper_min_score) = &self._helper_min_score {
            self.min_score = Some(helper_min_score.to_owned().into());
        } else {
            return Err(anyhow!("An Evaluation is missing min-score"));
        }
        if let Some(score) = &self.min_score {
            if score.absolute.is_some() && score.percentage.is_some() {
                return Err(anyhow!(
                    "An Evaluations min-score can only have either Absolute or Percentage defined, not both"
                ));
            }
        }
        if self.metrics.is_empty() {
            return Err(anyhow!("An Evaluation must have at least one Metric"));
        }
        Ok(())
    }
}

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

    #[test]
    fn parses_sdl_with_evaluation() {
        let sdl = r#"
            name: test-scenario
            description: some description
            start: 2022-01-20T13:00:00Z
            end: 2022-01-20T23:00:00Z
            conditions:
                condition-1:
                    command: executable/path.sh
                    interval: 30
            metrics:
                metric-1:
                    type: MANUAL
                    artifact: true
                    max-score: 10
                metric-2:
                    type: CONDITIONAL
                    max-score: 10
                    condition: condition-1
            evaluations:
                evaluation-1:
                    description: some description
                    metrics:
                        - metric-1
                        - metric-2
                    min-score: 50
        "#;
        let evaluations = parse_sdl(sdl).unwrap().evaluations;
        insta::with_settings!({sort_maps => true}, {
                insta::assert_yaml_snapshot!(evaluations);
        });
    }

    #[test]
    #[should_panic(
        expected = "Evaluation \"evaluation-1\" Metric \"metric-2\" not found under Scenario Metrics"
    )]
    fn fails_with_missing_metric() {
        let sdl = r#"
        
            name: test-scenario
            description: some description
            start: 2022-01-20T13:00:00Z
            end: 2022-01-20T23:00:00Z
            conditions:
                condition-1:
                    command: executable/path.sh
                    interval: 30
            metrics:
                metric-1:
                    type: MANUAL
                    artifact: true
                    max-score: 10
            evaluations:
                evaluation-1:
                    description: some description
                    metrics:
                        - metric-1
                        - metric-2
                    min-score: 50
        "#;
        parse_sdl(sdl).unwrap();
    }

    #[test]
    fn parses_shorthand_evaluation() {
        let evaluation_string = r#"
          description: some-description
          metrics:
            - metric-1
            - metric-2
          min-score: 50
        "#;
        let mut evaluation: Evaluation = serde_yaml::from_str(evaluation_string).unwrap();
        assert!(evaluation.formalize().is_ok());
    }

    #[test]
    fn parses_longhand_evaluation() {
        let evaluation_string = r#"
        description: some-description
        metrics:
          - metric-1
          - metric-2
        min-score:
          absolute: 50
      "#;
        let mut evaluation: Evaluation = serde_yaml::from_str(evaluation_string).unwrap();
        assert!(evaluation.formalize().is_ok());
    }

    #[test]
    fn fails_to_parse_evaluation_with_both_scores() {
        let evaluation_string = r#"
          description: some-description
          metrics:
            - metric-1
            - metric-2
          min-score:
            absolute: 50
            percentage: 60
        "#;
        let mut evaluation: Evaluation = serde_yaml::from_str(evaluation_string).unwrap();
        assert!(evaluation.formalize().is_err());
    }
}