github.com/biogo/biogo@v1.0.4/errors/chain_test.go (about)

     1  // Copyright ©2011-2013 The bíogo Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package errors
     6  
     7  import (
     8  	"fmt"
     9  	"io"
    10  
    11  	"gopkg.in/check.v1"
    12  )
    13  
    14  func (s *S) TestChain(c *check.C) {
    15  	err := io.EOF
    16  	err = Link(err, fmt.Errorf("failed: %v", err))
    17  	c.Check(err.Error(), check.Equals, "failed: EOF")
    18  	c.Check(Cause(err), check.Equals, io.EOF)
    19  	c.Check(Errors(err), check.DeepEquals, []error{io.EOF, fmt.Errorf("failed: EOF")})
    20  }
    21  
    22  // userChain is the basic implementation without an UnwrapAll method.
    23  type userChain []error
    24  
    25  func (c userChain) Error() string {
    26  	if len(c) > 0 {
    27  		return c[len(c)-1].Error()
    28  	}
    29  	return ""
    30  }
    31  func (c userChain) Cause() error {
    32  	if len(c) > 0 {
    33  		return c[0]
    34  	}
    35  	return nil
    36  }
    37  func (c userChain) Link(err error) Chain { return append(c, err) }
    38  func (c userChain) Last() (Chain, error) {
    39  	switch len(c) {
    40  	case 0:
    41  		return nil, nil
    42  	case 1:
    43  		return nil, c[0]
    44  	default:
    45  		return c[:len(c)-1], c[len(c)-1]
    46  	}
    47  }
    48  
    49  func (s *S) TestUserChain(c *check.C) {
    50  	var err error = userChain{io.EOF}
    51  	err = Link(err, fmt.Errorf("failed: %v", err))
    52  	c.Check(err.Error(), check.Equals, "failed: EOF")
    53  	c.Check(Cause(err), check.Equals, io.EOF)
    54  	unwrapped := Errors(err)
    55  	c.Check(Cause(err), check.Equals, unwrapped[0])
    56  	for i, e := range unwrapped {
    57  		c.Check(e.Error(), check.Equals, []error{io.EOF, fmt.Errorf("failed: EOF")}[i].Error())
    58  	}
    59  }