-
Notifications
You must be signed in to change notification settings - Fork 6
feat: feed submission issue labelling; refactoring utils and adding unit tests #1544
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
Open
ianktc
wants to merge
7
commits into
main
Choose a base branch
from
feat/feed-submission-issue-labelling
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
0aaf14d
separate url check to utils folder and add unit tests for it
ianktc 5367406
refactor and add some missings tests
ianktc 57ed0a0
refactor and add some missings tests
ianktc ed92d67
Merge branch 'feat/feed-submission-issue-labelling' of github.com:Mob…
ianktc 37e5733
Rename mock file to dash case format
ianktc 59ad2ac
fix import paths
ianktc 8f3aa3c
Merge branch 'main' into feat/feed-submission-issue-labelling
ianktc File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -2,57 +2,96 @@ | |
| buildFeedRow, | ||
| buildFeedRows, | ||
| SheetCol, | ||
| writeToSheet, | ||
| } from "../impl/feed-form-impl"; | ||
| import {type FeedSubmissionFormRequestBody} from "../impl/types"; | ||
| import * as logger from "firebase-functions/logger"; | ||
| import {sampleRequestBodyGTFS, sampleRequestBodyGTFSRT} from "../impl/__mocks__/feed-submission-form-request-body.mock"; | ||
| import {HttpsError} from "firebase-functions/v2/https"; | ||
|
|
||
| const sampleRequestBodyGTFS: FeedSubmissionFormRequestBody = { | ||
| name: "Sample Feed", | ||
| isOfficialProducer: "yes", | ||
| isOfficialFeed: "yes", | ||
| dataType: "gtfs", | ||
| transitProviderName: "Sample Transit Provider", | ||
| feedLink: "https://example.com/feed", | ||
| isUpdatingFeed: "yes", | ||
| oldFeedLink: "https://example.com/old-feed", | ||
| licensePath: "/path/to/license", | ||
| country: "USA", | ||
| region: "California", | ||
| municipality: "San Francisco", | ||
| tripUpdates: "", | ||
| vehiclePositions: "", | ||
| serviceAlerts: "", | ||
| gtfsRelatedScheduleLink: "https://example.com/gtfs-schedule", | ||
| authType: "None - 0", | ||
| authSignupLink: "https://example.com/signup", | ||
| authParameterName: "auth_token", | ||
| dataProducerEmail: "[email protected]", | ||
| isInterestedInQualityAudit: "yes", | ||
| userInterviewEmail: "[email protected]", | ||
| whatToolsUsedText: "Google Sheets, Node.js", | ||
| hasLogoPermission: "yes", | ||
| unofficialDesc: "For research purposes", | ||
| updateFreq: "every month", | ||
| emptyLicenseUsage: "unsure", | ||
| }; | ||
| jest.mock("google-spreadsheet", () => ({ | ||
| GoogleSpreadsheet: jest.fn().mockImplementation(() => ({ | ||
| loadInfo: jest.fn(), | ||
| sheetsByIndex: [ | ||
| { | ||
| addRows: jest.fn(), | ||
| }, | ||
| ], | ||
| })), | ||
| })); | ||
| jest.mock("google-auth-library", () => ({ | ||
| GoogleAuth: jest.fn(), | ||
| })); | ||
|
|
||
| const mockCreateGithubIssue = jest.fn().mockResolvedValue("https://github.com/issue/1"); | ||
| const mockSendSlackWebhook = jest.fn().mockResolvedValue(undefined); | ||
|
|
||
| jest.mock("../impl/utils/github-issue", () => ({ | ||
| createGithubIssue: (...args: any[]) => mockCreateGithubIssue(...args), | ||
| })); | ||
| jest.mock("../impl/utils/slack", () => ({ | ||
| sendSlackWebhook: (...args: any[]) => mockSendSlackWebhook(...args), | ||
| })); | ||
|
|
||
| jest.spyOn(logger, "error").mockImplementation(() => {}); | ||
|
|
||
| const sampleRequestBodyGTFSRT: FeedSubmissionFormRequestBody = { | ||
| ...sampleRequestBodyGTFS, | ||
| dataType: "gtfs_rt", | ||
| feedLink: "", | ||
| tripUpdates: "https://example.com/gtfs-realtime-trip-update", | ||
| vehiclePositions: "https://example.com/gtfs-realtime-vehicle-position", | ||
| serviceAlerts: "https://example.com/gtfs-realtime-service-alerts", | ||
| oldTripUpdates: "https://example.com/old-feed-tu", | ||
| oldServiceAlerts: "https://example.com/old-feed-sa", | ||
| oldVehiclePositions: "https://example.com/old-feed-vp", | ||
| }; | ||
| const defaultEnv = process.env; | ||
|
|
||
| describe("Feed Form Implementation", () => { | ||
|
|
||
| beforeAll(() => { | ||
| const mockDate = new Date("2023-08-01T00:00:00Z"); | ||
| jest.spyOn(global, "Date").mockImplementation(() => mockDate); | ||
| }); | ||
|
|
||
| beforeEach(() => { | ||
| jest.clearAllMocks(); | ||
| process.env = { ...defaultEnv }; | ||
|
Check failure on line 48 in functions/packages/feed-form/src/__tests__/feed-form.spec.ts
|
||
| process.env.FEED_SUBMIT_GOOGLE_SHEET_ID = "sheet123"; | ||
| process.env.GCLOUD_PROJECT = "mobility-feeds-prod"; | ||
| process.env.GITHUB_TOKEN = "token"; | ||
| process.env.SLACK_WEBHOOK_URL = "https://slack"; | ||
| }); | ||
|
|
||
| afterAll(() => { | ||
| process.env = defaultEnv; | ||
| }); | ||
|
|
||
| it("should throw HttpsError if sheet ID is not defined", async () => { | ||
| process.env.FEED_SUBMIT_GOOGLE_SHEET_ID = ""; | ||
| const mockRequest = { | ||
| auth: { uid: "user1" }, | ||
|
Check failure on line 62 in functions/packages/feed-form/src/__tests__/feed-form.spec.ts
|
||
| data: sampleRequestBodyGTFS, | ||
| }; | ||
| await expect(writeToSheet(mockRequest as any)).rejects.toThrow(HttpsError); | ||
| expect(logger.error).toHaveBeenCalledWith( | ||
| "Error writing to sheet:", | ||
| expect.any(HttpsError) | ||
| ); | ||
| }); | ||
|
|
||
| it("writeToSheet writes to sheet, creates github issue, sends slack, returns success", async () => { | ||
| const mockRequest = { | ||
| auth: { uid: "user1" }, | ||
| data: sampleRequestBodyGTFS, | ||
| }; | ||
| const result = await writeToSheet(mockRequest as any); | ||
| const { GoogleSpreadsheet } = require("google-spreadsheet"); | ||
| expect(GoogleSpreadsheet).toHaveBeenCalledWith("sheet123", expect.anything()); | ||
| const doc = GoogleSpreadsheet.mock.results[0].value; | ||
| expect(doc.loadInfo).toHaveBeenCalled(); | ||
| expect(doc.sheetsByIndex[0].addRows).toHaveBeenCalledWith( | ||
| expect.any(Array), | ||
| { insert: true } | ||
| ); | ||
| expect(mockCreateGithubIssue).toHaveBeenCalled(); | ||
| expect(mockSendSlackWebhook).toHaveBeenCalledWith( | ||
| "sheet123", | ||
| "https://github.com/issue/1", | ||
| true | ||
| ); | ||
| expect(result).toEqual({ message: "Data written to the new sheet successfully!" }); | ||
| }); | ||
|
|
||
| it("should build the rows if gtfs schedule", () => { | ||
| buildFeedRows(sampleRequestBodyGTFS, "user123"); | ||
| const expectedRows = [ | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
42 changes: 42 additions & 0 deletions
42
functions/packages/feed-form/src/__tests__/utils/slack.spec.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,42 @@ | ||
| import { sendSlackWebhook } from "../../impl/utils/slack"; | ||
| import axios from "axios"; | ||
| import * as logger from "firebase-functions/logger"; | ||
|
|
||
| jest.mock("axios"); | ||
| jest.mock("firebase-functions/logger"); | ||
|
|
||
| describe("sendSlackWebhook", () => { | ||
| const spreadsheetId = "sheet123"; | ||
| const githubIssueUrl = "https://github.com/issue/1"; | ||
| const oldEnv = process.env; | ||
|
|
||
| beforeEach(() => { | ||
| jest.clearAllMocks(); | ||
| process.env = { ...oldEnv, SLACK_WEBHOOK_URL: "https://hooks.slack.com/services/abc" }; | ||
| }); | ||
|
|
||
| afterAll(() => { | ||
| process.env = oldEnv; | ||
| }); | ||
|
|
||
| it("sends a Slack message with correct payload", async () => { | ||
| (axios.post as jest.Mock).mockResolvedValueOnce({}); | ||
| await sendSlackWebhook(spreadsheetId, githubIssueUrl, true); | ||
| expect(axios.post).toHaveBeenCalledWith( | ||
| process.env.SLACK_WEBHOOK_URL, | ||
| expect.objectContaining({ blocks: expect.any(Array) }) | ||
| ); | ||
| }); | ||
|
|
||
| it("logs error if webhook URL is not set", async () => { | ||
| process.env.SLACK_WEBHOOK_URL = ""; | ||
| await sendSlackWebhook(spreadsheetId, githubIssueUrl, false); | ||
| expect(logger.error).toHaveBeenCalledWith("Slack webhook URL is not defined"); | ||
| }); | ||
|
|
||
| it("logs error if axios fails", async () => { | ||
| (axios.post as jest.Mock).mockRejectedValueOnce(new Error("fail")); | ||
| await sendSlackWebhook(spreadsheetId, githubIssueUrl, false); | ||
| expect(logger.error).toHaveBeenCalled(); | ||
| }); | ||
| }); |
60 changes: 60 additions & 0 deletions
60
functions/packages/feed-form/src/__tests__/utils/url-parse.spec.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,60 @@ | ||
| import { isValidZipUrl, isValidZipDownload } from "../../impl/utils/url-parse"; | ||
| import axios from "axios"; | ||
|
|
||
| jest.mock("axios"); | ||
| const mockedAxios = axios as jest.Mocked<typeof axios>; | ||
|
|
||
| describe("isValidZipUrl", () => { | ||
| it("returns true for valid .zip URL", () => { | ||
| expect(isValidZipUrl("https://file-examples.com/wp-content/storage/2017/02/zip_2MB.zip")).toBe(true); | ||
| expect(isValidZipUrl("https://file-examples.com/wp-content/storage/2017/02/zip_5MB.zip")).toBe(true); | ||
| }); | ||
|
|
||
| it("returns false for non-.zip URL", () => { | ||
| expect(isValidZipUrl("https://file-examples.com/wp-content/storage/2017/02/file_example_CSV_5000.csv")).toBe(false); | ||
| expect(isValidZipUrl("https://file-examples.com/wp-content/storage/2017/02/file_example_JSON_1kb.json")).toBe(false); | ||
| }); | ||
|
|
||
| it("returns false for invalid or empty input", () => { | ||
| expect(isValidZipUrl("")).toBe(false); | ||
| expect(isValidZipUrl(undefined)).toBe(false); | ||
| expect(isValidZipUrl(null)).toBe(false); | ||
| expect(isValidZipUrl("not a url")).toBe(false); | ||
| }); | ||
| }); | ||
|
|
||
| describe("isValidZipDownload", () => { | ||
| afterEach(() => jest.resetAllMocks()); | ||
|
|
||
| it("returns true if content-type includes zip", async () => { | ||
| mockedAxios.head.mockResolvedValueOnce({ | ||
| headers: { "content-type": "application/zip" } | ||
| } as any); | ||
| await expect(isValidZipDownload("https://file-examples.com/wp-content/storage/2017/02/zip_2MB.zip")).resolves.toBe(true); | ||
| }); | ||
|
|
||
| it("returns true if content-disposition includes zip", async () => { | ||
| mockedAxios.head.mockResolvedValueOnce({ | ||
| headers: { "content-disposition": "attachment; filename=foo.zip" } | ||
| } as any); | ||
| await expect(isValidZipDownload("https://file-examples.com/wp-content/storage/2017/02/zip_2MB.zip")).resolves.toBe(true); | ||
| }); | ||
|
|
||
| it("returns false if neither header includes zip", async () => { | ||
| mockedAxios.head.mockResolvedValueOnce({ | ||
| headers: { "content-type": "text/plain" } | ||
| } as any); | ||
| await expect(isValidZipDownload("https://file-examples.com/wp-content/storage/2017/02/zip_2MB.zip")).resolves.toBe(false); | ||
| }); | ||
|
|
||
| it("returns false for invalid/empty url", async () => { | ||
| await expect(isValidZipDownload("")).resolves.toBe(false); | ||
| await expect(isValidZipDownload(undefined)).resolves.toBe(false); | ||
| await expect(isValidZipDownload(null)).resolves.toBe(false); | ||
| }); | ||
|
|
||
| it("returns false if axios throws", async () => { | ||
| mockedAxios.head.mockRejectedValueOnce(new Error("Network error")); | ||
| await expect(isValidZipDownload("https://file-examples.com/wp-content/storage/2017/02/zip_2MB.zip")).resolves.toBe(false); | ||
| }); | ||
| }); | ||
43 changes: 43 additions & 0 deletions
43
functions/packages/feed-form/src/impl/__mocks__/feed-submission-form-request-body.mock.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,43 @@ | ||
| import { FeedSubmissionFormRequestBody } from "../types"; | ||
|
|
||
| export const sampleRequestBodyGTFS: FeedSubmissionFormRequestBody = { | ||
| name: "Sample Feed", | ||
| isOfficialProducer: "yes", | ||
| isOfficialFeed: "yes", | ||
| dataType: "gtfs", | ||
| transitProviderName: "Sample Transit Provider", | ||
| feedLink: "https://example.com/feed", | ||
| isUpdatingFeed: "yes", | ||
| oldFeedLink: "https://example.com/old-feed", | ||
| licensePath: "/path/to/license", | ||
| country: "USA", | ||
| region: "California", | ||
| municipality: "San Francisco", | ||
| tripUpdates: "", | ||
| vehiclePositions: "", | ||
| serviceAlerts: "", | ||
| gtfsRelatedScheduleLink: "https://example.com/gtfs-schedule", | ||
| authType: "None - 0", | ||
| authSignupLink: "https://example.com/signup", | ||
| authParameterName: "auth_token", | ||
| dataProducerEmail: "[email protected]", | ||
| isInterestedInQualityAudit: "yes", | ||
| userInterviewEmail: "[email protected]", | ||
| whatToolsUsedText: "Google Sheets, Node.js", | ||
| hasLogoPermission: "yes", | ||
| unofficialDesc: "For research purposes", | ||
| updateFreq: "every month", | ||
| emptyLicenseUsage: "unsure", | ||
| }; | ||
|
|
||
| export const sampleRequestBodyGTFSRT: FeedSubmissionFormRequestBody = { | ||
| ...sampleRequestBodyGTFS, | ||
| dataType: "gtfs_rt", | ||
| feedLink: "", | ||
| tripUpdates: "https://example.com/gtfs-realtime-trip-update", | ||
| vehiclePositions: "https://example.com/gtfs-realtime-vehicle-position", | ||
| serviceAlerts: "https://example.com/gtfs-realtime-service-alerts", | ||
| oldTripUpdates: "https://example.com/old-feed-tu", | ||
| oldServiceAlerts: "https://example.com/old-feed-sa", | ||
| oldVehiclePositions: "https://example.com/old-feed-vp", | ||
| }; |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The formData object is incorrectly structured. It creates
{sampleRequestBodyGTFS: {...}}instead of spreading the properties. This should beconst formData = sampleRequestBodyGTFS as any;to correctly reference the mock data.