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