Skip to content

Commit

Permalink
Merge pull request #34 from SAP/addTests
Browse files Browse the repository at this point in the history
test: add new tests
  • Loading branch information
ANUGRAHG authored Sep 12, 2024
2 parents 60e2d1f + e9c5d03 commit 42994b1
Show file tree
Hide file tree
Showing 6 changed files with 426 additions and 8 deletions.
80 changes: 80 additions & 0 deletions cmd/generateConfig_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
package cmd

import (
"os"
"path/filepath"
"testing"
)

func TestSetupConfigDir(t *testing.T) {

t.Setenv("BTP_USERNAME", "username")
t.Setenv("BTP_PASSWORD", "password")
t.Setenv("BTP_GLOBALACCOUNT", "ga")

curWd, _ := os.Getwd()

setupConfigDir("configFolder")
if _, err := os.Stat(filepath.Join(curWd, "configFolder")); os.IsNotExist(err) {
t.Errorf("Directory should have been created")
}

if _, err := os.Stat(filepath.Join(curWd, "configFolder", "provider.tf")); os.IsNotExist(err) {
t.Errorf("File should have been copied to existing directory")
}

os.RemoveAll(filepath.Join(curWd, "configFolder"))
cleanup()
}

func setupTestEnvironment() (string, func()) {
tempDir, err := os.MkdirTemp("", "providerTest")
if err != nil {
panic(err)
}

return tempDir, func() {
os.RemoveAll(tempDir)
}
}

func TestConfigureProvider(t *testing.T) {
tempDir, cleanup := setupTestEnvironment()
defer cleanup()

TmpFolder = tempDir

t.Setenv("BTP_USERNAME", "testuser")
t.Setenv("BTP_PASSWORD", "testpass")
t.Setenv("BTP_GLOBALACCOUNT", "testaccount")
t.Setenv("BTP_CLI_SERVER_URL", "https://test.com")

configureProvider()
expectedFilePath := filepath.Join(TmpFolder, "provider.tf")
if _, err := os.Stat(expectedFilePath); os.IsNotExist(err) {
t.Errorf("Expected file %s does not exist", expectedFilePath)
}

expectedContent := `terraform {
required_providers {
btp = {
source = "SAP/btp"
version = "1.6.0"
}
}
}
provider "btp" {
globalaccount = "testaccount"
cli_server_url="https://test.com"
}`

content, err := os.ReadFile(expectedFilePath)
if err != nil {
t.Fatalf("Failed to read file %s: %v", expectedFilePath, err)
}

if string(content) != expectedContent {
t.Errorf("Content of the file %s does not match expected content.\nGot:\n%s\nExpected:\n%s", expectedFilePath, string(content), expectedContent)
}
}
8 changes: 1 addition & 7 deletions tfutils/docs.go
Original file line number Diff line number Diff line change
Expand Up @@ -1136,9 +1136,6 @@ func (p *tfMarkdownParser) parse(tfMarkdown []byte) (entityDocs, error) {
}
}

// // Get links.
// footerLinks := getFooterLinks(markdown)

doc, _ := cleanupDocument(p.rawname, p.ret)

return doc, nil
Expand Down Expand Up @@ -1166,10 +1163,7 @@ func GetDocsForResource(org string, provider string, resourcePrefix string, kind
markdownBytes, markdownFileName, found := getMarkdownDetails(org, provider,
resourcePrefix, kind, rawname, providerModuleVersion, githost)
if !found {
msg := fmt.Sprintf("could not find docs for %v %v.", kind, rawname)

log.Fatal(msg)
return entityDocs{}, nil
return entityDocs{}, fmt.Errorf("could not find docs for %v %v", kind, rawname)
}

doc, err := parseTFMarkdown(kind, markdownBytes, markdownFileName, rawname)
Expand Down
232 changes: 231 additions & 1 deletion tfutils/docs_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ func TestParseAttrReferenceSection(t *testing.T) {
assert.Len(t, ret.Attributes, 3)
}

func TestParseTFMarkdown(t *testing.T) {
func TestParseTFMarkdownResource(t *testing.T) {
t.Parallel()

type testCase struct {
Expand Down Expand Up @@ -123,6 +123,61 @@ func TestParseTFMarkdown(t *testing.T) {
}
}

func TestParseTFMarkdownDataSource(t *testing.T) {
t.Parallel()

type testCase struct {
name string
kind DocKind
rawName string
fileName string
}

test := func(name string, configure ...func(tc *testCase)) testCase {
tc := testCase{
name: name,
kind: "data-sources",
rawName: "btp_subaccount",
fileName: "subaccount.md",
}
for _, c := range configure {
c(&tc)
}
return tc
}

tests := []testCase{
test("subaccount"),
}

for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
require.NotZero(t, tt.name)
input := testFilePath(tt.name, "input_subaccount_data.md")
expected := filepath.Join(tt.name, "expected_subaccount_data.json")
p := &tfMarkdownParser{
kind: tt.kind,
markdownFileName: tt.fileName,
rawname: tt.rawName,
}

inputBytes, err := os.ReadFile(input)
require.NoError(t, err)

actual, err := p.parse(inputBytes)
require.NoError(t, err)

actualBytes, err := json.MarshalIndent(actual, "", " ")
if err != nil {
t.Fatal(err)
}
compareTestFile(t, expected, string(actualBytes), assert.JSONEq)
})
}
}

func compareTestFile(
t *testing.T, path, actual string,
comp func(t assert.TestingT, expected string, actual string, msgAndArgs ...interface{}) bool,
Expand Down Expand Up @@ -156,3 +211,178 @@ func readlines(t *testing.T, file string) []string {
func testFilePath(path ...string) string {
return filepath.Join(append([]string{"testdata"}, path...)...)
}

func TestReorganizeText(t *testing.T) {
tests := []struct {
input string
expected string
}{
{
input: "Creates a role in a directory.",
expected: "Creates a role in a directory.",
},
{
input: "Terraform string",
expected: "",
},
{
input: "\n(Optional)\nThe role description.",
expected: "The role description.",
},
{
input: "id -> The combined unique ID of the role",
expected: "id > The combined unique ID of the role",
},
{
input: "\n(Required)\nThe ID of the xsuaa application.",
expected: "The ID of the xsuaa application.",
},
}

for _, tt := range tests {
t.Run(tt.input, func(t *testing.T) {
got, elided := reorgenizeText(tt.input)

assert.Equal(t, tt.expected, got)
assert.Equalf(t, got == "", elided,
"We should only see an empty result for non-empty inputs if we have elided text")
})
}
}

func TestArgumentRegularExp(t *testing.T) {
tests := []struct {
name string
input []string
expected map[string]*argumentDocs
}{
{
name: "Discovers * bullet descriptions",
input: []string{
"* `id` - (Optional) A description of the directory",
"* `ipv6_address_count`- (Optional) A number of IPv6 addresses to associate with the primary network interface.",
"* `ipv6_addresses` - (Optional) Specify one or more IPv6 addresses from the range of the subnet to associate with the primary network interface",
"* `tags` - (Optional) A mapping of tags to assign to the resource.",
},
expected: map[string]*argumentDocs{
"id": {
description: "A description of the directory",
},
"ipv6_address_count": {
description: "A number of IPv6 addresses to associate with the primary network interface.",
},
"ipv6_addresses": {
description: "Specify one or more IPv6 addresses from the range of the subnet to associate with the primary network interface",
},
"tags": {
description: "A mapping of tags to assign to the resource.",
},
},
},
{
name: "Cleans up tabs",
input: []string{
"* `node_pool_config` (Input only) The configuration for the node pool. ",
" If specified, Dataproc attempts to create a node pool with the specified shape. ",
" If one with the same name already exists, it is verified against all specified fields. ",
" If a field differs, the virtual cluster creation will fail.",
},
expected: map[string]*argumentDocs{
"node_pool_config": {description: "The configuration for the node pool. \nIf specified, " +
"Dataproc attempts to create a node pool with the specified shape.\nIf one with the same name " +
"already exists, it is verified against all specified fields.\nIf a field differs, the virtual " +
"cluster creation will fail.",
},
},
},
}

for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
ret := entityDocs{
Arguments: make(map[string]*argumentDocs),
}
parseArgumentReferenceSection(tt.input, &ret)

assert.Equal(t, tt.expected, ret.Arguments)
})
}
}

func TestGetNestedBlockName(t *testing.T) {
var tests = []struct {
input string
expected string
}{
{"The `features` object supports the following:", "features"},
{"#### result_configuration Argument Reference", "result_configuration"},
{"### advanced_security_options", "advanced_security_options"},
{"### `server_side_encryption`", "server_side_encryption"},
{"### Failover Routing Policy", "failover_routing_policy"},
{"##### `log_configuration`", "log_configuration"},
{"## Import", ""},
}

for _, tt := range tests {
assert.Equal(t, tt.expected, getNestedBlockNames(tt.input))
}
}

func TestParseTextSeq(t *testing.T) {
turnaround := func(src string) {
res, err := parseTextSequenceFromNode(parseNode(src).FirstChild, true)
if err != nil {
t.Fatal(err)
}
assert.Equal(t, src, res)
}

turnaround("plain")
turnaround("`code`")
turnaround("*emph*")
turnaround("**strong**")
turnaround("[link](http://pulumi.com)")
turnaround("plain `code` *emph* **strong** [link](http://pulumi.com)")
turnaround(`(Block List, Max: 1) The definition for a Change widget. (see [below for nested schema]` +
`(#nestedblock--widget--group_definition--widget--change_definition))`)

res, err := parseTextSequenceFromNode(parseNode("request_max_bytes").FirstChild, false)
if err != nil {
t.Fatal(err)
}
assert.Equal(t, "request_max_bytes", res)
}

func TestGetDocsForResource(t *testing.T) {

doc, err := GetDocsForResource("SAP", "btp", "btp", "resources", "btp_subaccount_environment_instance", "v1.3.0", "github.com")

if err != nil {
t.Errorf("error is not expected")
}

assert.Equal(t, len(doc.Attributes), 6)
assert.Equal(t, doc.Import, "import {\n\t\t\t\tto = btp_subaccount_environment_instance.<resource_name>\n\t\t\t\tid = \"<subaccount_id>,<environment_instance_id>\"\n\t\t\t }")
}

func TestGetDocsForResource_MissingDoc(t *testing.T) {
org := "testOrg"
provider := "testProvider"
resourcePrefix := "testPrefix"
kind := DocKind("testKind") // Replace with actual DocKind value
rawname := "testRawname"
providerModuleVersion := "v1.0.0"
githost := "github.com"

_, err := GetDocsForResource(org, provider, resourcePrefix, kind, rawname, providerModuleVersion, githost)

if err == nil {
t.Errorf("expected an error but got nil")
}

expectedErrorMsg := "could not find docs for testKind testRawname"
if err.Error() != expectedErrorMsg {
t.Errorf("expected error message %q but got %q", expectedErrorMsg, err.Error())
}
}
23 changes: 23 additions & 0 deletions tfutils/files_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package tfutils

import (
"os"
"testing"

"github.com/stretchr/testify/assert"
)

func TestCreateFileWithContent(t *testing.T) {
fileName := "testfile.txt"
content := "This is a test."

defer os.Remove(fileName)

err := CreateFileWithContent(fileName, content)

assert.NoError(t, err, "expected no error when creating file with content")

fileData, err := os.ReadFile(fileName)
assert.NoError(t, err, "expected no error when reading the file")
assert.Equal(t, content, string(fileData), "file content should match the input content")
}
6 changes: 6 additions & 0 deletions tfutils/testdata/subaccount/expected_subaccount_data.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"Description": "Gets details about a subaccount.\n\n__Tip:__\nYou must be assigned to the admin or viewer role of the global account, directory, or subaccount.\n\n## Example Usage\n\n```terraform\n# Read a subaccount by ID\ndata \"btp_subaccount\" \"my_account_byid\" {\n id = \"6aa64c2f-38c1-49a9-b2e8-cf9fea769b7f\"\n}\n\n# Read a subaccount by region and subdomain\ndata \"btp_subaccount\" \"my_account_bysubdomain\" {\n region = \"eu10\"\n subdomain = \"my-subaccount-subdomain\"\n}\n```",
"Arguments": {},
"Attributes": {},
"Import": "data \"btp_subaccount\" \"all\"{\n id = \"The ID of the subaccount\" \n}\n"
}
Loading

0 comments on commit 42994b1

Please sign in to comment.