Skip to content

Commit

Permalink
Remove Session in favor of private cookies. New testing API.
Browse files Browse the repository at this point in the history
Sessions
--------

This commit removes the `Session` type in favor of methods on the
`Cookies` types that allow for adding, removing, and getting private
(signed and encrypted) cookies. These methods provide a superset of
the functionality of `Session` while also being a minimal addition to
the existing API. They can be used to implement the previous `Session`
type as well as other forms of session storage. The new methods are:

  * Cookie::add_private(&mut self, Cookie)
  * Cookie::remove_private(&mut self, Cookie)
  * Cookie::get_private(&self, &str)

Resolves #20

Testing
-------

This commit removes the `rocket::testing` module. It adds the
`rocket::local` module which provides a `Client` type for local
dispatching of requests against a `Rocket` instance. This `local`
package subsumes the previous `testing` package.

Rocket Examples
---------------

The `forms`, `optional_result`, and `hello_alt_methods` examples have
been removed. The following example have been renamed:

  * extended_validation -> form_validation
  * hello_ranks -> ranking
  * from_request -> request_guard
  * hello_tls -> tls

Other Changes
-------------

This commit also includes the following smaller changes:

  * Config::{development, staging, production} constructors have been
    added for easier creation of default `Config` structures.
  * The `Config` type is exported from the root.
  * `Request` implements `Clone` and `Debug`.
  * `Request::new` is no longer exported.
  * A `Response::body_bytes` method was added to easily retrieve a
    response's body as a `Vec<u8>`.
  • Loading branch information
SergioBenitez committed Jun 9, 2017
1 parent 504a7fe commit b8ba7b8
Show file tree
Hide file tree
Showing 89 changed files with 1,241 additions and 1,452 deletions.
11 changes: 4 additions & 7 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,35 +8,32 @@ members = [
"contrib/",
"examples/cookies",
"examples/errors",
"examples/extended_validation",
"examples/forms",
"examples/form_validation",
"examples/hello_person",
"examples/query_params",
"examples/hello_world",
"examples/manual_routes",
"examples/optional_redirect",
"examples/optional_result",
"examples/redirect",
"examples/static_files",
"examples/todo",
"examples/content_types",
"examples/hello_ranks",
"examples/ranking",
"examples/testing",
"examples/from_request",
"examples/request_guard",
"examples/stream",
"examples/json",
"examples/msgpack",
"examples/handlebars_templates",
"examples/form_kitchen_sink",
"examples/config",
"examples/hello_alt_methods",
"examples/raw_upload",
"examples/pastebin",
"examples/state",
"examples/managed_queue",
"examples/uuid",
"examples/session",
"examples/raw_sqlite",
"examples/hello_tls",
"examples/tls",
"examples/fairings",
]
10 changes: 4 additions & 6 deletions examples/config/tests/common/mod.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
use rocket::{self, State};
use rocket::fairing::AdHoc;
use rocket::config::{self, Config, Environment};
use rocket::http::{Method, Status};
use rocket::http::Status;
use rocket::LoggingLevel;
use rocket::testing::MockRequest;
use rocket::local::Client;

struct LocalConfig(Config);

Expand Down Expand Up @@ -55,8 +55,6 @@ pub fn test_config(environment: Environment) {
// environment in `ignite()`. We'll read this back in the handler to config.
::std::env::set_var("ROCKET_ENV", environment.to_string());

// FIXME: launch fairings aren't run during tests since...the Rocket isn't
// being launch
let rocket = rocket::ignite()
.attach(AdHoc::on_attach(|rocket| {
println!("Attaching local config.");
Expand All @@ -65,7 +63,7 @@ pub fn test_config(environment: Environment) {
}))
.mount("/", routes![check_config]);

let mut request = MockRequest::new(Method::Get, "/check_config");
let response = request.dispatch_with(&rocket);
let client = Client::new(rocket).unwrap();
let response = client.get("/check_config").dispatch();
assert_eq!(response.status(), Status::Ok);
}
6 changes: 3 additions & 3 deletions examples/content_types/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,17 @@ use super::rocket;
use super::serde_json;
use super::Person;
use rocket::http::{Accept, ContentType, Header, MediaType, Method, Status};
use rocket::testing::MockRequest;
use rocket::local::Client;

fn test<H>(method: Method, uri: &str, header: H, status: Status, body: String)
where H: Into<Header<'static>>
{
let rocket = rocket::ignite()
.mount("/hello", routes![super::get_hello, super::post_hello])
.catch(errors![super::not_found]);
let mut request = MockRequest::new(method, uri).header(header);
let mut response = request.dispatch_with(&rocket);

let client = Client::new(rocket).unwrap();
let mut response = client.req(method, uri).header(header).dispatch();
assert_eq!(response.status(), status);
assert_eq!(response.body_string(), Some(body));
}
Expand Down
32 changes: 13 additions & 19 deletions examples/cookies/src/tests.rs
Original file line number Diff line number Diff line change
@@ -1,19 +1,20 @@
use std::collections::HashMap;

use super::rocket;
use rocket::testing::MockRequest;
use rocket::local::Client;
use rocket::http::*;
use rocket_contrib::Template;

const TEMPLATE_ROOT: &'static str = "templates/";

#[test]
fn test_submit() {
let rocket = rocket();
let mut request = MockRequest::new(Method::Post, "/submit")
let client = Client::new(rocket()).unwrap();
let response = client.post("/submit")
.header(ContentType::Form)
.body("message=Hello from Rocket!");
let response = request.dispatch_with(&rocket);
.body("message=Hello from Rocket!")
.dispatch();

let cookie_headers: Vec<_> = response.headers().get("Set-Cookie").collect();
let location_headers: Vec<_> = response.headers().get("Location").collect();

Expand All @@ -23,33 +24,26 @@ fn test_submit() {
}

fn test_body(optional_cookie: Option<Cookie<'static>>, expected_body: String) {
let rocket = rocket();
let mut request = MockRequest::new(Method::Get, "/");

// Attach a cookie if one is given.
if let Some(cookie) = optional_cookie {
request = request.cookie(cookie);
}
let client = Client::new(rocket()).unwrap();
let mut response = match optional_cookie {
Some(cookie) => client.get("/").cookie(cookie).dispatch(),
None => client.get("/").dispatch(),
};

let mut response = request.dispatch_with(&rocket);
assert_eq!(response.status(), Status::Ok);
assert_eq!(response.body_string(), Some(expected_body));
}

#[test]
fn test_index() {
// Render the template with an empty context to test against.
// Render the template with an empty context.
let mut context: HashMap<&str, &str> = HashMap::new();
let template = Template::show(TEMPLATE_ROOT, "index", &context).unwrap();

// Test the route without sending the "message" cookie.
test_body(None, template);

// Render the template with a context that contains the message.
context.insert("message", "Hello from Rocket!");

// Test the route with the "message" cookie.
let cookie = Cookie::new("message", "Hello from Rocket!");
let template = Template::show(TEMPLATE_ROOT, "index", &context).unwrap();
test_body(Some(cookie), template);
test_body(Some(Cookie::new("message", "Hello from Rocket!")), template);
}
8 changes: 4 additions & 4 deletions examples/errors/src/tests.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
use super::rocket;
use rocket::testing::MockRequest;
use rocket::http::{Method, Status};
use rocket::local::Client;
use rocket::http::Status;

fn test(uri: &str, status: Status, body: String) {
let rocket = rocket::ignite()
.mount("/", routes![super::hello])
.catch(errors![super::not_found]);
let mut req = MockRequest::new(Method::Get, uri);
let mut response = req.dispatch_with(&rocket);

let client = Client::new(rocket).unwrap();
let mut response = client.get(uri).dispatch();
assert_eq!(response.status(), status);
assert_eq!(response.body_string(), Some(body));
}
Expand Down
8 changes: 0 additions & 8 deletions examples/extended_validation/Cargo.toml

This file was deleted.

30 changes: 11 additions & 19 deletions examples/fairings/src/tests.rs
Original file line number Diff line number Diff line change
@@ -1,46 +1,38 @@
use super::rocket;
use rocket::testing::MockRequest;
use rocket::http::Method::*;
use rocket::local::Client;

#[test]
fn rewrite_get_put() {
let rocket = rocket();
let mut req = MockRequest::new(Get, "/");
let mut response = req.dispatch_with(&rocket);
let client = Client::new(rocket()).unwrap();
let mut response = client.get("/").dispatch();
assert_eq!(response.body_string(), Some("Hello, fairings!".into()));
}

#[test]
fn counts() {
let rocket = rocket();
let client = Client::new(rocket()).unwrap();

// Issue 1 GET request.
let mut req = MockRequest::new(Get, "/");
req.dispatch_with(&rocket);
client.get("/").dispatch();

// Check the GET count, taking into account _this_ GET request.
let mut req = MockRequest::new(Get, "/counts");
let mut response = req.dispatch_with(&rocket);
let mut response = client.get("/counts").dispatch();
assert_eq!(response.body_string(), Some("Get: 2\nPost: 0".into()));

// Issue 1 more GET request and a POST.
let mut req = MockRequest::new(Get, "/");
req.dispatch_with(&rocket);
let mut req = MockRequest::new(Post, "/");
req.dispatch_with(&rocket);
client.get("/").dispatch();
client.post("/").dispatch();

// Check the counts.
let mut req = MockRequest::new(Get, "/counts");
let mut response = req.dispatch_with(&rocket);
let mut response = client.get("/counts").dispatch();
assert_eq!(response.body_string(), Some("Get: 4\nPost: 1".into()));
}

#[test]
fn token() {
let rocket = rocket();
let client = Client::new(rocket()).unwrap();

// Ensure the token is '123', which is what we have in `Rocket.toml`.
let mut req = MockRequest::new(Get, "/token");
let mut res = req.dispatch_with(&rocket);
let mut res = client.get("/token").dispatch();
assert_eq!(res.body_string(), Some("123".into()));
}
6 changes: 3 additions & 3 deletions examples/form_kitchen_sink/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,19 +33,19 @@ impl<'v> FromFormValue<'v> for FormOption {
}

#[derive(Debug, FromForm)]
struct FormInput {
struct FormInput<'r> {
checkbox: bool,
number: usize,
#[form(field = "type")]
radio: FormOption,
password: String,
password: &'r RawStr,
#[form(field = "textarea")]
text_area: String,
select: FormOption,
}

#[post("/", data = "<sink>")]
fn sink(sink: Result<Form<FormInput>, Option<String>>) -> String {
fn sink<'r>(sink: Result<Form<'r, FormInput<'r>>, Option<String>>) -> String {
match sink {
Ok(form) => format!("{:?}", form.get()),
Err(Some(f)) => format!("Invalid form input: {}", f),
Expand Down

0 comments on commit b8ba7b8

Please sign in to comment.