Skip to content

Commit 4938b7c

Browse files
committed
fix: Refactor log logic for tests
1 parent ba974fb commit 4938b7c

9 files changed

Lines changed: 108 additions & 303 deletions

File tree

tests/e2e/config/testConfig.ts

Lines changed: 5 additions & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -4,69 +4,17 @@ import { config } from 'dotenv';
44
// Load .env.e2e file for E2E test configuration
55
config({ path: '.env.e2e' });
66

7-
export interface TestConfig {
8-
// Environment settings
9-
environment: {
10-
tempDir: string;
11-
isolatedPort: number;
12-
clearCache: boolean;
13-
mockData: boolean;
14-
clearStorage: boolean;
15-
};
16-
17-
// App settings
18-
app: {
19-
timeout: number;
20-
retryAttempts: number;
21-
waitForSelectorTimeout: number;
22-
};
23-
24-
// Test data settings
25-
testData: {
26-
mockProjectName: string;
27-
mockSceneTitle: string;
28-
mockSceneDescription: string;
29-
};
30-
}
31-
32-
export const testConfig: TestConfig = {
33-
environment: {
34-
// Use absolute path to tests/temp/ directory for all test data
35-
tempDir: join(resolve(process.cwd()), 'tests', 'temp'),
36-
isolatedPort: 3001,
37-
clearCache: true,
38-
mockData: true,
39-
clearStorage: true,
40-
},
41-
42-
app: {
43-
timeout: parseInt(process.env.E2E_TIMEOUT || '10000', 10),
44-
retryAttempts: 3,
45-
waitForSelectorTimeout: 5000,
46-
},
47-
48-
testData: {
49-
mockProjectName: 'test-scene',
50-
mockSceneTitle: process.env.E2E_SCENE_NAME || 'E2E test scene',
51-
mockSceneDescription: 'A test scene for E2E testing',
52-
},
53-
};
54-
55-
// Helper function to get test-specific temp directory
56-
export const getTestTempDir = (): string => {
57-
return join(testConfig.environment.tempDir);
58-
};
59-
7+
// Helper function to get scene directory path (actually used)
608
export const getTestScenesDir = (sceneName: string): string => {
61-
return join(testConfig.environment.tempDir, 'scenes', sceneName);
9+
return join(resolve(process.cwd()), 'tests', 'temp', 'scenes', sceneName);
6210
};
6311

6412
// Helper function to get environment variables for tests
6513
export const getTestEnv = (): Record<string, string> => ({
6614
NODE_ENV: 'test',
6715
ELECTRON_ENABLE_LOGGING: 'false',
6816
ELECTRON_ENABLE_STACK_DUMPING: 'false',
69-
PORT: testConfig.environment.isolatedPort.toString(),
17+
PORT: '3001',
7018
DISABLE_ANALYTICS: 'true',
7119
DISABLE_TELEMETRY: 'true',
7220
DISABLE_AUTO_UPDATE: 'true',
@@ -78,4 +26,6 @@ export const getTestEnv = (): Record<string, string> => ({
7826
// Include E2E-specific environment variables
7927
E2E: process.env.E2E || 'true',
8028
...(process.env.E2E_NAME ? { E2E_NAME: process.env.E2E_NAME } : {}),
29+
// Debug logging control
30+
DEBUG: process.env.DEBUG || 'false',
8131
});

tests/e2e/features/scenes/preview.spec.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@ test.describe('when previewing a scene', () => {
4545
await Promise.race([
4646
app.waitForEvent('window', {
4747
predicate: page => page.getByTestId('debugger').isVisible({ timeout: 10_000 }),
48+
timeout: 30_000,
4849
}),
4950
setup.editorPage.isInstallClientModalVisible(),
5051
]);

tests/e2e/globalSetup.ts

Lines changed: 7 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1,42 +1,19 @@
1-
import { mkdir } from 'fs/promises';
2-
import { join, resolve } from 'path';
31
import { ElectronUtils } from './utils/electron';
4-
import { TestEnvironment } from './utils/testEnvironment';
52
import { ensureTempDir } from './scripts/ensureTempDir';
3+
import { getTestEnv } from './config/testConfig';
4+
import { log } from './utils/logger';
65

76
async function globalSetup() {
87
// Global setup before all tests
9-
console.log('Setting up e2e test environment...');
8+
log.info('Setting up e2e test environment...');
109

1110
// Ensure base /temp directory exists
1211
await ensureTempDir();
1312

14-
// Create the specific paths that the Electron app expects in E2E mode
15-
const tempDir = join(resolve(process.cwd()), 'tests', 'temp');
16-
const userDataPath = join(tempDir, 'userData');
17-
const homePath = join(tempDir, 'home');
18-
19-
try {
20-
// Create userData directory
21-
await mkdir(userDataPath, { recursive: true, mode: 0o755 });
22-
console.log(`✅ Created userData directory: ${userDataPath}`);
23-
24-
// Create home directory
25-
await mkdir(homePath, { recursive: true, mode: 0o755 });
26-
console.log(`✅ Created home directory: ${homePath}`);
27-
28-
// Create scenes directory
29-
const scenesPath = join(tempDir, 'scenes');
30-
await mkdir(scenesPath, { recursive: true, mode: 0o755 });
31-
console.log(`✅ Created scenes directory: ${scenesPath}`);
32-
} catch (error) {
33-
console.error(`❌ Failed to create required directories: ${error}`);
34-
throw error;
35-
}
36-
37-
// Set up clean, isolated test environment
38-
const testEnvironment = new TestEnvironment();
39-
await testEnvironment.setup();
13+
// Set up isolated environment variables
14+
const testEnv = getTestEnv();
15+
Object.assign(process.env, testEnv);
16+
log.info('Environment variables configured');
4017

4118
// Reset any existing Electron instances
4219
await ElectronUtils.resetGlobalInstance();

tests/e2e/globalTeardown.ts

Lines changed: 6 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,11 @@
11
import { rm } from 'fs/promises';
22
import { join, resolve } from 'path';
33
import { ElectronUtils } from './utils/electron';
4+
import { log } from './logger';
45

56
async function globalTeardown() {
67
// Global cleanup after all tests
7-
console.log('Cleaning up e2e test environment...');
8+
log.info('Cleaning up e2e test environment...');
89

910
// Ensure Electron app is closed
1011
const electronUtils = new ElectronUtils();
@@ -19,21 +20,17 @@ async function globalTeardown() {
1920
try {
2021
// Clean up userData directory
2122
await rm(userDataPath, { recursive: true, force: true });
22-
console.log(`🗑️ Cleaned up userData directory: ${userDataPath}`);
23+
log.info(`Cleaned up userData directory: ${userDataPath}`);
2324

2425
// Clean up home directory
2526
await rm(homePath, { recursive: true, force: true });
26-
console.log(`🗑️ Cleaned up home directory: ${homePath}`);
27+
log.info(`Cleaned up home directory: ${homePath}`);
2728

2829
// Clean up scenes directory
2930
await rm(scenesPath, { recursive: true, force: true });
30-
console.log(`🗑️ Cleaned up scenes directory: ${scenesPath}`);
31-
32-
// Optionally clean up the entire temp directory
33-
// await rm(tempDir, { recursive: true, force: true });
34-
// console.log(`🗑️ Cleaned up temp directory: ${tempDir}`);
31+
log.info(`Cleaned up scenes directory: ${scenesPath}`);
3532
} catch (error) {
36-
console.warn(`⚠️ Could not clean up directories: ${error}`);
33+
log.warn(`Could not clean up directories: ${error}`);
3734
}
3835
}
3936

tests/e2e/utils/electron.ts

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { rm } from 'fs/promises';
33
import type { ElectronApplication, Page } from 'playwright';
44
import { _electron as electron } from 'playwright';
55
import dotenv from 'dotenv';
6+
import { log } from './logger';
67

78
dotenv.config({ path: '.env.e2e' });
89

@@ -88,9 +89,9 @@ export class ElectronUtils {
8889
// Only clear cookies, which is usually safe
8990
await page.context().clearCookies();
9091

91-
console.log('🧹 Cleared cookies safely');
92+
log.info('Cleared cookies safely');
9293
} catch (error) {
93-
console.warn('⚠️ Could not clear cookies:', error);
94+
log.warn('Could not clear cookies:', error);
9495
}
9596
}
9697

@@ -108,9 +109,9 @@ export class ElectronUtils {
108109
// Clear cookies
109110
await this.page.context().clearCookies();
110111

111-
console.log('🔄 Reset page state');
112+
log.info('Reset page state');
112113
} catch (error) {
113-
console.warn('⚠️ Could not reset page state:', error);
114+
log.warn('Could not reset page state:', error);
114115
}
115116
}
116117
}
@@ -120,14 +121,14 @@ export class ElectronUtils {
120121
try {
121122
const singletonLockPath = path.join(userDataPath, 'SingletonLock');
122123
await rm(singletonLockPath, { force: true });
123-
console.log('🔓 Cleaned up singleton lock');
124+
log.info('Cleaned up singleton lock');
124125
} catch (error) {
125126
// Singleton lock doesn't exist, which is fine
126127
}
127128
}
128129

129130
// Static method for backward compatibility (deprecated)
130131
static async resetGlobalInstance(): Promise<void> {
131-
console.warn('⚠️ resetGlobalInstance is deprecated. Use instance-based approach instead.');
132+
log.warn('resetGlobalInstance is deprecated. Use instance-based approach instead.');
132133
}
133134
}

tests/e2e/utils/logger.ts

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
/**
2+
* Logger utility for E2E tests
3+
* Only prints when DEBUG=true environment variable is set
4+
*/
5+
6+
export type LogLevel = 'info' | 'warn' | 'error' | 'debug';
7+
8+
interface LogMessage {
9+
level: LogLevel;
10+
message: string;
11+
emoji?: string;
12+
timestamp?: string;
13+
}
14+
15+
class Logger {
16+
private isDebugEnabled: boolean;
17+
18+
constructor() {
19+
this.isDebugEnabled = process.env.DEBUG === 'true';
20+
}
21+
22+
private formatMessage({ level, message, emoji, timestamp }: LogMessage): string {
23+
const time = timestamp || new Date().toISOString();
24+
const emojiPrefix = emoji ? `${emoji} ` : '';
25+
const levelPrefix = `[${level.toUpperCase()}]`;
26+
27+
return `${levelPrefix} ${time} ${emojiPrefix}${message}`;
28+
}
29+
30+
private shouldLog(level: LogLevel): boolean {
31+
if (!this.isDebugEnabled) {
32+
return false;
33+
}
34+
35+
// Allow error logs even when DEBUG is false for critical issues
36+
if (level === 'error') {
37+
return true;
38+
}
39+
40+
return this.isDebugEnabled;
41+
}
42+
43+
info(message: string, emoji?: string): void {
44+
if (this.shouldLog('info')) {
45+
console.log(this.formatMessage({ level: 'info', message, emoji }));
46+
}
47+
}
48+
49+
warn(message: string, emoji?: string): void {
50+
if (this.shouldLog('warn')) {
51+
console.warn(this.formatMessage({ level: 'warn', message, emoji }));
52+
}
53+
}
54+
55+
error(message: string, emoji?: string): void {
56+
if (this.shouldLog('error')) {
57+
console.error(this.formatMessage({ level: 'error', message, emoji }));
58+
}
59+
}
60+
61+
debug(message: string, emoji?: string): void {
62+
if (this.shouldLog('debug')) {
63+
console.log(this.formatMessage({ level: 'debug', message, emoji }));
64+
}
65+
}
66+
}
67+
68+
// Export singleton instance
69+
export const log = new Logger();
70+
71+
// Export the class for testing purposes
72+
export { Logger };

tests/e2e/utils/storageCleaner.ts

Lines changed: 0 additions & 51 deletions
This file was deleted.

0 commit comments

Comments
 (0)