TestIcu.cxx 1.91 KB
Newer Older
1 2 3 4 5 6
/*
 * Unit tests for src/util/
 */

#include "config.h"
#include "lib/icu/Converter.hxx"
7 8
#include "util/AllocatedString.hxx"
#include "util/StringAPI.hxx"
9 10 11 12 13 14

#include <cppunit/TestFixture.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <cppunit/ui/text/TestRunner.h>
#include <cppunit/extensions/HelperMacros.h>

15 16
#include <stdexcept>

17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
#include <string.h>
#include <stdlib.h>

#ifdef HAVE_ICU_CONVERTER

static const char *const invalid_utf8[] = {
	"\xfc",
};

struct StringPair {
	const char *utf8, *other;
};

static constexpr StringPair latin1_tests[] = {
	{ "foo", "foo" },
	{ "\xc3\xbc", "\xfc" },
};

class TestIcuConverter : public CppUnit::TestFixture {
	CPPUNIT_TEST_SUITE(TestIcuConverter);
	CPPUNIT_TEST(TestInvalidCharset);
	CPPUNIT_TEST(TestLatin1);
	CPPUNIT_TEST_SUITE_END();

public:
	void TestInvalidCharset() {
43 44 45 46 47
		try {
			IcuConverter::Create("doesntexist");
			CPPUNIT_FAIL("Exception expected");
		} catch (const std::runtime_error &) {
		}
48 49 50 51
	}

	void TestLatin1() {
		IcuConverter *const converter =
52
			IcuConverter::Create("iso-8859-1");
53 54 55
		CPPUNIT_ASSERT(converter != nullptr);

		for (const auto i : invalid_utf8) {
56 57 58 59 60
			try {
				auto f = converter->FromUTF8(i);
				CPPUNIT_FAIL("Exception expected");
			} catch (const std::runtime_error &) {
			}
61 62 63 64
		}

		for (const auto i : latin1_tests) {
			auto f = converter->FromUTF8(i.utf8);
65 66
			CPPUNIT_ASSERT_EQUAL(true, StringIsEqual(f.c_str(),
								 i.other));
67 68

			auto t = converter->ToUTF8(i.other);
69 70
			CPPUNIT_ASSERT_EQUAL(true, StringIsEqual(t.c_str(),
								 i.utf8));
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
		}

		delete converter;
	}
};

CPPUNIT_TEST_SUITE_REGISTRATION(TestIcuConverter);

#endif

int
main(gcc_unused int argc, gcc_unused char **argv)
{
#ifdef HAVE_ICU_CONVERTER
	CppUnit::TextUi::TestRunner runner;
	auto &registry = CppUnit::TestFactoryRegistry::getRegistry();
	runner.addTest(registry.makeTest());
	return runner.run() ? EXIT_SUCCESS : EXIT_FAILURE;
#else
	return EXIT_SUCCESS;
#endif
}