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

chore(fe): update playwright config and add some tests #2355

Merged
merged 5 commits into from
Feb 6, 2025
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
3 changes: 2 additions & 1 deletion apps/frontend/.gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,8 @@ __generated__/

# Playwright
test-results/*
test-results.json
playwright/test-results.json
playwright/.auth

# Next.js Bundle Analyzer
analyze
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
SelectTrigger,
SelectValue
} from '@/components/shadcn/select'
import { auth } from '@/libs/auth'
import { useSession } from '@/libs/hooks/useSession'
import { fetcherWithAuth } from '@/libs/utils'
import submitIcon from '@/public/icons/submit.svg'
import { useAuthModalStore } from '@/stores/authModal'
Expand Down Expand Up @@ -81,7 +81,8 @@
const storageKey = useRef(
getStorageKey(language, problem.id, userName, contestId)
)
const { currentModal, showSignIn } = useAuthModalStore((state) => state)
const session = useSession()
const showSignIn = useAuthModalStore((state) => state.showSignIn)
const [showModal, setShowModal] = useState<boolean>(false)
//const pushed = useRef(false)
const whereToPush = useRef('')
Expand Down Expand Up @@ -118,18 +119,15 @@
loading && submissionId ? 500 : null
)

const checkSession = async () => {
const session = await auth()
useEffect(() => {
if (!session) {
toast.info('Log in to use submission & save feature')
setTimeout(() => {
toast.info('Log in to use submission & save feature')
})
} else {
setUserName(session.user.username)
}
}

useEffect(() => {
checkSession()
}, [currentModal])
}, [session])

useEffect(() => {
if (!templateString) {
Expand All @@ -143,7 +141,7 @@
return
}
setTemplateCode(filteredTemplate[0].code[0].text)
}, [language])

Check warning on line 144 in apps/frontend/app/(client)/(code-editor)/_components/EditorHeader/EditorHeader.tsx

View workflow job for this annotation

GitHub Actions / Lint

React Hook useEffect has a missing dependency: 'templateString'. Either include it or remove the dependency array

Check warning on line 144 in apps/frontend/app/(client)/(code-editor)/_components/EditorHeader/EditorHeader.tsx

View workflow job for this annotation

GitHub Actions / Lint

React Hook useEffect has a missing dependency: 'templateString'. Either include it or remove the dependency array

useEffect(() => {
storageKey.current = getStorageKey(
Expand All @@ -156,7 +154,7 @@
const storedCode = getCodeFromLocalStorage(storageKey.current)
setCode(storedCode || templateCode)
}
}, [userName, problem, contestId, language, templateCode])

Check warning on line 157 in apps/frontend/app/(client)/(code-editor)/_components/EditorHeader/EditorHeader.tsx

View workflow job for this annotation

GitHub Actions / Lint

React Hook useEffect has a missing dependency: 'setCode'. Either include it or remove the dependency array

Check warning on line 157 in apps/frontend/app/(client)/(code-editor)/_components/EditorHeader/EditorHeader.tsx

View workflow job for this annotation

GitHub Actions / Lint

React Hook useEffect has a missing dependency: 'setCode'. Either include it or remove the dependency array

const storeCodeToLocalStorage = (code: string) => {
if (storageKey.current !== undefined) {
Expand All @@ -168,6 +166,12 @@
const submit = async () => {
const code = getCode()

if (session === null) {
showSignIn()
toast.error('Log in first to submit your code')
return
}

if (code === '') {
toast.error('Please write code before submission')
return
Expand Down Expand Up @@ -225,12 +229,12 @@
}
}

const saveCode = async () => {
const session = await auth()
const saveCode = () => {
const code = getCode()

if (!session) {
if (session === null) {
toast.error('Log in first to save your code')
showSignIn()
} else if (storageKey.current !== undefined) {
localStorage.setItem(storageKey.current, code)
toast.success('Successfully saved the code')
Expand Down Expand Up @@ -300,7 +304,7 @@
window.removeEventListener('beforeunload', handleBeforeUnload)
//window.removeEventListener('popstate', handlePopState)
}
}, [])

Check warning on line 307 in apps/frontend/app/(client)/(code-editor)/_components/EditorHeader/EditorHeader.tsx

View workflow job for this annotation

GitHub Actions / Lint

React Hook useEffect has missing dependencies: 'contestId', 'handleBeforeUnload', 'language', 'problem.id', and 'userName'. Either include them or remove the dependency array

Check warning on line 307 in apps/frontend/app/(client)/(code-editor)/_components/EditorHeader/EditorHeader.tsx

View workflow job for this annotation

GitHub Actions / Lint

React Hook useEffect has missing dependencies: 'contestId', 'handleBeforeUnload', 'language', 'problem.id', and 'userName'. Either include them or remove the dependency array

useEffect(() => {
const originalPush = router.push
Expand All @@ -322,7 +326,7 @@
return () => {
router.push = originalPush
}
}, [router])

Check warning on line 329 in apps/frontend/app/(client)/(code-editor)/_components/EditorHeader/EditorHeader.tsx

View workflow job for this annotation

GitHub Actions / Lint

React Hook useEffect has a missing dependency: 'checkSaved'. Either include it or remove the dependency array

Check warning on line 329 in apps/frontend/app/(client)/(code-editor)/_components/EditorHeader/EditorHeader.tsx

View workflow job for this annotation

GitHub Actions / Lint

React Hook useEffect has a missing dependency: 'checkSaved'. Either include it or remove the dependency array

return (
<div className="flex shrink-0 items-center justify-between border-b border-b-slate-700 bg-[#222939] px-6">
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Button, type ButtonProps } from '@/components/shadcn/button'
import { useSession } from '@/libs/hooks/useSession'
import { isHttpError, safeFetcherWithAuth } from '@/libs/utils'
import { useAuthModalStore } from '@/stores/authModal'
import { useCodeStore } from '@/stores/editor'
Expand All @@ -21,6 +22,7 @@ export function RunTestButton({
saveCode,
...props
}: RunTestButtonProps) {
const session = useSession()
const setIsTesting = useTestPollingStore((state) => state.setIsTesting)
const startPolling = useTestPollingStore((state) => state.startPolling)
const showSignIn = useAuthModalStore((state) => state.showSignIn)
Expand Down Expand Up @@ -97,6 +99,12 @@ export function RunTestButton({
const code = getCode()
const testcases = getUserTestcases()

if (session === null) {
showSignIn()
toast.error('Log in first to test your code')
return
}

if (code === '') {
toast.error('Please write code before test')
return
Expand Down
5 changes: 4 additions & 1 deletion apps/frontend/app/layout.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import { AuthProvider } from '@/components/auth/AuthProvider'
import { Toaster } from '@/components/shadcn/sonner'
import { auth } from '@/libs/auth'
import { metaBaseUrl } from '@/libs/constants'
import { getBootstrapData } from '@/libs/posthog.server'
import type { Metadata, Viewport } from 'next'
Expand Down Expand Up @@ -36,14 +38,15 @@ export default async function RootLayout({
children: React.ReactNode
}) {
const bootstrapData = await getBootstrapData()
const session = await auth()

return (
<html lang="en" className={mono.variable}>
<body>
<PostHogProvider bootstrap={bootstrapData}>
{/**NOTE: remove comment if you want to track page view of users */}
{/* <PostHogPageView /> */}
{children}
<AuthProvider session={session}>{children}</AuthProvider>
<Toaster
richColors
position="top-center"
Expand Down
21 changes: 21 additions & 0 deletions apps/frontend/components/auth/AuthProvider.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
'use client'

import type { Session } from 'next-auth'
import { createContext, type ReactNode } from 'react'

export const SessionContext = createContext<Session | null | undefined>(
undefined
)

interface AuthProviderProps {
children: ReactNode
session: Session | null
}

export function AuthProvider({ children, session }: AuthProviderProps) {
return (
<SessionContext.Provider value={session}>
{children}
</SessionContext.Provider>
)
}
1 change: 1 addition & 0 deletions apps/frontend/components/auth/SignIn.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ export function SignIn() {
<form
className="flex w-full flex-col gap-4"
onSubmit={handleSubmit(onSubmit)}
aria-label="Log in"
>
<p className="text-primary mb-4 text-left font-mono text-xl font-bold">
Log in
Expand Down
12 changes: 12 additions & 0 deletions apps/frontend/libs/hooks/useSession.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { SessionContext } from '@/components/auth/AuthProvider'
import { useContext } from 'react'

export const useSession = () => {
const context = useContext(SessionContext)

if (context === undefined) {
throw new Error('useSession should be used within the AuthProvider')
}

return context
}
76 changes: 62 additions & 14 deletions apps/frontend/playwright.config.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,74 @@
import { defineConfig, devices } from '@playwright/test'
import {
defineConfig,
devices,
type PlaywrightTestConfig
} from '@playwright/test'

export default defineConfig({
timeout: 30000,
retries: 3,
reporter: [['list'], ['json', { outputFile: 'test-results.json' }]],
testDir: './playwright/tests/',
retries: 3,
reporter: [
['list'],
['json', { outputFile: 'playwright/test-results.json' }]
],
webServer: {
command: 'pnpm dev',
url: 'http://localhost:5525',
reuseExistingServer: !process.env.CI,
timeout: 120 * 1000
},
use: {
baseURL: 'http://localhost:5525'
},
projects: [
// Setup projects
{
name: 'firefox',
use: { ...devices['Desktop Firefox'] }
name: 'Admin Setup',
testDir: './playwright/tests/admin',
testMatch: /.*\.setup\.ts/
},
{
name: 'webkit',
use: { ...devices['Desktop Safari'] }
name: 'User Setup',
testDir: './playwright/tests/user',
testMatch: /.*\.setup\.ts/
},
...getProjectsByBrowser()
]
})

function getProjectsByBrowser(): NonNullable<PlaywrightTestConfig['projects']> {
const browsers = [
'Desktop Safari',
'Desktop Firefox',
'Desktop Chrome',
'Desktop Edge'
] as const

return browsers.flatMap((browser) => [
{
name: browser,
testDir: './playwright/tests/non-auth',
use: {
...devices[browser]
}
},
{
name: 'Google Chrome',
use: { ...devices['Desktop Chrome'] }
name: `${browser} (User)`,
testDir: './playwright/tests/user',
dependencies: ['User Setup'],
use: {
...devices[browser],
storageState: 'playwright/.auth/user.json'
}
},
{
name: 'Microsoft Edge',
use: { ...devices['Desktop Edge'] }
name: `${browser} (Admin)`,
testDir: './playwright/tests/admin',
dependencies: ['Admin Setup'],
use: {
...devices[browser],
storageState: 'playwright/.auth/admin.json'
}
}
]
})
])
}
Loading