Skip to content
Merged
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
9 changes: 9 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@
"@types/express": "^4.17.7",
"@types/jest": "26.0.14",
"@types/lodash": "^4.14.168",
"@types/multer": "^1.4.5",
"@types/node": "^14.0.27",
"@types/passport-jwt": "^3.0.3",
"@types/passport-local": "^1.0.33",
Expand Down
31 changes: 31 additions & 0 deletions src/shared/api-file.decorator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { ApiPropertyOptions, ApiProperty } from "@nestjs/swagger";

export const ApiFile = (options?: ApiPropertyOptions): PropertyDecorator => (
target: Object,
propertyKey: string | symbol,
) => {
if (options?.isArray) {
ApiProperty({
type: 'array',
items: {
type: 'file',
properties: {
[propertyKey]: {
type: 'string',
format: 'binary',
},
},
},
})(target, propertyKey);
} else {
ApiProperty({
type: 'file',
properties: {
[propertyKey]: {
type: 'string',
format: 'binary',
},
},
})(target, propertyKey);
}
};
38 changes: 38 additions & 0 deletions src/shared/fite-to-body.interceptor.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from "@nestjs/common";
import { Observable } from "rxjs";

@Injectable()
export class FilesToBodyInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
const ctx = context.switchToHttp();
const req = ctx.getRequest();
if (req.body && Array.isArray(req.files) && req.files.length) {
req.files.forEach((file: Express.Multer.File) => {
const { fieldname } = file;
if (!req.body[fieldname]) {
req.body[fieldname] = [file];
} else {
req.body[fieldname].push(file);
}
});
}

return next.handle();
}
}

@Injectable()
export class FileToBodyInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
const ctx = context.switchToHttp();
const req = ctx.getRequest();
if (req.body && req.file?.fieldname) {
const { fieldname } = req.file;
if (!req.body[fieldname]) {
req.body[fieldname] = req.file;
}
}

return next.handle();
}
}
11 changes: 11 additions & 0 deletions src/test-runs/dto/create-test-request-base64.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { ApiProperty } from '@nestjs/swagger';
import { Transform } from 'class-transformer';
import { IsBase64 } from 'class-validator';
import { CreateTestRequestDto } from './create-test-request.dto';

export class CreateTestRequestBase64Dto extends CreateTestRequestDto {
@ApiProperty()
@Transform((value) => value.replace(/(\r\n|\n|\r)/gm, ''))
@IsBase64()
imageBase64: string;
}
7 changes: 7 additions & 0 deletions src/test-runs/dto/create-test-request-multipart.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { ApiFile } from '../../shared/api-file.decorator';
import { CreateTestRequestDto } from './create-test-request.dto';

export class CreateTestRequestMultipartDto extends CreateTestRequestDto {
@ApiFile()
image: Express.Multer.File;
}
18 changes: 12 additions & 6 deletions src/test-runs/dto/create-test-request.dto.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,10 @@
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { Transform } from 'class-transformer';
import { IsOptional, IsUUID, IsNumber, IsBoolean, IsBase64 } from 'class-validator';
import { IsOptional, IsUUID, IsNumber, IsBoolean } from 'class-validator';
import { BaselineDataDto } from '../../shared/dto/baseline-data.dto';
import { IgnoreAreaDto } from './ignore-area.dto';

export class CreateTestRequestDto extends BaselineDataDto {
@ApiProperty()
@Transform((value) => value.replace(/(\r\n|\n|\r)/gm, ''))
@IsBase64()
imageBase64: string;

@ApiProperty()
@IsUUID()
buildId: string;
Expand All @@ -21,11 +16,22 @@ export class CreateTestRequestDto extends BaselineDataDto {
@ApiPropertyOptional()
@IsOptional()
@IsNumber()
@Transform((it) => parseFloat(it))
diffTollerancePercent?: number;

@ApiPropertyOptional()
@IsBoolean()
@IsOptional()
@Transform((it) => {
switch (it) {
case 'true':
return true;
case 'false':
return false;
default:
return it;
}
})
merge?: boolean;

@ApiPropertyOptional({ type: [IgnoreAreaDto] })
Expand Down
42 changes: 37 additions & 5 deletions src/test-runs/test-runs.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,18 +10,33 @@ import {
Query,
Post,
ParseBoolPipe,
ParseIntPipe,
UseInterceptors,
UploadedFile,
UsePipes,
ValidationPipe,
} from '@nestjs/common';
import { ApiTags, ApiParam, ApiBearerAuth, ApiQuery, ApiSecurity, ApiOkResponse } from '@nestjs/swagger';
import {
ApiTags,
ApiParam,
ApiBearerAuth,
ApiQuery,
ApiSecurity,
ApiOkResponse,
ApiConsumes,
ApiBody,
} from '@nestjs/swagger';
import { JwtAuthGuard } from '../auth/guards/auth.guard';
import { TestRun, TestStatus } from '@prisma/client';
import { TestRunsService } from './test-runs.service';
import { IgnoreAreaDto } from './dto/ignore-area.dto';
import { CommentDto } from '../shared/dto/comment.dto';
import { TestRunResultDto } from './dto/testRunResult.dto';
import { ApiGuard } from '../auth/guards/api.guard';
import { CreateTestRequestDto } from './dto/create-test-request.dto';
import { TestRunDto } from './dto/testRun.dto';
import { FileInterceptor } from '@nestjs/platform-express';
import { CreateTestRequestBase64Dto } from './dto/create-test-request-base64.dto';
import { CreateTestRequestMultipartDto } from './dto/create-test-request-multipart.dto';
import { FileToBodyInterceptor } from '../shared/fite-to-body.interceptor';

@ApiTags('test-runs')
@Controller('test-runs')
Expand Down Expand Up @@ -87,7 +102,24 @@ export class TestRunsController {
@ApiSecurity('api_key')
@ApiOkResponse({ type: TestRunResultDto })
@UseGuards(ApiGuard)
postTestRun(@Body() createTestRequestDto: CreateTestRequestDto): Promise<TestRunResultDto> {
return this.testRunsService.postTestRun(createTestRequestDto);
postTestRun(@Body() createTestRequestDto: CreateTestRequestBase64Dto): Promise<TestRunResultDto> {
const imageBuffer = Buffer.from(createTestRequestDto.imageBase64, 'base64');
return this.testRunsService.postTestRun({
createTestRequestDto,
imageBuffer,
});
}

@Post('/multipart')
@ApiSecurity('api_key')
@ApiBody({ type: CreateTestRequestMultipartDto })
@ApiOkResponse({ type: TestRunResultDto })
@ApiConsumes('multipart/form-data')
@UseGuards(ApiGuard)
@UseInterceptors(FileInterceptor('image'), FileToBodyInterceptor)
@UsePipes(new ValidationPipe({ transform: true }))
postTestRunMultipart(@Body() createTestRequestDto: CreateTestRequestMultipartDto): Promise<TestRunResultDto> {
const imageBuffer = createTestRequestDto.image.buffer;
return this.testRunsService.postTestRun({ createTestRequestDto, imageBuffer });
}
}
12 changes: 6 additions & 6 deletions src/test-runs/test-runs.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import { BuildsService } from '../builds/builds.service';
import { TEST_PROJECT } from '../_data_';
import { getTestVariationUniqueData } from '../utils';
import { BaselineDataDto } from '../shared/dto/baseline-data.dto';
import { CreateTestRequestBase64Dto } from './dto/create-test-request-base64.dto';

jest.mock('pixelmatch');
jest.mock('./dto/testRunResult.dto');
Expand Down Expand Up @@ -103,6 +104,7 @@ const initService = async ({
};
describe('TestRunsService', () => {
let service: TestRunsService;
const imageBuffer = Buffer.from('Image');
const ignoreAreas = [{ x: 1, y: 2, width: 10, height: 20 }];
const tempIgnoreAreas = [{ x: 3, y: 4, width: 30, height: 40 }];
const baseTestRun: TestRun = {
Expand Down Expand Up @@ -184,7 +186,6 @@ describe('TestRunsService', () => {
buildId: 'buildId',
projectId: 'projectId',
name: 'Test name',
imageBase64: 'Image',
os: 'OS',
browser: 'browser',
viewport: 'viewport',
Expand Down Expand Up @@ -259,9 +260,9 @@ describe('TestRunsService', () => {
const tryAutoApproveByNewBaselines = jest.fn();
service['tryAutoApproveByNewBaselines'] = tryAutoApproveByNewBaselines.mockResolvedValueOnce(testRunWithResult);

const result = await service.create(testVariation, createTestRequestDto);
const result = await service.create({ testVariation, createTestRequestDto, imageBuffer });

expect(saveImageMock).toHaveBeenCalledWith('screenshot', Buffer.from(createTestRequestDto.imageBase64, 'base64'));
expect(saveImageMock).toHaveBeenCalledWith('screenshot', imageBuffer);
expect(testRunCreateMock).toHaveBeenCalledWith({
data: {
imageName,
Expand Down Expand Up @@ -722,7 +723,6 @@ describe('TestRunsService', () => {
buildId: 'buildId',
projectId: 'projectId',
name: 'Test name',
imageBase64: 'Image',
os: 'OS',
browser: 'browser',
viewport: 'viewport',
Expand Down Expand Up @@ -789,7 +789,7 @@ describe('TestRunsService', () => {
branchName: createTestRequestDto.branchName,
};

await service.postTestRun(createTestRequestDto);
await service.postTestRun({ createTestRequestDto, imageBuffer });

expect(testVariationFindOrCreateMock).toHaveBeenCalledWith(createTestRequestDto.projectId, baselineData);
expect(testRunFindManyMock).toHaveBeenCalledWith({
Expand All @@ -800,7 +800,7 @@ describe('TestRunsService', () => {
},
});
expect(deleteMock).toHaveBeenCalledWith(testRun.id);
expect(createMock).toHaveBeenCalledWith(testVariation, createTestRequestDto);
expect(createMock).toHaveBeenCalledWith({ testVariation, createTestRequestDto, imageBuffer });
expect(service.calculateDiff).toHaveBeenCalledWith(testRun);
expect(service['tryAutoApproveByPastBaselines']).toHaveBeenCalledWith(testVariation, testRun);
expect(service['tryAutoApproveByNewBaselines']).toHaveBeenCalledWith(testVariation, testRun);
Expand Down
21 changes: 17 additions & 4 deletions src/test-runs/test-runs.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,13 @@ export class TestRunsService {
});
}

async postTestRun(createTestRequestDto: CreateTestRequestDto): Promise<TestRunResultDto> {
async postTestRun({
createTestRequestDto,
imageBuffer,
}: {
createTestRequestDto: CreateTestRequestDto;
imageBuffer: Buffer;
}): Promise<TestRunResultDto> {
// creates variatioin if does not exist
const testVariation = await this.testVariationService.findOrCreate(createTestRequestDto.projectId, {
...getTestVariationUniqueData(createTestRequestDto),
Expand All @@ -69,7 +75,7 @@ export class TestRunsService {
}

// create test run result
const testRun = await this.create(testVariation, createTestRequestDto);
const testRun = await this.create({ testVariation, createTestRequestDto, imageBuffer });

// calculate diff
let testRunWithResult = await this.calculateDiff(testRun);
Expand Down Expand Up @@ -157,9 +163,16 @@ export class TestRunsService {
return this.saveDiffResult(testRun.id, diffResult);
}

async create(testVariation: TestVariation, createTestRequestDto: CreateTestRequestDto): Promise<TestRun> {
async create({
testVariation,
createTestRequestDto,
imageBuffer,
}: {
testVariation: TestVariation;
createTestRequestDto: CreateTestRequestDto;
imageBuffer: Buffer;
}): Promise<TestRun> {
// save image
const imageBuffer = Buffer.from(createTestRequestDto.imageBase64, 'base64');
const imageName = this.staticService.saveImage('screenshot', imageBuffer);

const testRun = await this.prismaService.testRun.create({
Expand Down
38 changes: 20 additions & 18 deletions src/test-variations/test-variations.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,6 @@ describe('TestVariationsService', () => {
buildId: 'buildId',
projectId: projectMock.id,
name: 'Test name',
imageBase64: 'Image',
os: 'OS',
browser: 'browser',
viewport: 'viewport',
Expand Down Expand Up @@ -181,7 +180,6 @@ describe('TestVariationsService', () => {
buildId: 'buildId',
projectId: projectMock.id,
name: 'Test name',
imageBase64: 'Image',
os: 'OS',
browser: 'browser',
viewport: 'viewport',
Expand Down Expand Up @@ -240,7 +238,6 @@ describe('TestVariationsService', () => {
buildId: 'buildId',
projectId: projectMock.id,
name: 'Test name',
imageBase64: 'Image',
os: 'OS',
browser: 'browser',
viewport: 'viewport',
Expand Down Expand Up @@ -317,7 +314,6 @@ describe('TestVariationsService', () => {
buildId: 'buildId',
projectId: projectMock.id,
name: 'Test name',
imageBase64: 'Image',
os: 'OS',
browser: 'browser',
viewport: 'viewport',
Expand Down Expand Up @@ -529,21 +525,27 @@ describe('TestVariationsService', () => {
});

await new Promise((r) => setTimeout(r, 1));
expect(testRunCreateMock).toHaveBeenNthCalledWith(1, testVariationMainBranch, {
...testVariation,
buildId: build.id,
imageBase64: PNG.sync.write(image).toString('base64'),
diffTollerancePercent: 0,
merge: true,
ignoreAreas: JSON.parse(testVariation.ignoreAreas),
expect(testRunCreateMock).toHaveBeenNthCalledWith(1, {
testVariation: testVariationMainBranch,
createTestRequestDto: {
...testVariation,
buildId: build.id,
diffTollerancePercent: 0,
merge: true,
ignoreAreas: JSON.parse(testVariation.ignoreAreas),
},
imageBuffer: PNG.sync.write(image),
});
expect(testRunCreateMock).toHaveBeenNthCalledWith(2, testVariationMainBranch, {
...testVariationSecond,
buildId: build.id,
imageBase64: PNG.sync.write(image).toString('base64'),
diffTollerancePercent: 0,
merge: true,
ignoreAreas: JSON.parse(testVariationSecond.ignoreAreas),
expect(testRunCreateMock).toHaveBeenNthCalledWith(2, {
testVariation: testVariationMainBranch,
createTestRequestDto: {
...testVariationSecond,
buildId: build.id,
diffTollerancePercent: 0,
merge: true,
ignoreAreas: JSON.parse(testVariationSecond.ignoreAreas),
},
imageBuffer: PNG.sync.write(image),
});
expect(testRunCreateMock).toHaveBeenCalledTimes(2);
expect(buildUpdateMock).toHaveBeenCalledWith(build.id, { isRunning: false });
Expand Down
Loading