Skip to content

Commit

Permalink
test(firestore-multimodal-genai): added more tests
Browse files Browse the repository at this point in the history
  • Loading branch information
cabljac committed Jan 19, 2024
1 parent 35d8607 commit 57b7d43
Show file tree
Hide file tree
Showing 6 changed files with 152 additions and 7 deletions.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
20 changes: 20 additions & 0 deletions firestore-multimodal-genai/functions/src/__mocks__/config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
export default {
vertex: {
model: 'gemini-pro',
},
googleAi: {
model: 'gemini-pro',
apiKey: 'test-api-key',
},
location: 'us-central1',
projectId: 'text-project-id',
instanceId: 'text-instance-id',
collectionName: 'discussions',
prompt: 'test prompt',
responseField: 'output',
candidateCount: 1,
provider: 'vertex-ai',
apiKey: process.env.API_KEY,
bucketName: 'demo-gcp.appspot.com',
imageField: 'image',
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import * as fs from 'fs';
import * as path from 'path';
import {compressImageBuffer, extractBucketName} from './image_utils';
describe('compressImageBuffer', () => {
test('should compress large image', async () => {
// get image fixture

const imagePath = path.posix.join(
__dirname,
'../../__tests__/fixtures/large-image.jpg'
);

const imageBuffer = fs.readFileSync(imagePath);

const compressed = await compressImageBuffer(imageBuffer, 'jpg');

expect(compressed).toBeDefined();
expect(compressed.length).toBeLessThan(imageBuffer.length);
expect(compressed.length).toBeLessThan(900000);
});
});

describe('extractBucketName', () => {
test('extracts the bucket name from a valid URL', () => {
const url = 'gs://my-bucket/path/to/object';
expect(extractBucketName(url)).toBe('my-bucket');
});

test('throws an error for URLs not containing gs://', () => {
const url = 'http://my-bucket/path/to/object';
expect(() => extractBucketName(url)).toThrow('Invalid URL format');
});

test('throws an error for URLs with gs:// not at the start', () => {
const url = 'http://my-bucket/gs://path/to/object';
expect(() => extractBucketName(url)).toThrow('Invalid URL format');
});

test('handles URLs with only the bucket name after gs://', () => {
const url = 'gs://my-bucket';
expect(extractBucketName(url)).toBe('my-bucket');
});

test('throws an error for empty strings', () => {
const url = '';
expect(() => extractBucketName(url)).toThrow('Invalid URL format');
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -43,12 +43,16 @@ export async function getImageFromStorage(image: string) {
}

export function extractBucketName(url: string) {
if (!url.startsWith('gs://')) {
throw new Error('Invalid URL format');
}

// Split the URL by '://'
const parts = url.split('gs://');

// Check if the URL is correctly formatted
if (parts.length !== 2) {
return 'Invalid URL format';
throw new Error('Invalid URL format');
}

// Further split the second part by '/' to isolate the bucket name
Expand Down
74 changes: 74 additions & 0 deletions firestore-multimodal-genai/functions/src/logs.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import * as logFunctions from './logs'; // Adjust the path to where your functions are located
import {logger} from 'firebase-functions';
import config from './__mocks__/config';

jest.mock('firebase-functions', () => ({
logger: {
info: jest.fn(),
error: jest.fn(),
log: jest.fn(),
},
}));

describe('Log Functions', () => {
beforeEach(() => {
jest.clearAllMocks();
});

test('init logs correct information', () => {
logFunctions.init(config);
expect(logger.info).toHaveBeenCalledWith(
expect.stringContaining('Initialized with config')
);

const obfuscatedConfig = {
...config,
apiKey: '[REDACTED]',
};
expect(logger.info).toHaveBeenCalledWith(
expect.stringContaining(JSON.stringify(obfuscatedConfig))
);
});

test('missingField logs correct information', () => {
logFunctions.missingField('field', 'path');
expect(logger.info).toHaveBeenCalledWith(
expect.stringContaining(
"Missing ordering field 'field' on document 'path'"
)
);
});

test('receivedAPIResponse logs correct information', () => {
logFunctions.receivedAPIResponse('path', 100);
expect(logger.info).toHaveBeenCalledWith(
expect.stringContaining(
"[firestore-multimodal-genai] Received API response for document 'path' in 100ms"
)
);
});

test('errorCallingGLMAPI logs correct error message', () => {
const error = new Error('Test Error');
logFunctions.errorCallingGLMAPI('path', error);
expect(logger.error).toHaveBeenCalledWith(
expect.stringContaining("Error calling Gemini API for document 'path'")
);
});

test('usingADC logs correct message', () => {
logFunctions.usingADC();
expect(logger.log).toHaveBeenCalledWith(
expect.stringContaining(
'no API key provided, using application default credentials.'
)
);
});

test('usingAPIKey logs correct message', () => {
logFunctions.usingAPIKey();
expect(logger.log).toHaveBeenCalledWith(
expect.stringContaining('using API key provided.')
);
});
});
11 changes: 5 additions & 6 deletions firestore-multimodal-genai/functions/src/logs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
import {logger} from 'firebase-functions';
import {Config} from './config';

const extensionName = 'firestore-palm-gen-text';
const EXTENSION_NAME = 'firestore-multimodal-genai';

export const init = (config: Config) => {
const obfuscatedConfig = {
Expand All @@ -34,27 +34,26 @@ export const init = (config: Config) => {

export const missingField = (field: string, path: string) => {
logger.info(
`[${extensionName}] Missing ordering field '${field}' on document '${path}', setting to current timestamp.`
`[${EXTENSION_NAME}] Missing ordering field '${field}' on document '${path}', setting to current timestamp.`
);
};

export const receivedAPIResponse = (path: string, duration: number) => {
logger.info(
`[${extensionName}] Received API response for document '${path}' in ${duration}ms.`,
{duration}
`[${EXTENSION_NAME}] Received API response for document '${path}' in ${duration}ms.`
);
};

export const errorCallingGLMAPI = (path: string, error: any) => {
logger.error(
`[${extensionName}] Error calling Gemini API for document '${path}': ${
`[${EXTENSION_NAME}] Error calling Gemini API for document '${path}': ${
error.message || 'UNKNOWN ERROR'
}`
);
};
export const usingADC = () => {
logger.log(
`[${extensionName}] no API key provided, using application default credentials.`
`[${EXTENSION_NAME}] no API key provided, using application default credentials.`
);
};

Expand Down

0 comments on commit 57b7d43

Please sign in to comment.