setSystemHosts.test.ts 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import fs from 'node:fs/promises'
  2. import path from 'node:path'
  3. import { fileURLToPath } from 'node:url'
  4. import { beforeEach, describe, expect, it, vi } from 'vitest'
  5. import { clearData } from '../_base'
  6. import configSet from '../../src/main/actions/config/set'
  7. const dirname = path.dirname(fileURLToPath(import.meta.url))
  8. const systemHostsPath = path.join(dirname, '..', 'tmp', 'system-hosts')
  9. vi.mock('../../src/main/actions/hosts/getPathOfSystemHostsPath', () => ({
  10. default: async () => systemHostsPath,
  11. }))
  12. describe('setSystemHosts', () => {
  13. beforeEach(async () => {
  14. await clearData()
  15. ;(global as typeof global & { tracer?: { add: (message: string) => void } }).tracer = {
  16. add() {},
  17. }
  18. await configSet('write_mode', 'overwrite')
  19. await configSet('cmd_after_hosts_apply', '')
  20. await fs.mkdir(path.dirname(systemHostsPath), { recursive: true })
  21. await fs.writeFile(systemHostsPath, '127.0.0.1 localhost\n', 'utf-8')
  22. })
  23. it('writes CRLF when the platform line ending is Windows', async () => {
  24. vi.doMock('../../src/common/newlines', async () => {
  25. const actual = await vi.importActual<typeof import('../../src/common/newlines')>(
  26. '../../src/common/newlines',
  27. )
  28. return {
  29. ...actual,
  30. getLineEndingForPlatform: () => '\r\n' as const,
  31. }
  32. })
  33. const { default: setSystemHosts } = await import('../../src/main/actions/hosts/setSystemHosts')
  34. const result = await setSystemHosts('1.1.1.1 example.test\n# note\n')
  35. expect(result.success).toBe(true)
  36. expect(await fs.readFile(systemHostsPath, 'utf-8')).toBe('1.1.1.1 example.test\r\n# note\r\n')
  37. })
  38. })