-
Notifications
You must be signed in to change notification settings - Fork 129
/
Copy pathtestCliUtils.js
245 lines (234 loc) · 7.47 KB
/
testCliUtils.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
const fs = require('fs');
const util = require('util');
const { exec } = require('child_process');
const execAsync = util.promisify(exec);
const { expect } = require('chai');
const actions = require('../../../src/proxy/actions/Action');
const steps = require('../../../src/proxy/actions/Step');
const processor = require('../../../src/proxy/processors/push-action/audit');
const db = require('../../../src/db');
const { Repo } = require('../../../src/model');
// cookie file name
const GIT_PROXY_COOKIE_FILE = 'git-proxy-cookie';
/**
* @async
* @param {string} cli - The CLI command to be executed.
* @param {number} expectedExitCode - The expected exit code after the command
* execution. Typically, `0` for successful execution.
* @param {string} expectedMessages - The array of expected messages included
* in the output after the command execution.
* @param {string} expectedErrorMessages - The array of expected messages
* included in the error output after the command execution.
* @param {boolean} debug - Flag to enable detailed logging for debugging.
* @throws {AssertionError} Throws an error if the actual exit code does not
* match the `expectedExitCode`.
*/
async function runCli(
cli,
expectedExitCode = 0,
expectedMessages = null,
expectedErrorMessages = null,
debug = false,
) {
try {
console.log(`cli: '${cli}'`);
const { stdout, stderr } = await execAsync(cli);
if (debug) {
console.log(`stdout: ${stdout}`);
console.log(`stderr: ${stderr}`);
}
expect(0).to.equal(expectedExitCode);
if (expectedMessages) {
expectedMessages.forEach((expectedMessage) => {
expect(stdout).to.include(expectedMessage);
});
}
if (expectedErrorMessages) {
expectedErrorMessages.forEach((expectedErrorMessage) => {
expect(stderr).to.include(expectedErrorMessage);
});
}
} catch (error) {
const exitCode = error.code;
if (!exitCode) {
// an AssertionError is thrown from failing some of the expectations
// in the 'try' block: forward it to Mocha to process
throw error;
}
if (debug) {
console.log(`error.stdout: ${error.stdout}`);
console.log(`error.stderr: ${error.stderr}`);
}
expect(exitCode).to.equal(expectedExitCode);
if (expectedMessages) {
expectedMessages.forEach((expectedMessage) => {
expect(error.stdout).to.include(expectedMessage);
});
}
if (expectedErrorMessages) {
expectedErrorMessages.forEach((expectedErrorMessage) => {
expect(error.stderr).to.include(expectedErrorMessage);
});
}
} finally {
if (debug) {
console.log(`cli: '${cli}': done`);
}
}
}
/**
* Starts the server.
* @param {Object} service - The Git Proxy API service to be started.
* @return {Promise<void>} A promise that resolves when the service has
* successfully started. Does not return any value upon resolution.
*/
async function startServer(service) {
await service.start();
}
/**
* Closes the specified HTTP server gracefully. This function wraps the
* `close` method of the `http.Server` instance in a promise to facilitate
* async/await usage. It ensures the server stops accepting new connections
* and terminates existing ones before shutting down.
*
* @param {http.Server} server - The `http.Server` instance to close.
* @param {number} waitTime - The wait time after close.
* @return {Promise<void>} A promise that resolves when the server has been
* successfully closed, or rejects if an error occurs during closure. The
* promise does not return any value upon resolution.
*
* @throws {Error} If the server cannot be closed properly or if an error
* occurs during the close operation.
*/
async function closeServer(server, waitTime = 0) {
return new Promise((resolve, reject) => {
server.closeAllConnections();
server.close((err) => {
if (err) {
console.error('Failed to close the server:', err);
reject(err); // Reject the promise if there's an error
} else {
setTimeout(() => {
console.log(`Server closed successfully (wait time ${waitTime}).`);
resolve(); // Resolve the promise when the server is closed
}, waitTime);
}
});
});
}
/**
* Create local cookies file with an expired connect cookie.
*/
async function createCookiesFileWithExpiredCookie() {
await removeCookiesFile();
const cookies = [
// eslint-disable-next-line max-len
'connect.sid=s%3AuWjJK_VGFbX9-03UfvoSt_HFU3a0vFOd.jd986YQ17Bw4j1xGJn2l9yiF3QPYhayaYcDqGsNgQY4; Path=/; HttpOnly',
];
fs.writeFileSync(GIT_PROXY_COOKIE_FILE, JSON.stringify(cookies), 'utf8');
}
/**
* Remove local cookies file.
*/
async function removeCookiesFile() {
if (fs.existsSync(GIT_PROXY_COOKIE_FILE)) {
fs.unlinkSync(GIT_PROXY_COOKIE_FILE);
}
}
/**
* Add a new repo to the database.
* @param {object} newRepo The new repo attributes.
* @param {boolean} debug Print debug messages to console if true.
*/
async function addRepoToDb(newRepo, debug = false) {
const repos = await db.getRepos();
const found = repos.find((y) => y.project === newRepo.project && newRepo.name === y.name);
if (!found) {
await db.createRepo(newRepo);
await db.addUserCanPush(newRepo.name, 'admin');
await db.addUserCanAuthorise(newRepo.name, 'admin');
if (debug) {
console.log(`New repo added to database: ${newRepo}`);
}
} else {
if (debug) {
console.log(`New repo already found in database: ${newRepo}`);
}
}
}
/**
* Add a new git push record to the database.
* @param {string} id The ID of the git push.
* @param {string} repoUrl The repository url of the git push.
* @param {boolean} debug Flag to enable logging for debugging.
*/
async function addGitPushToDb(id, repoUrl, debug = false) {
const action = new actions.Action(
id,
'push', // type
'get', // method
Date.now(), // timestamp
new Repo(repoUrl),
);
const step = new steps.Step(
'authBlock', // stepName
false, // error
null, // errorMessage
true, // blocked
`\n\n\nGit Proxy has received your push:\n\nhttp://localhost:8080/requests/${id}\n\n\n`, // blockedMessage
null, // content
);
const commitData = [];
commitData.push({
tree: 'tree test',
parent: 'parent',
author: 'author',
committer: 'committer',
commitTs: 'commitTs',
message: 'message',
});
action.commitData = commitData;
action.addStep(step);
const result = await processor.exec(null, action);
if (debug) {
console.log(`New git push added to DB: ${util.inspect(result)}`);
}
}
/**
* Add new user record to the database.
* @param {string} username The user name.
* @param {string} password The user password.
* @param {string} email The user email.
* @param {string} gitAccount The user git account.
* @param {boolean} admin Flag to make the user administrator.
* @param {boolean} debug Flag to enable logging for debugging.
*/
async function addUserToDb(
username,
password,
email,
gitAccount,
admin = false,
debug = false,
) {
const result = await db.createUser(
username,
password,
email,
gitAccount,
admin,
);
if (debug) {
console.log(`New user added to DB: ${util.inspect(result)}`);
}
}
module.exports = {
runCli: runCli,
startServer: startServer,
closeServer: closeServer,
addRepoToDb: addRepoToDb,
addGitPushToDb: addGitPushToDb,
addUserToDb: addUserToDb,
createCookiesFileWithExpiredCookie: createCookiesFileWithExpiredCookie,
removeCookiesFile: removeCookiesFile,
};