aboutsummaryrefslogtreecommitdiff
path: root/tests/tutorial/mod.rs
blob: 54f9c9f8ac42abcb29699f4ebae33963d8068313 (plain)
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
use std::env::set_current_dir;
use std::fs;
use std::io::{BufRead, BufReader};
use std::path::Path;
use std::process::{Command, Stdio};
use std::thread::sleep;
use std::time::Duration;

use rand::prelude::*;

trait ExitStatusExt {
    fn check(self);
}

impl ExitStatusExt for std::process::ExitStatus {
    fn check(self) {
        assert!(self.success());
    }
}

const CARGO: &str = env!("CARGO");
const PROJECT_DIR: &str = env!("CARGO_MANIFEST_DIR");
const TOSIN_ADMIN: &str = env!("CARGO_BIN_EXE_tosin-admin");

fn get(url: &str) -> (hyper::StatusCode, String) {
    let get = async {
        use hyper::Client;

        let client = Client::new();

        let res = client.get(url.parse().unwrap()).await.unwrap();

        let status = res.status();

        let body = hyper::body::to_bytes(res).await.unwrap();
        let body = String::from_utf8_lossy(&body).into_owned();

        (status, body)
    };
    tokio::runtime::Builder::new_multi_thread()
        .enable_all()
        .build()
        .unwrap()
        .block_on(get)
}

pub fn step1(dest: &str) {
    // tosin-admin start-project {dest}
    set_current_dir(PROJECT_DIR).unwrap();
    set_current_dir("target").unwrap();
    if fs::metadata("tests").is_err() {
        fs::create_dir("tests").unwrap();
    }
    set_current_dir("tests").unwrap();
    fs::write("Cargo.toml", "[workspace]\nmembers = ['tutorial1']").unwrap();
    if fs::metadata(dest).is_ok() {
        fs::remove_dir_all(dest).unwrap();
    }
    Command::new(TOSIN_ADMIN)
        .args(&["start-project", dest])
        .status()
        .unwrap()
        .check();
    set_current_dir(dest).unwrap();
    assert!(fs::metadata("Cargo.toml").is_ok());
    assert!(fs::read_to_string("Cargo.toml").unwrap().contains("tosin = "));
    assert!(fs::metadata("src/main.rs").is_ok());
    assert!(fs::read_to_string("src/main.rs").unwrap().contains("tosin::main!"));

    // cargo run run-server
    let port = thread_rng().gen_range(8081u16..9000u16);
    let mut server = Command::new(CARGO)
        .args(&["run", "run-server", &format!("{}", port)])
        .stdout(Stdio::piped())
        .spawn()
        .unwrap();
    let mut server_output = String::new();
    let server_stdout = server.stdout.take().unwrap();
    let mut server_stdout = BufReader::new(server_stdout);
    server_stdout.read_line(&mut server_output).unwrap();
    assert!(server_output.contains(&format!("http://127.0.0.1:{}", port)));
    sleep(Duration::from_secs_f32(0.5));
    let server_poke = get(&format!("http://127.0.0.1:{}/", port));
    assert_eq!(server_poke.0, hyper::StatusCode::NOT_FOUND);
    if let Ok(Some(exit_status)) = server.try_wait() {
        exit_status.check();
    }
    server.kill().unwrap();

    // could `cargo run start-app polls` or `tosin-admin start-app polls` so
    // flip a coin i guess
    if random() {
        let mut cmd = Command::new(CARGO);
        cmd.arg("run");
        cmd
    } else {
        Command::new(TOSIN_ADMIN)
    }
        .args(&["start-app", "polls"])
        .status().unwrap().check();
    assert!(fs::metadata("src/polls/mod.rs").is_ok());

    // write views.rs
    fs::write("src/polls/views.rs", r#"
use tosin::http::{Reply, Response};

pub fn index() -> Response {
    "Hello, world. You're at the polls index.".into_response()
}
    "#).unwrap();

    // write urls.rs
    fs::write("src/polls/urls.rs", r#"
use tosin::urls::{UrlMap, url_map};

use super::views;

pub fn urls() -> UrlMap {
    url_map! {
        => views::index, // TODO name: "index"
    }
}
    "#).unwrap();

    // update main.rs
    fs::write("src/main.rs", r#"
use tosin::Settings;
use tosin::contrib::admin;
use tosin::urls::{UrlMap, url_map};

mod polls;

fn urls() -> UrlMap {
    url_map! {
        "polls" / ..polls::urls(),
        "admin" / ..admin::site::urls(),
    }
}

fn settings() -> Settings {
    Settings {
        ..Settings::default()
    }
}

tosin::main!(urls(), settings());
    "#).unwrap();

    // poke that new route
    let mut server = Command::new(CARGO)
        .args(&["run", "run-server", "8069"])
        .spawn()
        .unwrap();
    let server_poke = get("http://127.0.0.1:8069/polls/");
    assert_eq!(server_poke.0, hyper::StatusCode::OK);
    assert_eq!(server_poke.1, "Hello, world. You're at the polls index.");
    server.kill().unwrap();

    // vibe check
    let example_tutorial1 = Path::new(PROJECT_DIR).join("examples/tutorial01");
    for file in &["src/main.rs", "src/polls/mod.rs", "src/polls/urls.rs", "src/polls/views.rs"] {
        let this_file = fs::read_to_string(file).unwrap();
        let example_tutorial1_path = example_tutorial1.join(file);
        let example_tutorial1_file = fs::read_to_string(example_tutorial1_path).unwrap();
        assert_eq!(this_file.trim(), example_tutorial1_file.trim());
    }
}

pub fn step2(dest: &str) {
    step1(dest);
    todo!();
}