Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Prevent override of file if multiple XHR for same endpoint found and treat search params as folder #20

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,5 @@
/tmp
/yarn.lock
node_modules
/.DS_Store
.DS_Store
/coverage
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import type { Entry } from '../../../types';
export const entrysToPathsWithData = (entrys: Entry[], targetPath: string) =>
entrys.map((entry) => {
const parsedUrl = new URL(entry.request.url);
const filePath = path.join(targetPath, parsedUrl.pathname);
const filePath = path.join(targetPath, parsedUrl.pathname, parsedUrl.search);
const fileName = `${entry.request.method.toUpperCase()}.json`;
const fileData = entry.response.content.text;
return {
Expand Down
13 changes: 13 additions & 0 deletions src/har-to-mocks/features/write-mocks/utils/unique-filename.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import fs from 'fs';

export const getUniqueFileName = (baseFileName: string, filePath: string) => {
let counter = 1;
let fileName = baseFileName;

while (fs.existsSync(`${filePath}/${fileName}`)) {
fileName = `${counter}_${fileName}`;
counter++;
}

return fileName;
};
12 changes: 11 additions & 1 deletion src/har-to-mocks/features/write-mocks/write-mocks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,11 @@ import path from 'path';
import type { Entry, Logger } from '../../types';
import { folderTree } from '../folder-tree';
import { entrysToPathsWithData } from './utils';
import { getUniqueFileName } from './utils/unique-filename';

interface Options {
isDryRun: boolean;
shouldCreateUnique: boolean;
}

export const writeMocks = (targetPath: string, data: Entry[], log: Logger, options: Options): void => {
Expand All @@ -20,8 +22,16 @@ export const writeMocks = (targetPath: string, data: Entry[], log: Logger, optio
} else {
cli.action.start('\nwriting files');
newFiles.forEach(({ filePath, fileName, fileData }) => {
if (!fileData) {
return;
}
ensureDirSync(filePath);
writeFileSync(path.join(filePath, fileName), fileData);
try {
const uniqueFileName = options.shouldCreateUnique ? getUniqueFileName(fileName, filePath) : fileName;
writeFileSync(path.join(filePath, uniqueFileName), fileData);
} catch (error) {
console.error('Error writing file:', error);
}
});
cli.action.stop();
}
Expand Down
4 changes: 2 additions & 2 deletions src/har-to-mocks/har-to-mocks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ export class HarToMocksProcess {
this.data = filtred;
}

write(targetPath: string, isDryRun = false) {
writeMocks(targetPath, this.data, this.log, { isDryRun });
write(targetPath: string, isDryRun = false, shouldCreateUnique = false) {
writeMocks(targetPath, this.data, this.log, { isDryRun, shouldCreateUnique });
}
}
3 changes: 2 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ class HarToMocks extends Command {
description: 'filter by resourceType',
default: ResourceType.xhr,
}),
uniqueFiles: flags.boolean({ description: 'to create unique files per each xhr' }),

// flag to not write files, just show results (--dry-run)
'dry-run': flags.boolean({ description: 'to not write files, just show results' }),
Expand Down Expand Up @@ -62,7 +63,7 @@ class HarToMocks extends Command {
}

if (args.to && typeof args.to === 'string') {
process.write(args.to, usedFlags['dry-run']);
process.write(args.to, usedFlags['dry-run'], usedFlags.uniqueFiles);
}

// this is bottom padding
Expand Down
22 changes: 17 additions & 5 deletions tests/integration.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ Filtered requests:
─────────────────────── ────── ───────────────────────────
userRoles GET /api/service/userRoles
currentUserId GET /api/service/currentUserId
currentUserId GET /api/service/currentUserId
active GET /api/service/clients/active

`);
Expand Down Expand Up @@ -46,6 +47,7 @@ Filtered requests:
─────────────────────── ────── ───────────────────────────
userRoles GET /api/service/userRoles
currentUserId GET /api/service/currentUserId
currentUserId GET /api/service/currentUserId
active GET /api/service/clients/active

Folder tree which will be applied:
Expand All @@ -56,7 +58,10 @@ Folder tree which will be applied:
├─ userRoles
│ └─ GET.json
├─ currentUserId
│ └─ GET.json
│ ├─ ?abc=123
│ │ └─ GET.json
│ └─ ?filter=test
│ └─ GET.json
└─ clients
└─ active
└─ GET.json
Expand All @@ -70,14 +75,15 @@ No files were written. If you want to write files remove the (--dry-run) flag.
.stdout()
.do(() => cmd.run(['./tests/mocks/sample.har', './mocks']))
.it('should write files to fs', (ctx) => {
expect(fsExtra.writeFileSync).toBeCalledTimes(3);
expect(fsExtra.writeFileSync).toBeCalledTimes(4);
expect(ctx.stdout).toBe(`
Filtered requests:

Name Method Path
─────────────────────── ────── ───────────────────────────
userRoles GET /api/service/userRoles
currentUserId GET /api/service/currentUserId
currentUserId GET /api/service/currentUserId
active GET /api/service/clients/active

Folder tree which will be applied:
Expand All @@ -88,7 +94,10 @@ Folder tree which will be applied:
├─ userRoles
│ └─ GET.json
├─ currentUserId
│ └─ GET.json
│ ├─ ?abc=123
│ │ └─ GET.json
│ └─ ?filter=test
│ └─ GET.json
└─ clients
└─ active
└─ GET.json
Expand All @@ -109,6 +118,7 @@ Filtered requests:
─────────────────────── ────── ───────────────────────────
userRoles GET /api/service/userRoles
currentUserId GET /api/service/currentUserId
currentUserId GET /api/service/currentUserId
active GET /api/service/clients/active
send POST /api/service/send

Expand All @@ -120,7 +130,10 @@ Folder tree which will be applied:
├─ userRoles
│ └─ GET.json
├─ currentUserId
│ └─ GET.json
│ ├─ ?abc=123
│ │ └─ GET.json
│ └─ ?filter=test
│ └─ GET.json
├─ clients
│ └─ active
│ └─ GET.json
Expand All @@ -129,5 +142,4 @@ Folder tree which will be applied:

`);
});

});
115 changes: 113 additions & 2 deletions tests/mocks/sample.har
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@
"pageref": "page_1",
"request": {
"method": "GET",
"url": "https://sample.com/api/service/currentUserId",
"url": "https://sample.com/api/service/currentUserId?abc=123",
"httpVersion": "HTTP/1.1",
"headers": [
{
Expand Down Expand Up @@ -244,6 +244,117 @@
"_blocked_proxy": 0.8019999999999998
}
},
{
"_priority": "High",
"_resourceType": "xhr",
"cache": {},
"connection": "392963",
"pageref": "page_1",
"request": {
"method": "GET",
"url": "https://sample.com/api/service/currentUserId?filter=test",
"httpVersion": "HTTP/1.1",
"headers": [
{
"name": "Connection",
"value": "keep-alive"
},
{
"name": "Cache-Control",
"value": "no-cache"
},
{
"name": "User-Agent",
"value": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63 Safari/537.36"
},
{
"name": "Accept",
"value": "application/json, text/plain, */*"
},
{
"name": "Accept-Encoding",
"value": "gzip, deflate, br"
},
{
"name": "Accept-Language",
"value": "sk-SK,sk;q=0.9,cs;q=0.8,en-US;q=0.7,en;q=0.6"
}
],
"queryString": [],
"cookies": [],
"headersSize": 1724,
"bodySize": 0
},
"response": {
"status": 200,
"statusText": "OK",
"httpVersion": "HTTP/1.1",
"headers": [
{
"name": "Date",
"value": "Fri, 17 Sep 2021 06:33:48 GMT"
},
{
"name": "Server",
"value": "Apache"
},
{
"name": "Cache-Control",
"value": "no-cache, no-store, max-age=0, must-revalidate"
},
{
"name": "Vary",
"value": "Accept-Encoding"
},
{
"name": "Content-Encoding",
"value": "gzip"
},
{
"name": "Keep-Alive",
"value": "timeout=20, max=71"
},
{
"name": "Connection",
"value": "Keep-Alive"
},
{
"name": "Transfer-Encoding",
"value": "chunked"
},
{
"name": "Content-Type",
"value": "application/json"
}
],
"cookies": [],
"content": {
"size": 19,
"mimeType": "application/json",
"compression": -42,
"text": "{\"userId\":\"896261\"}"
},
"redirectURL": "",
"headersSize": 400,
"bodySize": 61,
"_transferSize": 461,
"_error": null
},
"serverIPAddress": "10.212.184.32",
"startedDateTime": "2021-09-17T06:33:47.923Z",
"time": 16.336000058799982,
"timings": {
"blocked": 3.9909999612271787,
"dns": -1,
"ssl": -1,
"connect": -1,
"send": 0.29400000000000004,
"wait": 10.124999983973801,
"receive": 1.9260001135990024,
"_blocked_queueing": 1.2179999612271786,
"_blocked_proxy": 0.8019999999999998
}
},
{
"_priority": "High",
"_resourceType": "xhr",
Expand Down Expand Up @@ -454,4 +565,4 @@
}
]
}
}
}