1 #include <cxxtest/TestSuite.h>
3 #include <helper/units.h>
4 #include <glibmm/i18n.h>
5 #include <math.h>
7 class UnitsTest : public CxxTest::TestSuite {
8 public:
10 UnitsTest()
11 {
12 }
13 virtual ~UnitsTest() {}
15 // createSuite and destroySuite get us per-suite setup and teardown
16 // without us having to worry about static initialization order, etc.
17 static UnitsTest *createSuite() { return new UnitsTest(); }
18 static void destroySuite( UnitsTest *suite ) { delete suite; }
20 void testConversions()
21 {
22 struct Case { double x; char const *abbr; double pts; } const tests[] = {
23 { 1.0, "pt", 1.0 },
24 { 5.0, "pt", 5.0 },
25 { 1.0, "in", 72.0 },
26 { 2.0, "in", 144.0 },
27 { 254., "mm", 720.0 },
28 { 254., "cm", 7200. },
29 { 254., "m", 720000. },
30 { 1.5, "mm", (15 * 72. / 254) }
31 };
32 for (unsigned i = 0; i < G_N_ELEMENTS(tests); ++i) {
33 Case const &c = tests[i];
34 SPUnit const &unit = *sp_unit_get_by_abbreviation(N_(c.abbr));
36 double const calc_pts = sp_units_get_points(c.x, unit);
37 TS_ASSERT(approx_equal(calc_pts, c.pts));
39 double const calc_x = sp_points_get_units(c.pts, unit);
40 TS_ASSERT(approx_equal(calc_x, c.x));
42 double tmp = c.x;
43 bool const converted_to_pts = sp_convert_distance(&tmp, &unit, SP_PS_UNIT);
44 TS_ASSERT(converted_to_pts);
45 TS_ASSERT(approx_equal(tmp, c.pts));
47 tmp = c.pts;
48 bool const converted_from_pts = sp_convert_distance(&tmp, SP_PS_UNIT, &unit);
49 TS_ASSERT(converted_from_pts);
50 TS_ASSERT(approx_equal(tmp, c.x));
51 }
52 }
54 void testUnitTable()
55 {
56 TS_ASSERT(sp_units_table_sane());
57 }
59 private:
60 /* N.B. Wrongly returns false if both near 0. (Not a problem for current users.) */
61 bool approx_equal(double const x, double const y)
62 {
63 return fabs(x / y - 1) < 1e-15;
64 }
66 double sp_units_get_points(double const x, SPUnit const &unit)
67 {
68 SPUnit const &pt_unit = sp_unit_get_by_id(SP_UNIT_PT);
69 double const px = sp_units_get_pixels(x, unit);
70 return sp_pixels_get_units(px, pt_unit);
71 }
73 double sp_points_get_units(double const pts, SPUnit const &unit)
74 {
75 SPUnit const &pt_unit = sp_unit_get_by_id(SP_UNIT_PT);
76 double const px = sp_units_get_pixels(pts, pt_unit);
77 return sp_pixels_get_units(px, unit);
78 }
79 };
81 /*
82 Local Variables:
83 mode:c++
84 c-file-style:"stroustrup"
85 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
86 indent-tabs-mode:nil
87 fill-column:99
88 End:
89 */
90 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :encoding=utf-8:textwidth=99 :