-
Notifications
You must be signed in to change notification settings - Fork 579
/
util.rs
311 lines (270 loc) · 9.98 KB
/
util.rs
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
/// This module provides utility types and traits for managing a test session
///
/// Tests start by using one of the `TestApp` constructors. All constrcutors return at least a
/// `TestApp` and `MockAnonymousUser`. The `MockAnonymousUser` can be used to issue requests
/// in an unauthenticated session.
///
/// A `TestApp` value provides raw access to the database through the `db` function and can
/// construct new users via the `db_new_user` function. This function returns a
/// `MockCookieUser`, which can be used to generate one or more tokens via its `db_new_token`
/// function, which in turn returns a `MockTokenUser`.
///
/// All three user types implement the `RequestHelper` trait which provides convenience methods for
/// constructing requests. Some of these methods, such as `publish` are expected to fail for an
/// unauthenticated user (or for other reasons) and return a `Response<T>`. The `Response<T>`
/// provides several functions to check the response status and deserialize the JSON response.
///
/// `MockCookieUser` and `MockTokenUser` provide an `as_model` function which returns a reference
/// to the underlying database model value (`User` and `ApiToken` respectively).
use std::{self, rc::Rc, sync::Arc};
use {conduit, conduit_middleware, diesel, serde};
use conduit::{Handler, Method, Request};
use conduit_test::MockRequest;
use cargo_registry::app::App;
use cargo_registry::middleware::current_user::AuthenticationSource;
use models::{ApiToken, User};
use super::{app, record, CrateList, CrateResponse, GoodCrate, PublishBuilder};
struct TestAppInner {
app: Arc<App>,
// The bomb needs to be held in scope until the end of the test.
_bomb: record::Bomb,
middle: conduit_middleware::MiddlewareBuilder,
}
/// A representation of the app and its database transaction
pub struct TestApp(Rc<TestAppInner>);
impl TestApp {
/// Create a `TestApp` with an empty database
pub fn empty() -> (Self, MockAnonymousUser) {
let (_bomb, app, middle) = app();
let inner = Rc::new(TestAppInner { app, _bomb, middle });
let anon = MockAnonymousUser {
inner: TestApp(Rc::clone(&inner)),
};
(TestApp(inner), anon)
}
// Create a `TestApp` with a database including a default user
pub fn with_user() -> (Self, MockAnonymousUser, MockCookieUser) {
let (app, anon) = TestApp::empty();
let user = app.db_new_user("foo");
(app, anon, user)
}
/// Create a `TestApp` with a database including a default user and its token
pub fn with_token() -> (Self, MockAnonymousUser, MockCookieUser, MockTokenUser) {
let (app, anon) = TestApp::empty();
let user = app.db_new_user("foo");
let token = user.db_new_token("bar");
(app, anon, user, token)
}
/// Obtain the database connection and pass it to the closure
///
/// Within each test, the connection pool only has 1 connection so it is necessary to drop the
/// connection before making any API calls. Once the closure returns, the connection is
/// dropped, ensuring it is returned to the pool and available for any future API calls.
pub fn db<T, F: FnOnce(&DieselConnection) -> T>(&self, f: F) -> T {
let conn = self.0.app.diesel_database.get().unwrap();
f(&conn)
}
/// Create a new user in the database and return a mock user session
pub fn db_new_user(&self, user: &str) -> MockCookieUser {
let user = self.db(|conn| ::new_user(user).create_or_update(conn).unwrap());
MockCookieUser {
inner: TestApp(Rc::clone(&self.0)),
user,
}
}
}
/// A colleciton of helper methods for the 3 authentication types
///
/// Helper methods go through public APIs, and should not modify the database directly
pub trait RequestHelper {
fn request_builder(&self, method: Method, path: &str) -> MockRequest;
fn app(&self) -> &TestApp;
/// Issue a GET request
fn get<T>(&self, path: &str) -> Response<T>
where
for<'de> T: serde::Deserialize<'de>,
{
let mut request = self.request_builder(Method::Get, path);
Response::new(self.app().0.middle.call(&mut request))
}
/// Issue a GET request that includes query parameters
fn get_with_query<T>(&self, path: &str, query: &str) -> Response<T>
where
for<'de> T: serde::Deserialize<'de>,
{
let mut request = self.request_builder(Method::Get, path);
request.with_query(query);
Response::new(self.app().0.middle.call(&mut request))
}
/// Issue a PUT request
fn put<T>(&self, path: &str, body: &[u8]) -> Response<T>
where
for<'de> T: serde::Deserialize<'de>,
{
let mut builder = self.request_builder(Method::Put, path);
let request = builder.with_body(body);
Response::new(self.app().0.middle.call(request))
}
/// Issue a DELETE request
fn delete<T>(&self, path: &str) -> Response<T>
where
for<'de> T: serde::Deserialize<'de>,
{
let mut request = self.request_builder(Method::Delete, path);
Response::new(self.app().0.middle.call(&mut request))
}
/// Get the crates owned by the specified user.
fn crates_owned_by_user_id(&self, id: i32) -> CrateList {
let query = format!("user_id={}", id);
self.get_with_query("/api/v1/crates", &query).good()
}
/// Publish a crate
fn publish(&self, publish_builder: PublishBuilder) -> Response<GoodCrate> {
let krate_name = publish_builder.krate_name.clone();
let response = self.put("/api/v1/crates/new", &publish_builder.body());
let callback_on_good = move |json: &GoodCrate| assert_eq!(json.krate.name, krate_name);
response.with_callback(Box::new(callback_on_good))
}
/// Request the JSON used for a crate's page
fn show_crate(&self, krate_name: &str) -> CrateResponse {
let url = format!("/api/v1/crates/{}", krate_name);
self.get(&url).good()
}
}
/// A type that can generate unauthenticated requests
pub struct MockAnonymousUser {
inner: TestApp,
}
impl RequestHelper for MockAnonymousUser {
fn request_builder(&self, method: Method, path: &str) -> MockRequest {
::req(method, path)
}
fn app(&self) -> &TestApp {
&self.inner
}
}
/// A type that can generate cookie authenticated requests
///
/// The `User` is directly injected into middleware extensions and thus the cookie logic is not
/// exercised.
pub struct MockCookieUser {
inner: TestApp,
user: User,
}
impl RequestHelper for MockCookieUser {
fn request_builder(&self, method: Method, path: &str) -> MockRequest {
let mut request = ::req(method, path);
request.mut_extensions().insert(self.user.clone());
request
.mut_extensions()
.insert(AuthenticationSource::SessionCookie);
request
}
fn app(&self) -> &TestApp {
&self.inner
}
}
impl MockCookieUser {
/// Returns a reference to the database `User` model
pub fn as_model(&self) -> &User {
&self.user
}
/// Creates a token and wraps it in a helper struct
///
/// This method updates the database directly
pub fn db_new_token(&self, name: &str) -> MockTokenUser {
let token = self
.inner
.db(|conn| ApiToken::insert(conn, self.user.id, name).unwrap());
MockTokenUser {
inner: TestApp(Rc::clone(&self.inner.0)),
token,
}
}
}
/// A type that can generate token authenticated requests
pub struct MockTokenUser {
inner: TestApp,
token: ApiToken,
}
impl RequestHelper for MockTokenUser {
fn request_builder(&self, method: Method, path: &str) -> MockRequest {
let mut request = ::req(method, path);
request.header("Authorization", &self.token.token);
request
}
fn app(&self) -> &TestApp {
&self.inner
}
}
impl MockTokenUser {
/// Returns a reference to the database `ApiToken` model
pub fn as_model(&self) -> &ApiToken {
&self.token
}
}
#[derive(Deserialize, Debug)]
pub struct Error {
pub detail: String,
}
#[derive(Deserialize)]
pub struct Bad {
pub errors: Vec<Error>,
}
pub type DieselConnection =
diesel::r2d2::PooledConnection<diesel::r2d2::ConnectionManager<diesel::PgConnection>>;
type ResponseResult = Result<conduit::Response, Box<std::error::Error + Send>>;
/// A type providing helper methods for working with responses
#[must_use]
pub struct Response<T> {
response: conduit::Response,
callback_on_good: Option<Box<Fn(&T)>>,
}
impl<T> Response<T>
where
for<'de> T: serde::Deserialize<'de>,
{
fn new(response: ResponseResult) -> Self {
Self {
response: t!(response),
callback_on_good: None,
}
}
fn with_callback(self, callback_on_good: Box<Fn(&T)>) -> Self {
Self {
response: self.response,
callback_on_good: Some(callback_on_good),
}
}
/// Assert that the response is good and deserialize the message
pub fn good(mut self) -> T {
if !::ok_resp(&self.response) {
panic!("bad response: {:?}", self.response.status);
}
let good = ::json(&mut self.response);
if let Some(callback) = self.callback_on_good {
callback(&good)
}
good
}
/// Assert the response status code and deserialze into a list of errors
///
/// Cargo endpoints return a status 200 on error instead of 400.
pub fn bad_with_status(&mut self, code: u32) -> Bad {
assert_eq!(self.response.status.0, code);
match ::bad_resp(&mut self.response) {
None => panic!("ok response: {:?}", self.response.status),
Some(b) => b,
}
}
}
impl Response<()> {
/// Assert that the status code is 404
pub fn assert_not_found(&self) {
assert_eq!((404, "Not Found"), self.response.status);
}
/// Assert that the status code is 403
pub fn assert_forbidden(&self) {
assert_eq!((403, "Forbidden"), self.response.status);
}
}