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

test(githubService): add tests #1045

Merged
merged 3 commits into from
Dec 6, 2023
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
19 changes: 19 additions & 0 deletions src/fixtures/sessionData.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import GithubSessionData from "@root/classes/GithubSessionData"
import UserSessionData from "@root/classes/UserSessionData"
import UserWithSiteSessionData from "@root/classes/UserWithSiteSessionData"
import { FeatureFlags } from "@root/types/featureFlags"
import { RawGitTreeEntry } from "@root/types/github"

import {
MOCK_USER_EMAIL_ONE,
Expand All @@ -25,6 +26,24 @@ export const mockCurrentCommitSha = "mockCurrentCommitSha"
export const mockSiteName = "mockSiteName"
export const mockGrowthBook = new GrowthBook<FeatureFlags>()

export const gitTree: RawGitTreeEntry[] = [
{
path: "directory/file1.txt",
type: "tree",
sha: "fake-sha-1",
mode: "100644",
url: "fake-url-1",
},
{
path: "directory/file2.txt",
type: "file",
sha: "fake-sha-2",
mode: "100644",
url: "fake-url-2",
size: 100,
},
]

export const mockGithubState = {
treeSha: mockTreeSha,
currentCommitSha: mockCurrentCommitSha,
Expand Down
34 changes: 11 additions & 23 deletions src/services/db/GitHubService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { isAxiosError, validateStatus } from "@utils/axios-utils"

import GithubSessionData from "@root/classes/GithubSessionData"
import UserWithSiteSessionData from "@root/classes/UserWithSiteSessionData"
import { STAGING_BRANCH, STAGING_LITE_BRANCH } from "@root/constants"
import { STAGING_BRANCH } from "@root/constants"
import logger from "@root/logger/logger"
import { GitCommitResult } from "@root/types/gitfilesystem"
import { RawGitTreeEntry } from "@root/types/github"
Expand Down Expand Up @@ -235,7 +235,7 @@ export default class GitHubService {

async readMedia(
sessionData: UserWithSiteSessionData,
{ fileSha }: { fileSha: any; branchName?: string }
{ fileSha }: { fileSha: string }
) {
/**
* Files that are bigger than 1 MB needs to be retrieved
Expand Down Expand Up @@ -268,17 +268,14 @@ export default class GitHubService {

async readDirectory(
sessionData: UserWithSiteSessionData,
{
directoryName,
branchName = STAGING_BRANCH,
}: { directoryName: any; branchName?: string }
{ directoryName }: { directoryName: string }
) {
const { accessToken } = sessionData
const { siteName } = sessionData
const endpoint = this.getFolderPath({ siteName, directoryName })

const params = {
ref: branchName,
ref: STAGING_BRANCH,
}

const resp = await this.axiosInstance.get(endpoint, {
Expand All @@ -300,13 +297,11 @@ export default class GitHubService {
sha,
fileName,
directoryName,
branchName,
}: {
fileContent: string
sha: string
fileName: string
directoryName: string | undefined
branchName: string
}
): Promise<GitCommitResult> {
const { accessToken, siteName, isomerUserId: userId } = sessionData
Expand Down Expand Up @@ -335,7 +330,7 @@ export default class GitHubService {
const params = {
message,
content: encodedNewContent,
branch: branchName,
branch: STAGING_BRANCH,
sha: fileSha,
}

Expand Down Expand Up @@ -519,16 +514,15 @@ export default class GitHubService {
async getTree(
sessionData: UserWithSiteSessionData,
githubSessionData: GithubSessionData,
{ isRecursive }: any,
isStaging = true
{ isRecursive }: any
): Promise<RawGitTreeEntry[]> {
const { accessToken } = sessionData
const { siteName } = sessionData
const { treeSha } = githubSessionData.getGithubState()
const url = `${siteName}/git/trees/${treeSha}`

const params = {
ref: isStaging ? STAGING_BRANCH : STAGING_LITE_BRANCH,
ref: STAGING_BRANCH,
recursive: false,
}

Expand Down Expand Up @@ -690,17 +684,11 @@ export default class GitHubService {
githubSessionData: GithubSessionData,
oldPath: string,
newPath: string,
message?: string,
isStaging = true
message?: string
): Promise<GitCommitResult> {
const gitTree = await this.getTree(
sessionData,
githubSessionData,
{
isRecursive: true,
},
!!isStaging
)
const gitTree = await this.getTree(sessionData, githubSessionData, {
isRecursive: true,
})
const newGitTree: any[] = []
const isMovingDirectory =
gitTree.find((item: any) => item.path === oldPath)?.type === "tree" ||
Expand Down
7 changes: 3 additions & 4 deletions src/services/db/RepoService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -363,9 +363,9 @@ export default class RepoService extends GitHubService {

dirContent = result.value
} else {
dirContent = (await super.readDirectory(sessionData, {
dirContent = await super.readDirectory(sessionData, {
directoryName,
})) as GitDirectoryItem[]
})
}

const { directories, files, total } = getPaginatedDirectoryContents(
Expand Down Expand Up @@ -418,7 +418,6 @@ export default class RepoService extends GitHubService {
sha,
fileName,
directoryName,
branchName: STAGING_BRANCH,
})
}

Expand Down Expand Up @@ -612,7 +611,7 @@ export default class RepoService extends GitHubService {
{
commitSha,
branchName = BRANCH_REF,
}: { commitSha: string; branchName?: string }
}: { commitSha: string; branchName: string }
): Promise<void> {
const { siteName } = sessionData
if (
Expand Down
157 changes: 153 additions & 4 deletions src/services/db/__tests__/GitHubService.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,12 @@ import {
mockCurrentCommitSha,
mockGithubSessionData,
mockIsomerUserId,
gitTree,
} from "@fixtures/sessionData"
import { STAGING_BRANCH, STAGING_LITE_BRANCH } from "@root/constants"
import { indexHtmlContent } from "@root/fixtures/markdown-fixtures"
import { collectionYmlContent } from "@root/fixtures/yaml-fixtures"
import { RawGitTreeEntry } from "@root/types/github"
import GitHubService from "@services/db/GitHubService"

// using es6 gives some error
Expand Down Expand Up @@ -531,7 +534,6 @@ describe("Github Service", () => {
directoryName,
fileContent: content,
sha,
branchName: BRANCH_REF,
})
).resolves.toMatchObject({
newSha: sha,
Expand Down Expand Up @@ -560,7 +562,6 @@ describe("Github Service", () => {
directoryName,
fileContent: content,
sha,
branchName: BRANCH_REF,
})
).rejects.toThrowError(NotFoundError)
expect(mockAxiosInstance.put).toHaveBeenCalledWith(
Expand Down Expand Up @@ -596,7 +597,6 @@ describe("Github Service", () => {
directoryName,
fileContent: content,
sha: "",
branchName: BRANCH_REF,
})
).resolves.toMatchObject({
newSha: sha,
Expand Down Expand Up @@ -628,7 +628,6 @@ describe("Github Service", () => {
directoryName,
fileContent: content,
sha: "",
branchName: BRANCH_REF,
})
).rejects.toThrowError(NotFoundError)
expect(mockAxiosInstance.get).toHaveBeenCalledWith(endpoint, {
Expand Down Expand Up @@ -985,4 +984,154 @@ describe("Github Service", () => {
expect(resp.isOk()).toEqual(true)
})
})

describe("deleteDirectory", () => {
const message = JSON.stringify({
message: `Delete directory: ${directoryName}`,
directoryName,
userId,
})
const params = {
message,
branch: BRANCH_REF,
sha: treeSha,
force: true,
}

const endpoint = `${siteName}/git/refs/heads/${STAGING_BRANCH}`
const stagingLiteEndpoint = `${siteName}/git/refs/heads/${STAGING_LITE_BRANCH}`

it("should delete a directory correctly", async () => {
// Arrange
const getTreeSpy = jest.spyOn(service, "getTree")
getTreeSpy.mockResolvedValueOnce(gitTree)
mockAxiosInstance.get.mockImplementation(() =>
Promise.resolve({ data: gitTree })
)
const updateTreeSpy = jest.spyOn(service, "updateTree")
updateTreeSpy.mockResolvedValueOnce(treeSha)
// Act
await service.deleteDirectory(sessionData, {
directoryName,
message,
githubSessionData: mockGithubSessionData,
})

// Assert
expect(mockAxiosInstance.patch).toHaveBeenCalledWith(
endpoint,
{
force: true,
sha: treeSha,
},
{
headers: { Authorization: `token ${accessToken}` },
}
)
})

it("should throw the correct error if directory cannot be found", async () => {
// Arrange
const getTreeSpy = jest.spyOn(service, "getTree")
getTreeSpy.mockResolvedValueOnce(gitTree)
const updateTreeSpy = jest.spyOn(service, "updateTree")
updateTreeSpy.mockResolvedValueOnce(treeSha)
mockAxiosInstance.patch.mockImplementation(() => {
const err = {
response: {
status: 404,
},
isAxiosError: true,
}
throw err
})

// Act
await expect(
service.deleteDirectory(sessionData, {
directoryName,
message,
githubSessionData: mockGithubSessionData,
})
).rejects.toStrictEqual({ isAxiosError: true, response: { status: 404 } })

// Assert
expect(mockAxiosInstance.patch).toHaveBeenCalledWith(
endpoint,
{
force: true,
sha: "mockTreeSha",
},
{
headers: authHeader.headers,
}
)
})
})

describe("renameSinglePath", () => {
it("should rename a file correctly", async () => {
// Arrange

const oldPath = "old/path.txt"
const newPath = "new/path.txt"
const message = "Renaming file"

const newGitTree: RawGitTreeEntry[] = [
{
path: oldPath,
type: "file",
sha: "new-sha2",
mode: "100644",
url: "",
},
]

const resolvedTree = [
{
path: newPath,
type: "file",
sha: "new-sha2",
mode: "100644",
url: "",
},
{
path: oldPath,
type: "file",
sha: null,
mode: "100644",
url: "",
},
]
const newCommitSha = "new-commit-sha"
jest.spyOn(service, "getTree").mockResolvedValueOnce(newGitTree)
jest.spyOn(service, "updateTree").mockResolvedValueOnce(newCommitSha)
jest.spyOn(service, "updateRepoState").mockResolvedValueOnce()

// Act
const result = await service.renameSinglePath(
sessionData,
mockGithubSessionData,
oldPath,
newPath,
message
)

// Assert
expect(service.getTree).toHaveBeenCalledWith(
sessionData,
mockGithubSessionData,
{ isRecursive: true }
)
expect(service.updateTree).toHaveBeenCalledWith(
sessionData,
mockGithubSessionData,
{ gitTree: resolvedTree, message }
)
expect(service.updateRepoState).toHaveBeenCalledWith(sessionData, {
commitSha: newCommitSha,
})
expect(result).toEqual({ newSha: newCommitSha })
})
})
})
Loading