Skip to content

Commit

Permalink
fix: add tests for the account command
Browse files Browse the repository at this point in the history
  • Loading branch information
0xff-dev committed May 5, 2023
1 parent cbfc7ef commit 37819e0
Show file tree
Hide file tree
Showing 5 changed files with 314 additions and 3 deletions.
100 changes: 100 additions & 0 deletions pkg/account/create_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
/*
Copyright 2023 The Bestchains Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package account

import (
"bytes"
"fmt"
"os"
"reflect"
"sort"
"strings"
"testing"

"github.com/bestchains/bc-cli/pkg/common"
"k8s.io/cli-runtime/pkg/genericclioptions"
)

const (
createTestBasePath = ".create"
createTestPath = createTestBasePath + "/wallet"
userPrivateKey = "./pk.pem"
pkContent = `-----BEGIN PRIVATE KEY-----
MHcCAQEEIDuaob5MQI3tl8H/Z8L+VIiKaER1r/aojZfeRapKpbBhoAoGCCqGSM49
AwEHoUQDQgAER6bI26M8/6cEwpHNm+wHq/wxU4ISG/2xfcyGeAsghx4hAUjVg9rr
XYwFcMEK3BTGtx7v6Ai2OhxK4wF6/jibOA==
-----END PRIVATE KEY-----`
)

func TestNewCreateAccountCmd(t *testing.T) {
scanfFormat := "account/%s created"
bufOutput := bytes.NewBuffer([]byte{})
bufErrOutput := bytes.NewBuffer([]byte{})

f, err := os.Create(userPrivateKey)
if err != nil {
t.Fatal(err)
}
_, err = f.Write([]byte(pkContent))
if err != nil {
t.Fatal(err)
}
f.Close()

// step 1: Automatic generation of three accounts
createCmd := NewCreateAccountCmd(common.Options{IOStreams: genericclioptions.IOStreams{In: os.Stdin, Out: bufOutput, ErrOut: bufErrOutput}})
_ = createCmd.Flags().Set("wallet", createTestPath)
for i := 0; i < 3; i++ {
if err := createCmd.Execute(); err != nil {
t.Fatalf("run create account cmd error %s", err)
}
}

// step 2: Create an account with an existing private key
_ = createCmd.Flags().Set("pk", userPrivateKey)
if err := createCmd.Execute(); err != nil {
t.Fatalf("run create account cmd with pk error %s", err)
}

output := strings.Split(strings.TrimSpace(bufOutput.String()), "\n")
files := make([]string, len(output))
for i, o := range output {
var fileName string
fmt.Sscanf(o, scanfFormat, &fileName)
files[i] = fileName
}
sort.Strings(files)

// step 3: Check for file matches
dirEntries, err := os.ReadDir(createTestPath)
if err != nil {
t.Fatalf("run read dir error %s", err)
}
expectFiles := make([]string, 0)
for _, dir := range dirEntries {
if dir.IsDir() {
continue
}
expectFiles = append(expectFiles, dir.Name())
}
if !reflect.DeepEqual(expectFiles, files) {
t.Fatalf("expect %v get %v", expectFiles, files)
}

os.RemoveAll(createTestBasePath)
os.Remove(userPrivateKey)
}
90 changes: 90 additions & 0 deletions pkg/account/delete_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
/*
Copyright 2023 The Bestchains Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package account

import (
"bytes"
"fmt"
"os"
"testing"

"github.com/bestchains/bc-cli/pkg/common"
"k8s.io/cli-runtime/pkg/genericclioptions"
)

const (
delTestBasePath = ".delete"
delTestPath = getTestBasePath + "/wallet"
)

func TestNewDeleteAccountCmd(t *testing.T) {
// step 1: create 4 accounts.
b1 := bytes.NewBuffer([]byte{})
b2 := bytes.NewBuffer([]byte{})
createCmd := NewCreateAccountCmd(common.Options{IOStreams: genericclioptions.IOStreams{In: os.Stdin, Out: b1, ErrOut: b2}})
_ = createCmd.Flags().Set("wallet", getTestPath)
for i := 0; i < 4; i++ {
_ = createCmd.Execute()
}

deleteScanfFormat := "account \"%s\" deleted\n"
errFormat := "Error: account \"%s\" remove %s/%s: no such file or directory\n"
bufOutput := bytes.NewBuffer([]byte{})
bufErrOutput := bytes.NewBuffer([]byte{})
delCmd := NewDeleteAccountCmd(common.Options{IOStreams: genericclioptions.IOStreams{In: os.Stdin, Out: bufOutput, ErrOut: bufErrOutput}})
_ = delCmd.Flags().Set("wallet", delTestPath)

dirEntries, err := os.ReadDir(delTestPath)
if err != nil {
t.Fatalf("run read dir error %s", err)
}
expectOutput := bytes.NewBuffer([]byte{})
output := bytes.NewBuffer([]byte{})

normalDelFiles := make([]string, 0)
for _, dir := range dirEntries {
if dir.IsDir() {
continue
}
expectOutput.WriteString(fmt.Sprintf(deleteScanfFormat, dir.Name()))
normalDelFiles = append(normalDelFiles, dir.Name())
}

// step 1: First delete all accounts.
delCmd.SetArgs(normalDelFiles)
if err := delCmd.Execute(); err != nil {
t.Fatalf("run delete account cmd with args %v error %s", normalDelFiles, err)
}
output.Write(bufOutput.Bytes())

// step 2: Delete non-existent account information
missingAccount := []string{"abc", "def"}
for _, account := range missingAccount {
expectOutput.WriteString(fmt.Sprintf(errFormat, account, delTestPath, account))
}

delCmd.SetArgs(missingAccount)
if err := delCmd.Execute(); err != nil {
t.Fatalf("run delete account cmd with args %v error %s", missingAccount, err)
}
output.Write(bufErrOutput.Bytes())
if expectOutput.String() != output.String() {
t.Fatalf("expect \r\n%s get \r\n%s", expectOutput.String(), output.String())
}

os.RemoveAll(delTestBasePath)
}
91 changes: 91 additions & 0 deletions pkg/account/get_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
/*
Copyright 2023 The Bestchains Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package account

import (
"bytes"
"fmt"
"os"
"reflect"
"testing"

"github.com/bestchains/bc-cli/pkg/common"
"k8s.io/cli-runtime/pkg/genericclioptions"
)

const (
getTestBasePath = ".get"
getTestPath = getTestBasePath + "/wallet"
)

func TestNewGetAccountCmd(t *testing.T) {
// step 1: create 4 accounts.
b1 := bytes.NewBuffer([]byte{})
b2 := bytes.NewBuffer([]byte{})
createCmd := NewCreateAccountCmd(common.Options{IOStreams: genericclioptions.IOStreams{In: os.Stdin, Out: b1, ErrOut: b2}})
_ = createCmd.Flags().Set("wallet", getTestPath)
for i := 0; i < 4; i++ {
_ = createCmd.Execute()
}

bufOutput := bytes.NewBuffer([]byte{})
bufErrOutput := bytes.NewBuffer([]byte{})
getCmd := NewGetAccountCmd(common.Options{IOStreams: genericclioptions.IOStreams{In: os.Stdin, Out: bufOutput, ErrOut: bufErrOutput}})
expectOutput := []string{fmt.Sprintf("Error: stat %s: no such file or directory\nError: stat /tmp/def/abc: no such file or directory\n", common.WalletConfigDir)}

dirEntries, err := os.ReadDir(getTestPath)
if err != nil {
t.Fatalf("run read dir error %s", err)
}

buf := bytes.NewBuffer([]byte("ACCOUNT\n"))
for _, dir := range dirEntries {
if dir.IsDir() {
continue
}
buf.WriteString(fmt.Sprint(dir.Name(), "\n"))
}
expectOutput = append(expectOutput, buf.String())

output := make([]string, 0)
// step 1: Use the default path and the default path does not exist
if err := getCmd.Execute(); err != nil {
t.Fatalf("run get account cmd with default wallet %s error %s", common.WalletConfigDir, err)
}
// step 2: Using non-existent paths to obtain account information
_ = getCmd.Flags().Set("wallet", "/tmp/def/abc")
if err := getCmd.Execute(); err != nil {
t.Fatalf("run get account cmd with wallet /tmp/def/abc error %s", err)
}
output = append(output, bufErrOutput.String())

// step 3: Use the correct path to get the correct account information output
_ = getCmd.Flags().Set("wallet", getTestPath)
// Create a new directory and file, the get command should ignore it.
_ = os.Mkdir(getTestPath+"/xyz", 0755)
_, _ = os.Create(getTestPath + "/xyz/zyx")

if err := getCmd.Execute(); err != nil {
t.Fatalf("run get account cmd with wallet %s error %s", getTestPath, err)
}
output = append(output, bufOutput.String())
if !reflect.DeepEqual(expectOutput, output) {
t.Fatalf("expect %v get %v", expectOutput, output)
}

os.RemoveAll(getTestBasePath)
}
29 changes: 29 additions & 0 deletions pkg/account/types_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/*
Copyright 2023 The Bestchains Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package account

import "testing"

func TestGetByHeader(t *testing.T) {
input := []string{"abc", "def", "xyz"}
for _, i := range input {
x := AccountPrinter(i).GetByHeader("ACCOUNT")
if x != i {
t.Fatalf("expect %s get %s", i, x)
}
}
}
7 changes: 4 additions & 3 deletions pkg/depository/create.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,14 +23,15 @@ import (
"encoding/base64"
"encoding/json"
"fmt"
"github.com/bestchains/bc-cli/pkg/common"
uhttp "github.com/bestchains/bc-cli/pkg/utils/http"
"github.com/bestchains/bestchains-contracts/library/context"
"net/http"
"net/url"
"strconv"
"time"

"github.com/bestchains/bc-cli/pkg/common"
uhttp "github.com/bestchains/bc-cli/pkg/utils/http"
"github.com/bestchains/bestchains-contracts/library/context"

"github.com/bestchains/bestchains-contracts/library"
"github.com/spf13/cobra"
)
Expand Down

0 comments on commit 37819e0

Please sign in to comment.