fix local timezone, add tests

This commit is contained in:
eV 2019-08-16 09:35:56 +00:00
parent 8bfaca9f9b
commit 5d38faeb40
5 changed files with 46 additions and 3 deletions

View File

@ -21,6 +21,8 @@ env:
global:
- LD_LIBRARY_PATH: /usr/local/lib
- CLIPPY: n
install:
- curl https://rustwasm.github.io/wasm-pack/installer/init.sh -sSf | sh
script: ./ci/travis.sh
notifications:
email: false

View File

@ -39,8 +39,6 @@ serde = { version = "1", optional = true }
wasm-bindgen = { version = "0.2" }
js-sys = "0.3" # contains FFI bindings for the JS Date API
[dev-dependencies]
serde_json = { version = "1" }
serde_derive = { version = "1" }
@ -48,6 +46,9 @@ bincode = { version = "0.8.0" }
num-iter = { version = "0.1.35", default-features = false }
doc-comment = "0.3"
[target.'cfg(target_arch = "wasm32")'.dev-dependencies]
wasm-bindgen-test = "0.2"
[package.metadata.docs.rs]
all-features = true

View File

@ -48,6 +48,16 @@ build_and_test() {
channel build -v --no-default-features --features serde,rustc-serialize
TZ=Asia/Katmandu channel test -v --no-default-features --features serde,rustc-serialize --lib
# wasm tests
touch tests/wasm.rs # ensure rebuild happens so TZ / NOW take effect
TZ=ACST-9:30 NOW=$(date +%s) wasm-pack test --node
touch tests/wasm.rs
TZ=EST4 NOW=$(date +%s) wasm-pack test --node
touch tests/wasm.rs
TZ=UTC0 NOW=$(date +%s) wasm-pack test --node
touch tests/wasm.rs
TZ=Asia/Katmandu NOW=$(date +%s) wasm-pack test --node
if [[ "$CHANNEL" == stable ]]; then
if [[ -n "$TRAVIS" ]] ; then
check_readme

View File

@ -97,7 +97,10 @@ impl Local {
pub fn now() -> DateTime<Local> {
use super::Utc;
let now: DateTime<Utc> = super::Utc::now();
now.with_timezone(&Local)
// Workaround missing timezone logic in `time` crate
let offset = FixedOffset::west((js_sys::Date::new_0().get_timezone_offset() as i32) * 60);
DateTime::from_utc(now.naive_utc(), offset)
}
}

27
tests/wasm.rs Normal file
View File

@ -0,0 +1,27 @@
extern crate chrono;
extern crate wasm_bindgen_test;
use chrono::prelude::*;
use wasm_bindgen_test::*;
use std::env;
#[wasm_bindgen_test]
fn now() {
let utc: DateTime<Utc> = Utc::now();
let local: DateTime<Local> = Local::now();
// Ensure time fetched is correct
let actual = Utc.datetime_from_str(env!("NOW"), "%s").unwrap();
assert!(utc - actual < chrono::Duration::minutes(5));
// Ensure offset retrieved when getting local time is correct
let expected_offset = match env!("TZ") {
"ACST-9:30" => FixedOffset::east(19 * 30 * 60),
"Asia/Katmandu" => FixedOffset::east(23 * 15 * 60), // No DST thankfully
"EST4" => FixedOffset::east(-4 * 60 * 60),
"UTC0" => FixedOffset::east(0),
_ => panic!("unexpected TZ"),
};
assert_eq!(&expected_offset, local.offset());
}