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
|
- import fs from 'fs/promises';
- import { Command } from 'commander';
- import * as init from '../../src/commands/init';
- import logger from '../../src/logger';
- jest.mock('../../src/redteam/commands/init', () => ({
- redteamInit: jest.fn(),
- }));
- jest.mock('../../src/server/server', () => ({
- startServer: jest.fn(),
- BrowserBehavior: {
- ASK: 0,
- OPEN: 1,
- SKIP: 2,
- OPEN_TO_REPORT: 3,
- OPEN_TO_REDTEAM_CREATE: 4,
- },
- }));
- jest.mock('../../src/commands/init', () => {
- const actual = jest.requireActual('../../src/commands/init');
- return {
- ...actual,
- downloadDirectory: jest.fn(actual.downloadDirectory),
- downloadExample: jest.fn(actual.downloadExample),
- getExamplesList: jest.fn(actual.getExamplesList),
- };
- });
- jest.mock('fs/promises');
- jest.mock('path', () => ({
- ...jest.requireActual('path'),
- resolve: jest.fn(),
- }));
- jest.mock('../../src/constants');
- jest.mock('../../src/onboarding');
- jest.mock('../../src/telemetry');
- jest.mock('@inquirer/confirm');
- jest.mock('@inquirer/input');
- jest.mock('@inquirer/select');
- const mockFetch = jest.mocked(jest.fn());
- global.fetch = mockFetch;
- describe('init command', () => {
- beforeEach(() => {
- jest.clearAllMocks();
- });
- afterEach(() => {
- jest.restoreAllMocks();
- });
- describe('downloadFile', () => {
- it('should download a file successfully', async () => {
- const mockResponse = {
- ok: true,
- status: 200,
- text: jest.fn().mockResolvedValue('file content'),
- };
- mockFetch.mockResolvedValue(mockResponse);
- await init.downloadFile('https://example.com/file.txt', '/path/to/file.txt');
- expect(mockFetch).toHaveBeenCalledWith('https://example.com/file.txt');
- expect(fs.writeFile).toHaveBeenCalledWith('/path/to/file.txt', 'file content');
- });
- it('should throw an error if download fails', async () => {
- const mockResponse = {
- ok: false,
- status: 404,
- statusText: 'Not Found',
- };
- mockFetch.mockResolvedValue(mockResponse);
- await expect(
- init.downloadFile('https://example.com/file.txt', '/path/to/file.txt'),
- ).rejects.toThrow('Failed to download file: Not Found');
- });
- it('should handle network errors', async () => {
- mockFetch.mockRejectedValue(new Error('Network error'));
- await expect(
- init.downloadFile('https://example.com/file.txt', '/path/to/file.txt'),
- ).rejects.toThrow('Network error');
- });
- });
- describe('downloadDirectory', () => {
- it('should throw an error if fetching directory contents fails on both VERSION and main', async () => {
- const mockResponse = {
- ok: false,
- statusText: 'Not Found',
- };
- mockFetch.mockResolvedValueOnce(mockResponse).mockResolvedValueOnce(mockResponse);
- await expect(init.downloadDirectory('example', '/path/to/target')).rejects.toThrow(
- 'Failed to fetch directory contents: Not Found',
- );
- expect(mockFetch).toHaveBeenCalledTimes(2);
- expect(mockFetch.mock.calls[0][0]).toContain('?ref=');
- expect(mockFetch.mock.calls[1][0]).toContain('?ref=main');
- });
- it('should succeed if VERSION fails but main succeeds', async () => {
- const mockFailedResponse = {
- ok: false,
- statusText: 'Not Found',
- };
- const mockSuccessResponse = {
- ok: true,
- json: jest.fn().mockResolvedValue([]),
- };
- mockFetch
- .mockResolvedValueOnce(mockFailedResponse)
- .mockResolvedValueOnce(mockSuccessResponse);
- await init.downloadDirectory('example', '/path/to/target');
- expect(mockFetch).toHaveBeenCalledTimes(2);
- expect(mockFetch.mock.calls[0][0]).toContain('?ref=');
- expect(mockFetch.mock.calls[1][0]).toContain('?ref=main');
- });
- it('should handle network errors', async () => {
- mockFetch.mockRejectedValue(new Error('Network error'));
- await expect(init.downloadDirectory('example', '/path/to/target')).rejects.toThrow(
- 'Network error',
- );
- });
- });
- describe('downloadExample', () => {
- it('should throw an error if directory creation fails', async () => {
- jest.spyOn(fs, 'mkdir').mockRejectedValue(new Error('Permission denied'));
- await expect(init.downloadExample('example', '/path/to/target')).rejects.toThrow(
- 'Failed to download example: Permission denied',
- );
- });
- it('should throw an error if downloadDirectory fails', async () => {
- jest.spyOn(fs, 'mkdir').mockResolvedValue(undefined);
- // Mock fetch to simulate downloadDirectory failure
- mockFetch.mockRejectedValue(new Error('Network error'));
- await expect(init.downloadExample('example', '/path/to/target')).rejects.toThrow(
- 'Failed to download example: Network error',
- );
- });
- });
- describe('getExamplesList', () => {
- it('should return a list of examples', async () => {
- const mockResponse = {
- ok: true,
- status: 200,
- json: jest.fn().mockResolvedValue([
- { name: 'example1', type: 'dir' },
- { name: 'example2', type: 'dir' },
- { name: 'not-an-example', type: 'file' },
- ]),
- };
- mockFetch.mockResolvedValue(mockResponse);
- const examples = await init.getExamplesList();
- expect(examples).toEqual(['example1', 'example2']);
- });
- it('should return an empty array if fetching fails', async () => {
- const mockResponse = {
- ok: false,
- status: 404,
- statusText: 'Not Found',
- };
- mockFetch.mockResolvedValue(mockResponse);
- const examples = await init.getExamplesList();
- expect(examples).toEqual([]);
- expect(logger.error).toHaveBeenCalledWith(expect.stringContaining('Not Found'));
- });
- it('should handle network errors', async () => {
- mockFetch.mockRejectedValue(new Error('Network error'));
- const examples = await init.getExamplesList();
- expect(examples).toEqual([]);
- expect(logger.error).toHaveBeenCalledWith(expect.stringContaining('Network error'));
- });
- });
- describe('initCommand', () => {
- let program: Command;
- beforeEach(() => {
- program = new Command();
- init.initCommand(program);
- const initCmd = program.commands.find((cmd) => cmd.name() === 'init');
- if (!initCmd) {
- throw new Error('initCmd not found');
- }
- });
- it('should set up the init command correctly', () => {
- const initCmd = program.commands.find((cmd) => cmd.name() === 'init');
- expect(initCmd).toBeDefined();
- expect(initCmd?.description()).toBe(
- 'Initialize project with dummy files or download an example',
- );
- expect(initCmd?.options).toHaveLength(2);
- });
- });
- });
|