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 15using namespace BPrivate; 16 17 18struct Sample { 19 const char* a; 20 const char* b; 21 int expectedResult; 22}; 23 24 25NaturalCompareTest::NaturalCompareTest() 26{ 27} 28 29 30NaturalCompareTest::~NaturalCompareTest() 31{ 32} 33 34 35void 36NaturalCompareTest::TestSome() 37{ 38 static const Sample samples[] = { 39 // NULL in either side of the comparison 40 {NULL, NULL, 0}, 41 {NULL, "A", -1}, 42 {"A", NULL, 1}, 43 // Case insensitive 44 {"a", "A", 0}, 45 {"��", "��", 0}, 46 // Handling of accented characters 47 {"��", "a", 1}, 48 // Natural number ordering 49 {"3", "99", -1}, 50 {"9", "19", -1}, 51 {"13", "99", -1}, 52 {"9", "111", -1}, 53 {"00000009", "111", -1}, 54 // Natural number ordering, ignoring leading space 55 {"Hallo2", "hallo12", -1}, 56 {"Hallo 2", "hallo12", -1}, 57 {"Hallo 2", "hallo12", -1}, 58 {"Hallo 2 ", "hallo12", -1}, 59 // A mix of everything 60 {"12 ��ber 42", "12aber42", -1}, 61 {"12 ��ber 42", "12aber43", -1}, 62 {"12 ��ber 44", "12aber43", -1}, 63 {"12 ��ber 44", "12 aber45", -1}, 64 }; 65 _RunTests(samples, sizeof(samples) / sizeof(Sample)); 66} 67 68 69/*static*/ void 70NaturalCompareTest::AddTests(BTestSuite& parent) 71{ 72 CppUnit::TestSuite& suite = *new CppUnit::TestSuite("NaturalCompareTest"); 73 74 suite.addTest(new CppUnit::TestCaller<NaturalCompareTest>( 75 "NaturalCompareTest::TestSome", &NaturalCompareTest::TestSome)); 76 77 parent.addTest("NaturalCompareTest", &suite); 78} 79 80 81void 82NaturalCompareTest::_RunTests(const Sample* samples, int count) 83{ 84 for (int i = 0; i < count; i++) { 85 const Sample& sample = samples[i]; 86 87 _RunTest(sample.a, sample.b, sample.expectedResult); 88 _RunTest(sample.b, sample.a, -sample.expectedResult); 89 } 90} 91 92 93void 94NaturalCompareTest::_RunTest(const char* a, const char* b, int expectedResult) 95{ 96 int result = _Normalize(NaturalCompare(a, b)); 97 98 char message[256]; 99 snprintf(message, sizeof(message), "\"%s\" vs. \"%s\" == %d, expected %d", 100 a, b, result, expectedResult); 101 102 CppUnit::Asserter::failIf(result != expectedResult, message); 103} 104 105 106int 107NaturalCompareTest::_Normalize(int result) 108{ 109 if (result > 0) 110 return 1; 111 if (result < 0) 112 return -1; 113 return 0; 114} 115