Giter Site home page Giter Site logo

iron-test's Introduction

Iron

Build Status Crates.io Status License

Extensible, Concurrency Focused Web Development in Rust.

Response Timer Example

Note: This example works with the current iron code in this repository (master branch). If you are using iron 0.6 from crates.io, please refer to the corresponding example in the branch 0.6-maintenance.

extern crate iron;
extern crate time;

use iron::prelude::*;
use iron::{typemap, AfterMiddleware, BeforeMiddleware};
use time::precise_time_ns;

struct ResponseTime;

impl typemap::Key for ResponseTime { type Value = u64; }

impl BeforeMiddleware for ResponseTime {
    fn before(&self, req: &mut Request) -> IronResult<()> {
        req.extensions.insert::<ResponseTime>(precise_time_ns());
        Ok(())
    }
}

impl AfterMiddleware for ResponseTime {
    fn after(&self, req: &mut Request, res: Response) -> IronResult<Response> {
        let delta = precise_time_ns() - *req.extensions.get::<ResponseTime>().unwrap();
        println!("Request took: {} ms", (delta as f64) / 1000000.0);
        Ok(res)
    }
}

fn hello_world(_: &mut Request) -> IronResult<Response> {
    Ok(Response::with((iron::StatusCode::OK, "Hello World")))
}

fn main() {
    let mut chain = Chain::new(hello_world);
    chain.link_before(ResponseTime);
    chain.link_after(ResponseTime);
    Iron::new(chain).http("localhost:3000");
}

Overview

Iron is a high level web framework built in and for Rust, built on hyper. Iron is designed to take advantage of Rust's greatest features - its excellent type system and its principled approach to ownership in both single threaded and multi threaded contexts.

Iron is highly concurrent and can scale horizontally on more machines behind a load balancer or by running more threads on a more powerful machine. Iron avoids the bottlenecks encountered in highly concurrent code by avoiding shared writes and locking in the core framework.

Iron is 100% safe code:

$ rg unsafe src | wc
       0       0       0

Philosophy

Iron is meant to be as extensible and pluggable as possible; Iron's core is concentrated and avoids unnecessary features by leaving them to middleware, plugins, and modifiers.

Middleware, Plugins, and Modifiers are the main ways to extend Iron with new functionality. Most extensions that would be provided by middleware in other web frameworks are instead addressed by the much simpler Modifier and Plugin systems.

Modifiers allow external code to manipulate Requests and Response in an ergonomic fashion, allowing third-party extensions to get the same treatment as modifiers defined in Iron itself. Plugins allow for lazily-evaluated, automatically cached extensions to Requests and Responses, perfect for parsing, accessing, and otherwise lazily manipulating an http connection.

Middleware are only used when it is necessary to modify the control flow of a Request flow, hijack the entire handling of a Request, check an incoming Request, or to do final post-processing. This covers areas such as routing, mounting, static asset serving, final template rendering, authentication, and logging.

Iron comes with only basic modifiers for setting the status, body, and various headers, and the infrastructure for creating modifiers, plugins, and middleware. No plugins or middleware are bundled with Iron.

Performance

Iron averages 72,000+ requests per second for hello world and is mostly IO-bound, spending over 70% of its time in the kernel send-ing or recv-ing data.*

* Numbers from profiling on my OS X machine, your mileage may vary.

Core Extensions

Iron aims to fill a void in the Rust web stack - a high level framework that is extensible and makes organizing complex server code easy.

Extensions are painless to build. Some important ones are:

Middleware:

Plugins:

Both:

This allows for extremely flexible and powerful setups and allows nearly all of Iron's features to be swappable - you can even change the middleware resolution algorithm by swapping in your own Chain.

* Due to the rapidly evolving state of the Rust ecosystem, not everything builds all the time. Please be patient and file issues for breaking builds, we're doing our best.

Underlying HTTP Implementation

Iron is based on and uses hyper as its HTTP implementation, and lifts several types from it, including its header representation, status, and other core HTTP types. It is usually unnecessary to use hyper directly when using Iron, since Iron provides a facade over hyper's core facilities, but it is sometimes necessary to depend on it as well.

Installation

If you're using Cargo, just add Iron to your Cargo.toml:

[dependencies.iron]
version = "*"

The documentation is hosted online and auto-updated with each successful release. You can also use cargo doc to build a local copy.

Check out the examples directory!

You can run an individual example using cargo run --bin example-name inside the examples directory. Note that for benchmarking you should make sure to use the --release flag, which will cause cargo to compile the entire toolchain with optimizations. Without --release you will get truly sad numbers.

Getting Help

Feel free to ask questions as github issues in this or other related repos.

The best place to get immediate help is on IRC, on any of these channels on the mozilla network:

  • #rust-webdev
  • #iron
  • #rust

One of the maintainers or contributors is usually around and can probably help. We encourage you to stop by and say hi and tell us what you're using Iron for, even if you don't have any questions. It's invaluable to hear feedback from users and always nice to hear if someone is using the framework we've worked on.

Maintainers

Jonathan Reem (reem) is the core maintainer and author of Iron.

Commit Distribution (as of 8e55759):

Jonathan Reem (415)
Zach Pomerantz (123)
Michael Sproul (9)
Patrick Tran (5)
Corey Richardson (4)
Bryce Fisher-Fleig (3)
Barosl Lee (2)
Christoph Burgdorf (2)
da4c30ff (2)
arathunku (1)
Cengiz Can (1)
Darayus (1)
Eduardo Bautista (1)
Mehdi Avdi (1)
Michael Sierks (1)
Nerijus Arlauskas (1)
SuprDewd (1)

License

MIT

iron-test's People

Contributors

amw-zero avatar bbigras avatar calebmer avatar emberian avatar ernestas-poskus avatar euclio avatar fuchsnj avatar gsingh93 avatar kevinastone avatar mayah avatar mcasper avatar onur avatar panicbit avatar reem avatar roxasshadow avatar skylerlipthay avatar untitaker avatar upsuper avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

iron-test's Issues

Build a set of helpers to simplify testing middleware

Currently it's not easily possible to quickly setup a project structure to test against.
For example, to test static_file middleware, I need to make sure that there is a certain directory layout with specific files in it which could be served.

We should build a set of helpers to simplify this (similar to what Cargo does).

The code may look like:

test!(serves_specific_non_default_file {
  let st = Static::new(Path::new(""));
  // mock request and give it to handle method
 // verify response
})

the test! macro will call the setup function and then call the actual test code.

The setup function will be defined once per tests module and will create a directory layout:

project("foo").file("index.html", "<html>hello</html>").build();

I'm currently adapting cargo testing support infrastructure to be used in iron_test.
I actually finished it today, but there was a bug in the code which rm-rf'ed '.' and all my code is gone, I'll need to recreate it tomorrow :)

Docs don't reflect the code

Just wanted to start off by saying I love Iron and all the associated projects, I think they're great ๐Ÿ˜„

I've got a couple quick questions about this repo, just to make sure I'm going insane.

The README show mock requests being built like request::new(<http_method>, <request_target>), while the actual request::new() function looks like it needs three arguments, the third being a reader.

The other functions shown, request::at, request::at_with and all of response, don't seem to exist at all.

So I just wanted to confirm, is this project 'unfinished' at the moment? Or am I entirely missing something?

Once again, thank you for all the work ๐Ÿ˜„

API Design

How would we feel about a request API that makes the request for you, broken down by HTTP method?
Something like:

mod request {
  pub fn get<H: Handler>(url: &str, handler: H) -> Response
  pub fn post<H: Handler>(url: &str, handler: H, data: Vec<u8>) -> Response
  // etc
}

It's a little more syntactic sugar than the previously outlined constructor API, but it would also DRY up end user's tests a bit more, and remove some duplicated setup patterns.

I'd being willing to implement either API, just thought of this while I was using this library to test an Iron project.

Take Modifier instead of Headers

Feature request: setting request headers is a bit cumbersome right now, it would be nice if the request::* functions took a Modifier instead of a Headers.

Borrowing in `extract_body_to_string` and `extract_body_to_bytes`?

I'd like to reuse response in such code:

// .. cut
        let body = response::extract_body_to_string(resp);
        assert_eq!(body, "expected-content");
        assert_eq!(resp.status.unwrap(), Status::Created);
// ..

Is it possible now?

Now it gives:

   |
93 |         let body = response::extract_body_to_string(resp);
   |                                                     ---- value moved here
...
96 |         assert_eq!(resp.status.unwrap(), Status::Created);
   |                    ^^^^^^^^^^^ value used here after move
   |
   = note: move occurs because `resp` has type `iron::Response`, which does not implement the `Copy` trait

Example in docs does not work

Description

Executing cargo test with the provided example does not work.

$ cargo test                                                                                                                                                                        โœฑ
   Compiling hello-world v0.0.1 (file:///Users/willweiss/dev/rust/hello-world)
src/main.rs:21:64: 21:70 error: no method named `unwrap` found for type `iron::Response` in the current scope
src/main.rs:21     let result_body = response::extract_body_to_bytes(response.unwrap());
                                                                              ^~~~~~
error: aborting due to previous error
error: Could not compile `hello-world`.

Changing the test to read:

#[test]
fn test_hello_world() {
    let res = request::get("http://localhost:3000/hello",
                                Headers::new(),
                                &HelloWorldHandler).unwrap();
    let result_body = response::extract_body_to_bytes(res);

    assert_eq!(result_body, b"Hello, world!");
}

Fixes the issue as iron_test::response::extract_body_to_bytes takes an argument of type iron::response::Response per the docs.

Thanks in advance!

Environment

darwin 14.5.0
cargo 0.10.0-nightly (10ddd7d 2016-04-08)
iron 0.3.0
iron-test 0.3.0

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.