Skip to content

Commit

Permalink
Testcases added to support better test coverage
Browse files Browse the repository at this point in the history
More testcases have been added for registering and
enrolling a user, and also for util functions to provide
better test coverage. Make file now checks to see
if there is 75% test coverage for each package. If not,
it will return appropriate message.

Code was also reorganized and directory structure was changed.
Filenames all use lowercasing now.

https://jira.hyperledger.org/browse/FAB-862

Change-Id: I82c0265fd3a2bbae4c2b9f2145234db818cbb8cb
Signed-off-by: Saad Karim <[email protected]>
  • Loading branch information
Saad Karim committed Nov 15, 2016
1 parent 3ef8656 commit 33fa279
Show file tree
Hide file tree
Showing 104 changed files with 2,177 additions and 6,605 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
bin
cli/cop/cop
*.csr
*.der
22 changes: 16 additions & 6 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -24,21 +24,31 @@
# - tests - runs all the cop tests
# - unit-tests - runs the go-test based unit tests

all: license cop tests unit-tests
all: license vet lint format imports cop tests unit-tests

license: .FORCE
@scripts/license_check && exit
@scripts/check_license

format: .FORCE
@scripts/check_format

imports: .FORCE
@scripts/check_imports

lint: .FORCE
@scripts/check_lint

vet: .FORCE
@scripts/check_vet

cop:
@echo "Building cop in bin directory ..."
@mkdir -p bin && cd cli/cop && go build -o ../../bin/cop
@mkdir -p bin && cd cli && go build -o ../bin/cop
@echo "Built bin/cop"

tests: cop unit-tests

unit-tests: cop
@echo "Running cop unit tests ..."
@go test `go list ./... | grep -v "/vendor/"`
@echo "Completed cop unit tests"
@scripts/run_tests

.FORCE:
32 changes: 3 additions & 29 deletions api.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,7 @@ limitations under the License.

package cop

import (
"fmt"
"os"

real "github.com/hyperledger/fabric-cop/api"
def "github.com/hyperledger/fabric-cop/lib/defaultImpl"
)
import real "github.com/hyperledger/fabric-cop/api"

// Mgr is the main interface to COP functionality
type Mgr interface {
Expand Down Expand Up @@ -83,14 +77,12 @@ type RegisterRequest struct {
real.RegisterRequest
}

// EnrollRequest is an enroll request
type EnrollRequest struct {
real.EnrollRequest
}

type Attribute struct {
real.Attribute
}

// UserRecord is a user's record
type UserRecord struct {
real.UserRecord
}
Expand All @@ -115,21 +107,3 @@ const (
type Error interface {
real.Error
}

func init() {
provider := os.Getenv("COP.PROVIDER")
if provider == "" {
provider = "default"
}
if provider == "default" {
real.SetMgr(new(def.Mgr))
} else {
fmt.Printf("invalid COP provider: %s\n", provider)
os.Exit(1)
}
}

// NewCertMgr creates a COP certificate manager
func NewCertMgr() CertMgr {
return real.NewCertMgr()
}
26 changes: 15 additions & 11 deletions api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,11 @@ limitations under the License.

package api

import (
"github.com/hyperledger/fabric-cop/idp"
"github.com/jmoiron/sqlx"
)

// Mgr is the main interface to COP functionality
type Mgr interface {

Expand All @@ -45,7 +50,7 @@ type Client interface {
SetServerAddr(dir string)

// Register a new identity
Register(registration *RegisterRequest) Error
Register(registration *RegisterRequest) ([]byte, Error)

// Enroll a registered identity
// Enroll(user, pass string) (Identity, Error)
Expand Down Expand Up @@ -166,24 +171,21 @@ type KeyHandler interface {

// RegisterRequest information
type RegisterRequest struct {
User string `json:"user"`
Group string `json:"group"`
Attributes []Attribute `json:"attrs,omitempty"`
CallerID string `json:"callerID"`
User string `json:"user"`
Group string `json:"group"`
Type string `json:"type"` // Type of identity being registered (e.g. "peer, app, user")
Attributes []idp.Attribute `json:"attrs,omitempty"`
CallerID string `json:"callerID"`
}

// EnrollRequest - information need to process enrollment request to server
type EnrollRequest struct {
User string `json:"user"`
Token []byte `json:"token"`
CSR []byte `json:"csr"`
}

// Attribute is an arbitrary name/value pair
type Attribute struct {
Name string `json:"name"`
Value []string `json:"value"`
}

// Enrollment - information need to process enrollment request to client
type Enrollment struct {
ID string
EnrollSecret []byte
Expand All @@ -196,13 +198,15 @@ type UserRecord struct {
ID string `db:"id"`
EnrollmentID string `db:"enrollmentId"`
Token string `db:"token"`
Type string `db:"type"`
Metadata string `db:"metadata"`
State int `db:"state"`
Key int `db:"key"`
}

// Accessor abstracts the CRUD of certdb objects from a DB.
type Accessor interface {
SetDB(db *sqlx.DB)
InsertUser(user UserRecord) error
DeleteUser(id string) error
UpdateUser(user UserRecord) error
Expand Down
8 changes: 5 additions & 3 deletions api/error.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,8 @@ import (
)

// The following are all the error codes returned by COP.
// COP's errors begin with 100,000 to avoid an overlap with CFSSL`errors.
// Add all new errors to the end of the current list in order to maintain
// backwards compatibility with earlier versions of this file.
// COP's errors start from 100,000 to avoid an overlap with CFSSL Toolkit's errors.
// Append new errors to the end of the below list for backward compatibility.
const (
// NotImplemented means not yet implemented but plans to support
NotImplemented int = 100000 + iota
Expand All @@ -45,6 +44,9 @@ const (
Input
Output
UserStoreError
EnrollingUserError
RegisteringUserError
AuthorizationError
)

// Error is an interface with a Code method
Expand Down
16 changes: 16 additions & 0 deletions api/error_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,18 @@ package api

import (
"testing"

cfsslErr "github.com/cloudflare/cfssl/errors"
)

func TestNewError(t *testing.T) {
err := NewError(InvalidProviderName, "invalid factory name: %s", "foo")
if err == nil {
t.Error("Error creation failed.")
}
if err.Error() == "" {
t.Errorf("returned empty error")
}
if err.Code() != 100004 {
t.Errorf("invalid error code; expecting 100003 but found %d", err.ErrorCode)
}
Expand All @@ -41,3 +46,14 @@ func TestWrapError(t *testing.T) {
t.Error("Wrap creation failed.")
}
}

func TestCfsslWrapError(t *testing.T) {
err := cfsslErr.New(cfsslErr.CertificateError, cfsslErr.Unknown)
if err == nil {
t.Fatal("CFSSL Error creation failed.")
}
err2 := WrapCFSSLError(err, 1, "wrapped error")
if err2 == nil {
t.Fatal("COP Error creation failed.")
}
}
73 changes: 48 additions & 25 deletions cli/cop/client/enroll/enroll.go → cli/client/enroll.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,19 +14,21 @@ See the License for the specific language governing permissions and
limitations under the License.
*/

package enroll
package client

import (
"fmt"
"io/ioutil"
"path/filepath"

"github.com/cloudflare/cfssl/cli"
"github.com/cloudflare/cfssl/csr"
"github.com/cloudflare/cfssl/log"
cutil "github.com/hyperledger/fabric-cop/cli/cop/client"
"github.com/hyperledger/fabric-cop/cli/cop/config"

"github.com/hyperledger/fabric-cop/idp"
"github.com/hyperledger/fabric-cop/util"
)

var usageText = `cop client enroll -- Enroll with COP server
var enrollUsageText = `cop client enroll -- Enroll with COP server
Usage of client enroll command:
Enroll a client and get an ecert:
Expand All @@ -35,19 +37,15 @@ Usage of client enroll command:
Arguments:
ID: Enrollment ID
SECRET: Enrollment secret returned by register
CSRJSON: Certificate Signing Request JSON information
COP-SERVER-ADDR: COP server address
CSRJSON: Certificate Signing Request JSON information (Optional)
Flags:
`

var flags = []string{}

func myMain(args []string, c cli.Config) error {
fmt.Println("enroll - main()")

config.Init(&c)
var enrollFlags = []string{}

func enrollMain(args []string, c cli.Config) error {
log.Debug("in myMain of 'cop client enroll'")

id, args, err := cli.PopFirstArgument(args)
Expand All @@ -60,32 +58,57 @@ func myMain(args []string, c cli.Config) error {
return err
}

csrJSON, args, err := cli.PopFirstArgument(args)
if err != nil {
return err
}
_ = csrJSON // TODO: Make csrJSON optional arg and add to EnrollmentRequest below if present

copServer, args, err := cli.PopFirstArgument(args)
if err != nil {
return err
}

_ = args

req := &idp.EnrollmentRequest{
Name: id,
Secret: secret,
}

client, err := cutil.NewClient(copServer)
if len(args) > 0 {
if filepath.Ext(args[0]) == ".json" {
csrJSON, _, err := cli.PopFirstArgument(args)
if err != nil {
return err
}
csrJSONBytes, err := ioutil.ReadFile(csrJSON)
if err != nil {
return err
}

var CertRequest csr.CertificateRequest
util.Unmarshal(csrJSONBytes, &CertRequest, "Certificate request")
req.CR = &CertRequest
}
log.Debug("Other argument besides optional csr provided")
}

_ = args

client, err := NewClient(copServer)
if err != nil {
return err
}
ID, err := client.Enroll(req)
if err != nil {
return err
}

idByte, err := ID.Serialize()
if err != nil {
return err
}
home := util.GetDefaultHomeDir()
err = util.WriteFile(home+"/client.json", idByte, 0644)
if err != nil {
return err
}
_, err = client.Enroll(req)

return err
return nil
}

// Command assembles the definition of Command 'enroll'
var Command = &cli.Command{UsageText: usageText, Flags: flags, Main: myMain}
// EnrollCommand is the enroll command
var EnrollCommand = &cli.Command{UsageText: enrollUsageText, Flags: enrollFlags, Main: enrollMain}
Loading

0 comments on commit 33fa279

Please sign in to comment.