package webserver import ( "strings" "testing" ) const sampleMainConf = `user www; worker_processes 1; events { worker_connections 768; multi_accept on; } http { include /etc/nginx/mime.types; keepalive_timeout 65; gzip on; gzip_min_length 1000; gzip_comp_level 2; # a comment with a brace } must not confuse the parser server { listen 80; location / { root /www/wwwroot/demo; } } } ` func TestPatchPerformanceUpdatesAndKeepsStructure(t *testing.T) { p := Performance{ WorkerProcesses: "auto", WorkerConnections: 51200, KeepaliveTimeout: 60, Gzip: true, GzipMinLengthKB: 1, GzipCompLevel: 5, ClientMaxBodyMB: 50, ServerNamesHashBucket: 512, ClientHeaderBufferKB: 32, ClientBodyBufferKB: 512, } out, err := patchPerformance(sampleMainConf, p) if err != nil { t.Fatal(err) } for _, want := range []string{ "worker_processes auto;", "worker_connections 51200;", "keepalive_timeout 60;", "gzip on;", "gzip_min_length 1k;", "gzip_comp_level 5;", "client_max_body_size 50m;", "server_names_hash_bucket_size 512;", "client_header_buffer_size 32k;", "client_body_buffer_size 512k;", "multi_accept on;", "location / {", } { if !strings.Contains(out, want) { t.Errorf("patched config missing %q\n%s", want, out) } } if strings.Count(out, "worker_connections") != 1 { t.Errorf("worker_connections duplicated:\n%s", out) } if strings.Count(out, "gzip on;") != 1 { t.Errorf("gzip duplicated:\n%s", out) } } func TestPatchPerformanceInsertsMissingDirectives(t *testing.T) { src := `worker_processes 1; events { worker_connections 128; } http { include /etc/nginx/mime.types; } ` p := Performance{ WorkerProcesses: "2", WorkerConnections: 4096, KeepaliveTimeout: 30, Gzip: false, GzipMinLengthKB: 10, GzipCompLevel: 3, ClientMaxBodyMB: 20, ServerNamesHashBucket: 64, ClientHeaderBufferKB: 8, ClientBodyBufferKB: 64, } out, err := patchPerformance(src, p) if err != nil { t.Fatal(err) } for _, want := range []string{ "worker_processes 2;", "worker_connections 4096;", "keepalive_timeout 30;", "gzip off;", "client_max_body_size 20m;", "include /etc/nginx/mime.types;", } { if !strings.Contains(out, want) { t.Errorf("missing %q\n%s", want, out) } } } func TestPresentationValidate(t *testing.T) { ok := Performance{ WorkerProcesses: "auto", WorkerConnections: 1024, KeepaliveTimeout: 60, GzipMinLengthKB: 1, GzipCompLevel: 5, ClientMaxBodyMB: 50, ServerNamesHashBucket: 64, ClientHeaderBufferKB: 8, ClientBodyBufferKB: 16, } if err := ok.validate(); err != nil { t.Fatalf("valid config rejected: %v", err) } bad := ok bad.ServerNamesHashBucket = 100 if err := bad.validate(); err == nil { t.Fatal("non power-of-two bucket accepted") } bad = ok bad.WorkerProcesses = "many" if err := bad.validate(); err == nil { t.Fatal("invalid worker_processes accepted") } }