use std::env;

mod util;
use util::var;

#[test]
fn load_buf_example() {
    let dotenv = "FOO = bar  \nD\n\n# comment\nBOP = b a z".as_bytes();
    util::setup();
    loadenv::load_buf(dotenv).unwrap();

    assert_eq!(var("FOO"), "bar");
    assert_eq!(var("BOP"), "b a z");
    assert_eq!(var("D"), "");
}

#[test]
fn load_buf_example_2() {
    let dotenv = "# favorite colors\n\nYELLOW = #f7e418\nBLUE = #1818f7".as_bytes();
    util::setup();
    loadenv::load_buf(dotenv).unwrap();

    assert_eq!(var("YELLOW"), "#f7e418");
    assert_eq!(var("BLUE"), "#1818f7");
}

#[test]
fn load_buf_overwrite_environment() {
    let dotenv = "#Overwrite FOO\nFOO = new".as_bytes();
    util::setup();
    env::set_var("FOO", "old");
    loadenv::load_buf(dotenv).unwrap();

    assert_eq!(var("FOO"), "old");
}

#[test]
fn load_buf_keep_last() {
    let dotenv = "FOO=first\nFOO=last".as_bytes();
    util::setup();
    loadenv::load_buf(dotenv).unwrap();

    assert_eq!(var("FOO"), "last")
}

#[test]
fn load_buf_err_begins_with_assignment() {
    let dotenv = "FOO = bar  \n=D\n\n# comment\nBOP = b a z".as_bytes();
    util::setup();
    let err = loadenv::load_buf(dotenv).unwrap_err();

    assert!(env::var("FOO").is_err());
    assert!(env::var("BOP").is_err());
    assert!(env::var("D").is_err());

    assert_eq!(err, "error on line 2: line begins with assignment");
}

#[test]
fn load_buf_err_illegal_char() {
    let dotenv = "FOO = bar  \nD\n\n# comment\nBoP = b a z".as_bytes();
    util::setup();
    let err = loadenv::load_buf(dotenv).unwrap_err();

    assert!(env::var("FOO").is_err());
    assert!(env::var("BOP").is_err());
    assert!(env::var("D").is_err());

    assert_eq!(err, "error on line 5: illegal character in key: `o`");
}
