Skip to content

Commit 34f869f

Browse files
test(service-auth): add unit test for token parsing and validation sample
1 parent 13bb49a commit 34f869f

1 file changed

Lines changed: 82 additions & 0 deletions

File tree

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
// Copyright 2025 Google LLC
2+
//
3+
// Licensed under the Apache License, Version 2.0 (the "License");
4+
// you may not use this file except in compliance with the License.
5+
// You may obtain a copy of the License at
6+
//
7+
// http://www.apache.org/licenses/LICENSE-2.0
8+
//
9+
// Unless required by applicable law or agreed to in writing, software
10+
// distributed under the License is distributed on an "AS IS" BASIS,
11+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
// See the License for the specific language governing permissions and
13+
// limitations under the License.
14+
15+
'use strict';
16+
17+
const {expect} = require('chai');
18+
const sinon = require('sinon');
19+
const {OAuth2Client} = require('google-auth-library');
20+
const {main} = require('../receive');
21+
22+
describe('receiveRequestAndParseAuthHeader sample', () => {
23+
let verifyStub, consoleStub;
24+
25+
beforeEach(() => {
26+
verifyStub = sinon.stub(OAuth2Client.prototype, 'verifyIdToken');
27+
consoleStub = sinon.stub(console, 'log');
28+
});
29+
30+
afterEach(() => {
31+
sinon.restore();
32+
});
33+
34+
it('should log greeting if token is valid', async () => {
35+
const mockReq = {
36+
headers: {
37+
authorization: 'Bearer valid-token',
38+
},
39+
};
40+
41+
verifyStub.resolves({
42+
getPayload: () => ({email: 'test@example.com'}),
43+
});
44+
45+
await main(mockReq);
46+
expect(consoleStub.calledWith('Hello, test@example.com!\n')).to.be.true;
47+
});
48+
49+
it('should log error message if token is invalid', async () => {
50+
const mockReq = {
51+
headers: {
52+
authorization: 'Bearer invalid-token',
53+
},
54+
};
55+
56+
verifyStub.rejects(new Error('invalid'));
57+
58+
await main(mockReq);
59+
expect(consoleStub.calledWithMatch(/Invalid token: invalid/)).to.be.true;
60+
});
61+
62+
it('should log anonymous message if no auth header', async () => {
63+
const mockReq = {
64+
headers: {},
65+
};
66+
67+
await main(mockReq);
68+
expect(consoleStub.calledWith('Hello, anonymous user.\n')).to.be.true;
69+
});
70+
71+
it('should log unhandled format message if auth is not bearer', async () => {
72+
const mockReq = {
73+
headers: {
74+
authorization: 'Basic something',
75+
},
76+
};
77+
78+
await main(mockReq);
79+
expect(consoleStub.calledWith('Unhandled header format (Basic).\n')).to.be
80+
.true;
81+
});
82+
});

0 commit comments

Comments
 (0)