1/*
2 * Copyright 2023, Andrew Lindesay <apl@lindesay.co.nz>.
3 * All rights reserved. Distributed under the terms of the MIT License.
4 */
5
6
7#include "JwtTokenHelperTest.h"
8
9#include <String.h>
10
11#include <cppunit/TestCaller.h>
12#include <cppunit/TestSuite.h>
13
14#include <string.h>
15
16#include "JwtTokenHelper.h"
17
18
19JwtTokenHelperTest::JwtTokenHelperTest()
20{
21}
22
23
24JwtTokenHelperTest::~JwtTokenHelperTest()
25{
26}
27
28
29void
30JwtTokenHelperTest::TestParseTokenClaims()
31{
32	const char* jwtToken = "eyJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJkZXYuaGRzIiwic3ViIj"
33		"oiZXJpazY0QGhkcyIsImV4cCI6MTY5MzkwNzM1NywiaWF0IjoxNjkzOTA3MDU3fQ.DJOz0"
34		"TmgN0Ya8De-oV0mBwWb-8FYavLbaFUFhCLqr-s";
35	BMessage actualMessage;
36
37// ----------------------
38	status_t result = JwtTokenHelper::ParseClaims(BString(jwtToken), actualMessage);
39// ----------------------
40
41	CPPUNIT_ASSERT_EQUAL(B_OK, result);
42
43	_AssertStringValue(actualMessage, "iss", "dev.hds");
44	_AssertStringValue(actualMessage, "sub", "erik64@hds");
45	_AssertDoubleValue(actualMessage, "exp", 1693907357);
46	_AssertDoubleValue(actualMessage, "iat", 1693907057);
47}
48
49
50void
51JwtTokenHelperTest::TestCorrupt()
52{
53	const char* jwtToken = "application/json";
54	BMessage actualMessage;
55
56// ----------------------
57	status_t result = JwtTokenHelper::ParseClaims(BString(jwtToken), actualMessage);
58// ----------------------
59
60	CPPUNIT_ASSERT(B_OK != result);
61}
62
63
64/*static*/ void
65JwtTokenHelperTest::AddTests(BTestSuite& parent)
66{
67	CppUnit::TestSuite& suite = *new CppUnit::TestSuite("JwtTokenHelperTest");
68
69	suite.addTest(
70		new CppUnit::TestCaller<JwtTokenHelperTest>(
71			"JwtTokenHelperTest::TestParseTokenClaims",
72			&JwtTokenHelperTest::TestParseTokenClaims));
73
74	suite.addTest(
75		new CppUnit::TestCaller<JwtTokenHelperTest>(
76			"JwtTokenHelperTest::TestCorrupt",
77			&JwtTokenHelperTest::TestCorrupt));
78
79	parent.addTest("JwtTokenHelperTest", &suite);
80}
81
82
83void
84JwtTokenHelperTest::_AssertStringValue(const BMessage& message, const char* key,
85	const char* expectedValue) const
86{
87	BString value;
88	status_t result = message.FindString(key, &value);
89	CPPUNIT_ASSERT_EQUAL(B_OK, result);
90	CPPUNIT_ASSERT_EQUAL(BString(expectedValue), value);
91}
92
93
94void
95JwtTokenHelperTest::_AssertDoubleValue(const BMessage& message, const char* key,
96	int64 expectedValue) const
97{
98	double value;
99	status_t result = message.FindDouble(key, &value);
100	CPPUNIT_ASSERT_EQUAL(B_OK, result);
101	CPPUNIT_ASSERT_EQUAL((double) expectedValue, value);
102}