github.com/gophish/gophish@v0.12.2-0.20230915144530-8e7929441393/config/config_test.go (about)

     1  package config
     2  
     3  import (
     4  	"encoding/json"
     5  	"io/ioutil"
     6  	"os"
     7  	"reflect"
     8  	"testing"
     9  
    10  	log "github.com/gophish/gophish/logger"
    11  )
    12  
    13  var validConfig = []byte(`{
    14  	"admin_server": {
    15  		"listen_url": "127.0.0.1:3333",
    16  		"use_tls": true,
    17  		"cert_path": "gophish_admin.crt",
    18  		"key_path": "gophish_admin.key"
    19  	},
    20  	"phish_server": {
    21  		"listen_url": "0.0.0.0:8080",
    22  		"use_tls": false,
    23  		"cert_path": "example.crt",
    24  		"key_path": "example.key"
    25  	},
    26  	"db_name": "sqlite3",
    27  	"db_path": "gophish.db",
    28  	"migrations_prefix": "db/db_",
    29  	"contact_address": ""
    30  }`)
    31  
    32  func createTemporaryConfig(t *testing.T) *os.File {
    33  	f, err := ioutil.TempFile("", "gophish-config")
    34  	if err != nil {
    35  		t.Fatalf("unable to create temporary config: %v", err)
    36  	}
    37  	return f
    38  }
    39  
    40  func removeTemporaryConfig(t *testing.T, f *os.File) {
    41  	err := f.Close()
    42  	if err != nil {
    43  		t.Fatalf("unable to remove temporary config: %v", err)
    44  	}
    45  }
    46  
    47  func TestLoadConfig(t *testing.T) {
    48  	f := createTemporaryConfig(t)
    49  	defer removeTemporaryConfig(t, f)
    50  	_, err := f.Write(validConfig)
    51  	if err != nil {
    52  		t.Fatalf("error writing config to temporary file: %v", err)
    53  	}
    54  	// Load the valid config
    55  	conf, err := LoadConfig(f.Name())
    56  	if err != nil {
    57  		t.Fatalf("error loading config from temporary file: %v", err)
    58  	}
    59  
    60  	expectedConfig := &Config{}
    61  	err = json.Unmarshal(validConfig, &expectedConfig)
    62  	if err != nil {
    63  		t.Fatalf("error unmarshaling config: %v", err)
    64  	}
    65  	expectedConfig.MigrationsPath = expectedConfig.MigrationsPath + expectedConfig.DBName
    66  	expectedConfig.TestFlag = false
    67  	expectedConfig.AdminConf.CSRFKey = ""
    68  	expectedConfig.Logging = &log.Config{}
    69  	if !reflect.DeepEqual(expectedConfig, conf) {
    70  		t.Fatalf("invalid config received. expected %#v got %#v", expectedConfig, conf)
    71  	}
    72  
    73  	// Load an invalid config
    74  	_, err = LoadConfig("bogusfile")
    75  	if err == nil {
    76  		t.Fatalf("expected error when loading invalid config, but got %v", err)
    77  	}
    78  }