1test_that("mixed units work", {
2   (m = c(set_units(1:3, km), set_units(4:6, g), allow_mixed = TRUE))
3
4   # select a subset
5   expect_s3_class(m[3:4], "mixed_units")
6   expect_s3_class(m[3], "mixed_units")
7
8# select a single units object:
9   expect_s3_class(m[[3]], "units")
10
11   m <- set_units(m, c(rep(c("m", "kg"), each = 3)))
12   expect_s3_class(m, "mixed_units")
13   units(m) = rep(c("mm", "mg"), each = 3)
14   expect_s3_class(m, "mixed_units")
15   # does the value get recycled?
16   expect_s3_class(set_units(m[1:3], "m"), "mixed_units")
17
18   # convert to units:
19   expect_s3_class(as_units( m[1:3] ), "units")
20
21# round-trip via units:
22   m0 <- mixed_units(as_units(m[1:3]))
23   expect_identical(m[1:3], m0)
24
25# Ops using by single unit: needs to be explicitly coerced to mixed_units:
26   expect_s3_class(m[1:3] * mixed_units(set_units(1, mm)), "mixed_units")
27   expect_s3_class(m[1:3] / mixed_units(set_units(1, mm)), "mixed_units")
28   expect_s3_class(m[1:3] + mixed_units(set_units(1, mm)), "mixed_units")
29   expect_s3_class(m[1:3] - mixed_units(set_units(1, mm)), "mixed_units")
30   expect_type(m[1:3] == mixed_units(set_units(1, mm)), "logical")
31   expect_type(m[1:3] != mixed_units(set_units(1, mm)), "logical")
32   expect_error(m[1:3] ^ mixed_units(set_units(1, mm)))
33
34   # FIXME: Ops.mixed_units and Ops.units must be the same method
35   # to avoid the warning and the error.
36   # We can discriminate by switchpatching.
37   expect_error(expect_warning(m[1:3] * set_units(1, mm)))
38
39   expect_s3_class(units(m), "mixed_symbolic_units")
40   expect_type(format(m), "character")
41   expect_type(as.character(units(m)), "character")
42   print(m)
43   expect_equal(drop_units(m), sapply(m, as.numeric))
44
45   str(m)
46   units_options(allow_mixed = TRUE)
47   m = c(set_units(1:3, km), set_units(4:6, g))
48   units_options(allow_mixed = FALSE)
49})
50
51test_that("order is preserved", {
52   x <- 1:10
53   u <- rep(c("m", "l"), 5)
54   m <- mixed_units(x, u)
55   m <- set_units(m, paste0("k", u), mode = "standard")
56
57   expect_equal(as.numeric(m), x / 1000)
58})
59
60test_that("unique.mixed_units works", {
61   x <- c(set_units(c(1, 1, 2), kg), set_units(c(4, 4, 5), s), allow_mixed = TRUE)
62   expect_equal(unique(x), c(set_units(c(1, 2), kg), set_units(c(4, 5), s), allow_mixed = TRUE))
63
64   y <- c(set_units(c(1, 1, 1), m/s), set_units(c(1, 1, 1), kg/s), allow_mixed = TRUE)
65   expect_equal(unique(y), c(set_units(1, m/s), set_units(1, kg/s), allow_mixed = TRUE))
66
67   z <- c(set_units(c(1, 2), kg), set_units(c(3, 4), s), set_units(c(2, 3), kg), allow_mixed = TRUE)
68   expect_equal(unique(z), c(set_units(c(1, 2), kg), set_units(c(3, 4), s), set_units(3, kg), allow_mixed = TRUE))
69})
70