xref: /haiku/src/tests/kits/shared/NaturalCompareTest.cpp (revision 220d04022750f40f8bac8f01fa551211e28d04f2)
1 /*
2  * Copyright 2012, Axel Dörfler, axeld@pinc-software.de.
3  * Distributed under the terms of the MIT License.
4  */
5 
6 
7 #include "NaturalCompareTest.h"
8 
9 #include <NaturalCompare.h>
10 
11 #include <cppunit/TestCaller.h>
12 #include <cppunit/TestSuite.h>
13 
14 
15 using namespace BPrivate;
16 
17 
18 struct Sample {
19 	const char*	a;
20 	const char*	b;
21 	int			expectedResult;
22 };
23 
24 
25 NaturalCompareTest::NaturalCompareTest()
26 {
27 }
28 
29 
30 NaturalCompareTest::~NaturalCompareTest()
31 {
32 }
33 
34 
35 void
36 NaturalCompareTest::TestSome()
37 {
38 	static const Sample samples[] = {
39 		{NULL, NULL, 0},
40 		{NULL, "A", -1},
41 		{"a", "A", 0},
42 		{"ä", "a", 1},
43 		{"3", "99", -1},
44 		{"9", "19", -1},
45 		{"13", "99", -1},
46 		{"9", "111", -1},
47 		{"00000009", "111", -1},
48 		{"Hallo2", "hallo12", -1},
49 		{"Hallo 2", "hallo12", -1},
50 		{"Hallo  2", "hallo12", -1},
51 		{"Hallo  2 ", "hallo12", -1},
52 		{"12 äber 42", "12aber42", 1},
53 		{"12 äber 42", "12aber43", 1},
54 		{"12 äber 44", "12aber43", 1},
55 		{"12 äber 44", "12 aber45", 1},
56 	};
57 	_RunTests(samples, sizeof(samples) / sizeof(Sample));
58 }
59 
60 
61 /*static*/ void
62 NaturalCompareTest::AddTests(BTestSuite& parent)
63 {
64 	CppUnit::TestSuite& suite = *new CppUnit::TestSuite("NaturalCompareTest");
65 
66 	suite.addTest(new CppUnit::TestCaller<NaturalCompareTest>(
67 		"NaturalCompareTest::TestSome", &NaturalCompareTest::TestSome));
68 
69 	parent.addTest("NaturalCompareTest", &suite);
70 }
71 
72 
73 void
74 NaturalCompareTest::_RunTests(const Sample* samples, int count)
75 {
76 	for (int i = 0; i < count; i++) {
77 		const Sample& sample = samples[i];
78 
79 		_RunTest(sample.a, sample.b, sample.expectedResult);
80 		_RunTest(sample.b, sample.a, -sample.expectedResult);
81 	}
82 }
83 
84 
85 void
86 NaturalCompareTest::_RunTest(const char* a, const char* b, int expectedResult)
87 {
88 	int result = _Normalize(NaturalCompare(a, b));
89 
90 	char message[256];
91 	snprintf(message, sizeof(message), "\"%s\" vs. \"%s\" == %d, expected %d",
92 		a, b, result, expectedResult);
93 
94 	CppUnit::Asserter::failIf(result != expectedResult, message);
95 }
96 
97 
98 int
99 NaturalCompareTest::_Normalize(int result)
100 {
101 	if (result > 0)
102 		return 1;
103 	if (result < 0)
104 		return -1;
105 	return 0;
106 }
107