Files
Packer-Cn/datasource/http/data_acc_test.go
hashicorp-copywrite[bot] 19055df3ec [COMPLIANCE] License changes (#12568)
* Updating the license from MPL to Business Source License

Going forward, this project will be licensed under the Business Source License v1.1. Please see our blog post for more details at https://hashi.co/bsl-blog, FAQ at https://hashi.co/license-faq, and details of the license at www.hashicorp.com/bsl.

* Update copyright file headers to BUSL-1.1

---------

Co-authored-by: hashicorp-copywrite[bot] <110428419+hashicorp-copywrite[bot]@users.noreply.github.com>
2023-08-10 15:53:29 -07:00

113 lines
2.3 KiB
Go

// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: BUSL-1.1
package http
import (
_ "embed"
"fmt"
"io/ioutil"
"os"
"os/exec"
"regexp"
"testing"
"github.com/hashicorp/packer-plugin-sdk/acctest"
)
//go:embed test-fixtures/basic.pkr.hcl
var testDatasourceBasic string
//go:embed test-fixtures/empty_url.pkr.hcl
var testDatasourceEmptyUrl string
//go:embed test-fixtures/404_url.pkr.hcl
var testDatasource404Url string
func TestHttpDataSource(t *testing.T) {
tests := []struct {
Name string
Path string
Error bool
Outputs map[string]string
}{
{
Name: "basic_test",
Path: testDatasourceBasic,
Error: false,
Outputs: map[string]string{
"url": "url is https://www.packer.io/",
// Check that body is not empty
"body": "body is true",
},
},
{
Name: "url_is_empty",
Path: testDatasourceEmptyUrl,
Error: true,
Outputs: map[string]string{
"error": "the `url` must be specified",
},
},
{
Name: "404_url",
Path: testDatasource404Url,
Error: true,
},
}
for _, tt := range tests {
t.Run(tt.Name, func(t *testing.T) {
testCase := &acctest.PluginTestCase{
Name: tt.Name,
Setup: func() error {
return nil
},
Teardown: func() error {
return nil
},
Template: tt.Path,
Type: "http",
Check: func(buildCommand *exec.Cmd, logfile string) error {
if buildCommand.ProcessState != nil {
if buildCommand.ProcessState.ExitCode() != 0 && !tt.Error {
return fmt.Errorf("Bad exit code. Logfile: %s", logfile)
}
if tt.Error && buildCommand.ProcessState.ExitCode() == 0 {
return fmt.Errorf("Expected Bad exit code.")
}
}
if tt.Outputs != nil {
logs, err := os.Open(logfile)
if err != nil {
return fmt.Errorf("Unable find %s", logfile)
}
defer logs.Close()
logsBytes, err := ioutil.ReadAll(logs)
if err != nil {
return fmt.Errorf("Unable to read %s", logfile)
}
logsString := string(logsBytes)
for key, val := range tt.Outputs {
if matched, _ := regexp.MatchString(val+".*", logsString); !matched {
t.Fatalf(
"logs doesn't contain expected log %v with value %v in %q",
key,
val,
logsString)
}
}
}
return nil
},
}
acctest.TestPlugin(t, testCase)
})
}
}