github.com/leanovate/gopter@v0.2.9/properties.go (about)

     1  package gopter
     2  
     3  import "testing"
     4  
     5  // Properties is a collection of properties that should be checked in a test
     6  type Properties struct {
     7  	parameters *TestParameters
     8  	props      map[string]Prop
     9  	propNames  []string
    10  }
    11  
    12  // NewProperties create new Properties with given test parameters.
    13  // If parameters is nil default test parameters will be used
    14  func NewProperties(parameters *TestParameters) *Properties {
    15  	if parameters == nil {
    16  		parameters = DefaultTestParameters()
    17  	}
    18  	return &Properties{
    19  		parameters: parameters,
    20  		props:      make(map[string]Prop, 0),
    21  		propNames:  make([]string, 0),
    22  	}
    23  }
    24  
    25  // Property add/defines a property in a test.
    26  func (p *Properties) Property(name string, prop Prop) {
    27  	p.propNames = append(p.propNames, name)
    28  	p.props[name] = prop
    29  }
    30  
    31  // Run checks all definied propertiesand reports the result
    32  func (p *Properties) Run(reporter Reporter) bool {
    33  	success := true
    34  	for _, propName := range p.propNames {
    35  		prop := p.props[propName]
    36  
    37  		result := prop.Check(p.parameters)
    38  
    39  		reporter.ReportTestResult(propName, result)
    40  		if !result.Passed() {
    41  			success = false
    42  		}
    43  	}
    44  	return success
    45  }
    46  
    47  // TestingRun checks all definied properties with a testing.T context.
    48  // This the preferred wait to run property tests as part of a go unit test.
    49  func (p *Properties) TestingRun(t *testing.T, opts ...interface{}) {
    50  	reporter := ConsoleReporter(true)
    51  	for _, opt := range opts {
    52  		if r, ok := opt.(Reporter); ok {
    53  			reporter = r
    54  		}
    55  	}
    56  	if !p.Run(reporter) {
    57  		t.Errorf("failed with initial seed: %d", p.parameters.Seed())
    58  	}
    59  }