github.com/glennzw/gophish@v0.8.1-0.20190824020715-24fe998a3aa0/util/util_test.go (about)

     1  package util
     2  
     3  import (
     4  	"bytes"
     5  	"fmt"
     6  	"mime/multipart"
     7  	"net/http"
     8  	"reflect"
     9  	"testing"
    10  
    11  	"github.com/gophish/gophish/config"
    12  	"github.com/gophish/gophish/models"
    13  	"github.com/stretchr/testify/suite"
    14  )
    15  
    16  type UtilSuite struct {
    17  	suite.Suite
    18  }
    19  
    20  func (s *UtilSuite) SetupSuite() {
    21  	conf := &config.Config{
    22  		DBName:         "sqlite3",
    23  		DBPath:         ":memory:",
    24  		MigrationsPath: "../db/db_sqlite3/migrations/",
    25  	}
    26  	err := models.Setup(conf)
    27  	if err != nil {
    28  		s.T().Fatalf("Failed creating database: %v", err)
    29  	}
    30  	s.Nil(err)
    31  }
    32  
    33  func buildCSVRequest(csvPayload string) (*http.Request, error) {
    34  	csvHeader := "First Name,Last Name,Email\n"
    35  	body := new(bytes.Buffer)
    36  	writer := multipart.NewWriter(body)
    37  	part, err := writer.CreateFormFile("files[]", "example.csv")
    38  	if err != nil {
    39  		return nil, err
    40  	}
    41  	part.Write([]byte(csvHeader))
    42  	part.Write([]byte(csvPayload))
    43  	err = writer.Close()
    44  	if err != nil {
    45  		return nil, err
    46  	}
    47  	r, err := http.NewRequest("POST", "http://127.0.0.1", body)
    48  	if err != nil {
    49  		return nil, err
    50  	}
    51  	r.Header.Set("Content-Type", writer.FormDataContentType())
    52  	return r, nil
    53  }
    54  
    55  func (s *UtilSuite) TestParseCSVEmail() {
    56  	expected := models.Target{
    57  		BaseRecipient: models.BaseRecipient{
    58  			FirstName: "John",
    59  			LastName:  "Doe",
    60  			Email:     "johndoe@example.com",
    61  		},
    62  	}
    63  
    64  	csvPayload := fmt.Sprintf("%s,%s,<%s>", expected.FirstName, expected.LastName, expected.Email)
    65  	r, err := buildCSVRequest(csvPayload)
    66  	s.Nil(err)
    67  
    68  	got, err := ParseCSV(r)
    69  	s.Nil(err)
    70  	s.Equal(len(got), 1)
    71  	if !reflect.DeepEqual(expected, got[0]) {
    72  		s.T().Fatalf("Incorrect targets received. Expected: %#v\nGot: %#v", expected, got)
    73  	}
    74  }
    75  
    76  func TestUtilSuite(t *testing.T) {
    77  	suite.Run(t, new(UtilSuite))
    78  }