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
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use url::Url;
use wiremock::matchers::{header, method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};
use wiremock::{Request, Respond};

mod param;
use param::Params;

pub mod task;
use task::Task;

mod status;
use status::Status;

mod user;
use user::User;

mod priority;
use priority::Priority;

mod policy;
use policy::Policy;

mod space;
use space::Space;

pub mod project;
use project::Project;

mod api;
mod column;
use column::Column;

mod phid;
use phid::Phid;

pub fn status() -> status::StatusBuilder {
    status::StatusBuilder::default()
}

pub fn column() -> column::ColumnDataBuilder {
    column::ColumnDataBuilder::default()
}

pub fn project() -> project::ProjectDataBuilder {
    project::ProjectDataBuilder::default()
}

pub fn priority() -> priority::PriorityBuilder {
    priority::PriorityBuilder::default()
}

pub fn task() -> task::TaskDataBuilder {
    task::TaskDataBuilder::default()
}

pub fn user() -> user::UserDataBuilder {
    user::UserDataBuilder::default()
}

trait PhabRespond: Send + Sync {
    fn respond(
        &self,
        server: &PhabMockServer,
        params: &Params,
        request: &Request,
    ) -> ResponseTemplate;
}

struct AuthAndParse<R> {
    server: PhabMockServer,
    responder: R,
}

impl<R> Respond for AuthAndParse<R>
where
    R: PhabRespond,
{
    fn respond(&self, request: &Request) -> ResponseTemplate {
        let params = Params::new(&request.body).expect("Failed to parse request");
        let auth = params.get(&["api.token"]);

        match auth {
            None => ResponseTemplate::new(403).set_body_string("Missing auth token"),
            Some(a) if a != self.server.token() => {
                ResponseTemplate::new(403).set_body_string("Incorrect auth token")
            }
            _ => self.responder.respond(&self.server, &params, request),
        }
    }
}

struct Data {
    tasks: HashMap<u32, Task>,
    users: Vec<User>,
    default_priority: Priority,
    priorities: Vec<Priority>,
    statusses: Vec<Status>,
    projects: Vec<Project>,
}

struct Inner {
    server: MockServer,
    token: String,
    data: Mutex<Data>,
}

#[derive(Clone)]
pub struct PhabMockServer {
    inner: Arc<Inner>,
}

impl PhabMockServer {
    fn auth_and_parse<R>(&self, responder: R) -> AuthAndParse<R>
    where
        R: PhabRespond,
    {
        AuthAndParse {
            server: self.clone(),
            responder,
        }
    }

    async fn handle_post<R>(&self, p: &str, responder: R)
    where
        R: PhabRespond + 'static,
    {
        Mock::given(method("POST"))
            .and(path(p))
            .and(header("content-type", "application/x-www-form-urlencoded"))
            .respond_with(self.auth_and_parse(responder))
            .named("phid.lookup")
            .mount(&self.inner.server)
            .await;
    }

    pub async fn start() -> Self {
        let server = MockServer::start().await;

        let default_priority = Priority {
            value: 50,
            name: "normal".to_string(),
            color: "yellow".to_string(),
        };

        let data = Data {
            tasks: HashMap::new(),
            users: Vec::new(),
            default_priority,
            priorities: Vec::new(),
            statusses: Vec::new(),
            projects: Vec::new(),
        };
        let m = PhabMockServer {
            inner: Arc::new(Inner {
                server,
                token: "badgerbadger".to_string(),
                data: Mutex::new(data),
            }),
        };

        m.new_priority(10, "Low", "blue");
        m.new_priority(100, "High", "blue");

        let s = status()
            .value("open")
            .name("Open")
            .color("green")
            .special(status::Special::Default)
            .build()
            .unwrap();
        m.add_status(s);
        m.new_status("wip", "In Progress", Some("indigo"));
        let s = status()
            .value("closed")
            .name("Closed")
            .color("indigo")
            .special(status::Special::Closed)
            .closed(true)
            .build()
            .unwrap();
        m.add_status(s);

        m.handle_post("api/maniphest.search", api::maniphest::Search {})
            .await;
        m.handle_post("api/maniphest.info", api::maniphest::Info {})
            .await;
        m.handle_post("api/phid.lookup", api::phid::Lookup {}).await;
        m.handle_post("api/project.search", api::project::Search {})
            .await;
        m.handle_post("api/edge.search", api::edge::Search {}).await;
        m
    }

    pub fn uri(&self) -> Url {
        self.inner.server.uri().parse().expect("uri not a url")
    }

    pub fn token(&self) -> &str {
        &self.inner.token
    }

    pub async fn n_requests(&self) -> usize {
        self.inner
            .server
            .received_requests()
            .await
            .map(|v| v.len())
            .unwrap_or_default()
    }

    pub async fn requests(&self) -> Option<Vec<wiremock::Request>> {
        self.inner.server.received_requests().await
    }

    pub fn add_task(&self, task: Task) {
        let mut data = self.inner.data.lock().unwrap();
        data.tasks.insert(task.id, task);
    }

    pub fn add_project(&self, project: Project) {
        let mut data = self.inner.data.lock().unwrap();
        data.projects.push(project);
    }

    pub fn add_user(&self, u: User) {
        let mut data = self.inner.data.lock().unwrap();
        data.users.push(u);
    }

    pub fn add_status(&self, s: Status) {
        let mut data = self.inner.data.lock().unwrap();
        data.statusses.push(s);
    }

    pub fn add_priority(&self, p: Priority) {
        let mut data = self.inner.data.lock().unwrap();
        data.priorities.push(p);
    }

    pub fn get_task(&self, id: u32) -> Option<Task> {
        let data = self.inner.data.lock().unwrap();
        match data.tasks.get(&id) {
            Some(t) => Some(t.clone()),
            None => None,
        }
    }

    pub fn find_task(&self, phid: &Phid) -> Option<Task> {
        let data = self.inner.data.lock().unwrap();
        data.tasks
            .values()
            .find(|t| t.phid == *phid)
            .map(Clone::clone)
    }

    pub fn get_project(&self, id: u32) -> Option<Project> {
        let data = self.inner.data.lock().unwrap();
        data.projects.iter().find(|p| p.id == id).map(Clone::clone)
    }

    pub fn find_project(&self, phid: &Phid) -> Option<Project> {
        let data = self.inner.data.lock().unwrap();
        data.projects
            .iter()
            .find(|p| p.phid == *phid)
            .map(Clone::clone)
    }

    pub fn default_status(&self) -> Status {
        let data = self.inner.data.lock().unwrap();
        data.statusses
            .iter()
            .find(|s| s.special == Some(status::Special::Default))
            .map(Clone::clone)
            .expect("No default status")
    }

    pub fn default_priority(&self) -> Priority {
        let data = self.inner.data.lock().unwrap();
        data.default_priority.clone()
    }

    pub fn new_user(&self, name: &str, full_name: &str) -> User {
        let u = user::UserDataBuilder::default()
            .full_name(full_name)
            .name(name)
            .build()
            .unwrap();
        self.add_user(u.clone());
        u
    }

    pub fn new_priority(&self, value: u32, name: &str, color: &str) -> Priority {
        let p = priority()
            .value(value)
            .name(name)
            .color(color)
            .build()
            .unwrap();
        self.add_priority(p.clone());
        p
    }

    pub fn new_status(&self, value: &str, name: &str, color: Option<&str>) -> Status {
        let mut s = status();
        if let Some(color) = color {
            s.color(color);
        }
        let status = s.value(value).name(name).build().unwrap();
        self.add_status(status.clone());
        status
    }

    pub fn new_simple_task(&self, id: u32, user: &User) -> Task {
        let task = task()
            .id(id)
            .full_name(format!("Task T{}", id))
            .description(format!("Description of task T{}", id))
            .author(user.clone())
            .owner(user.clone())
            .priority(self.default_priority())
            .status(self.default_status())
            .build()
            .unwrap();
        self.add_task(task.clone());
        task
    }
}