api/tests/docker.test.ts
77 lines · 2491 bytes
1// Unit tests for the Portainer template -> docker run / compose builders
2import { describe, it, expect } from 'vitest'
3import { composeFile, normalize, runCommand, type Template } from '@/lib/docker'
4
5const template: Template = {
6 title: 'Pi-hole',
7 image: 'pihole/pihole:latest',
8 ports: ['53:53/tcp', '8080:80'],
9 env: [{ name: 'TZ', default: 'UTC' }, { name: 'WEBPASSWORD' }],
10 volumes: [
11 { bind: '/etc/pihole', container: '/data', readonly: true },
12 { container: '/cache' },
13 ],
14 restart_policy: 'unless-stopped',
15}
16
17describe('normalize', () => {
18 it('strips symbols and lowercases', () => {
19 expect(normalize('Pi-Hole!')).toBe('pihole')
20 })
21})
22
23describe('runCommand', () => {
24 const out = runCommand(template)
25
26 it('lays out flags then the image last', () => {
27 expect(out.startsWith('docker run -d \\')).toBe(true)
28 expect(out.endsWith('pihole/pihole:latest')).toBe(true)
29 })
30
31 it('maps ports, env placeholders, read-only volumes and restart', () => {
32 expect(out).toContain('-p 53:53/tcp')
33 expect(out).toContain('-e WEBPASSWORD=${WEBPASSWORD}')
34 expect(out).toContain('-v /etc/pihole:/data:ro')
35 expect(out).toContain('--restart=unless-stopped')
36 })
37
38 it('renders a bind-less volume as an anonymous mount', () => {
39 expect(out).toContain('-v /cache')
40 expect(out).not.toContain('undefined')
41 })
42})
43
44describe('composeFile', () => {
45 const out = composeFile(template)
46
47 it('builds a service keyed by a slugified title', () => {
48 expect(out).toContain('services:')
49 expect(out).toContain('pi-hole:')
50 expect(out).toContain('image: "pihole/pihole:latest"')
51 })
52
53 it('quotes ports, keeps protocol and resolves env defaults', () => {
54 expect(out).toContain('- "53:53/tcp"')
55 expect(out).toContain('TZ: UTC')
56 expect(out).toContain('WEBPASSWORD: ')
57 })
58
59 it('maps a bind-less volume to its container path', () => {
60 expect(out).toContain('- /cache')
61 expect(out).not.toContain('undefined')
62 })
63
64 it('drops empty sections rather than emitting bare keys or undefined', () => {
65 const bare = composeFile({ title: 'bare', image: 'redis' })
66 expect(bare).not.toContain('undefined')
67 expect(bare).not.toContain('environment:')
68 expect(bare).not.toContain('ports:')
69 expect(bare).not.toContain('volumes:')
70 })
71
72 it('trims slug punctuation from the service key', () => {
73 expect(composeFile({ title: 'Nextcloud (Container)', image: 'x' })).toContain(
74 'nextcloud-container:',
75 )
76 })
77})