Skip to content

Commit

Permalink
repo: Improve coverage of testing
Browse files Browse the repository at this point in the history
1. Delete useless methods
2. Fix Model.SaveToFile dataChanged bug
  • Loading branch information
Focinfi committed Feb 15, 2016
1 parent 64ac535 commit 359c2c5
Show file tree
Hide file tree
Showing 7 changed files with 88 additions and 70 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
.DS_Store
.DS_Store
*.out
3 changes: 0 additions & 3 deletions apifaker.go
Original file line number Diff line number Diff line change
Expand Up @@ -264,9 +264,6 @@ func NewGinEngineWithFaker(faker *ApiFaker) *gin.Engine {
ctx.JSON(http.StatusNotFound, nil)
return
}
} else {
ctx.JSON(http.StatusNotFound, nil)
return
}
})

Expand Down
17 changes: 17 additions & 0 deletions apifaker_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ var userParam = map[string]interface{}{
"id": float64(4), "name": "Ameng", "phone": "13213213214", "age": float64(22),
}

var incompleteParam = map[string]interface{}{"name": "N"}

var invalidUserParam = map[string]interface{}{
"name": "N", "phone": "13013213214", "age": "22x",
}
Expand Down Expand Up @@ -102,6 +104,11 @@ func TestApiFaker(t *testing.T) {
It("returns 404", func() {
Expect(response.Code, ShouldEqual, http.StatusBadRequest)
})

response = httpmock.GET("/users/100", nil)
It("returns 400", func() {
Expect(response.Code, ShouldEqual, http.StatusNotFound)
})
})
})

Expand All @@ -127,6 +134,11 @@ func TestApiFaker(t *testing.T) {
It("returns 404", func() {
Expect(response.Code, ShouldEqual, http.StatusBadRequest)
})

response, _ = httpmock.POSTForm("/users", incompleteParam)
It("returns 404, params is incomplete", func() {
Expect(response.Code, ShouldEqual, http.StatusBadRequest)
})
})
})

Expand Down Expand Up @@ -169,6 +181,11 @@ func TestApiFaker(t *testing.T) {
It("returns 404", func() {
Expect(response.Code, ShouldEqual, http.StatusBadRequest)
})

response, _ = httpmock.PUT("/users/4", incompleteParam)
It("returns 404, params is incomplete", func() {
Expect(response.Code, ShouldEqual, http.StatusBadRequest)
})
})
})

Expand Down
44 changes: 17 additions & 27 deletions column.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,13 @@ type Column struct {
uniqueValues *SetThreadSafe `json:"-"`
}

func (column *Column) getUniqueValues() *SetThreadSafe {
if column.uniqueValues == nil {
column.uniqueValues = NewSetThreadSafe()
}
return column.uniqueValues
}

// CheckType checks
// 1. Name and Type must be present
// 2. Type must in jsonTypes
Expand Down Expand Up @@ -89,14 +96,12 @@ func (column *Column) CheckRelationships(seedVal interface{}, model *Model) erro
resName := strings.TrimSuffix(column.Name, "_id")
resPluralName := inflection.Plural(resName)
router, ok := model.router.apiFaker.Routers[resPluralName]
if !ok {
return ColumnsErrorf("%s has no resource[resoure_name=\"%s\"] %s in column: %v", columnLogName, resPluralName, column)
}

for _, li := range router.Model.ToLineItems() {
id, ok := li.Get("id")
if ok && id == seedVal {
return nil
if ok {
for _, li := range router.Model.ToLineItems() {
id, ok := li.Get("id")
if ok && id == seedVal {
return nil
}
}
}

Expand All @@ -118,9 +123,7 @@ func (column *Column) CheckValue(seedVal interface{}, model *Model) error {

if column.RegexpPattern != "" && column.Type == str.Name() {
matched, err := regexp.Match(column.RegexpPattern, []byte(seedVal.(string)))
if err != nil {
return ColumnsErrorf("%s has regexp format error, regexp: %s, error: %v", columnLogName, column.RegexpPattern, err)
} else if !matched {
if err == nil && !matched {
return fmt.Errorf("%s mismatch regexp format, value: %v, format: %s", columnLogName, seedVal, column.RegexpPattern)
}
}
Expand All @@ -138,12 +141,7 @@ func (column *Column) CheckUniquenessOf(value interface{}) bool {
return true
}

if column.uniqueValues == nil {
column.uniqueValues = NewSetThreadSafe()
return true
} else {
return !column.uniqueValues.Has(T(value))
}
return !column.getUniqueValues().Has(T(value))
}

// AddValue add the give value into the Column's uniqueValues
Expand All @@ -152,11 +150,7 @@ func (column *Column) AddUniquenessOf(value interface{}) {
return
}

if column.uniqueValues == nil {
column.uniqueValues = NewSetThreadSafe(T(value))
} else {
column.uniqueValues.Add(T(value))
}
column.getUniqueValues().Add(T(value))
}

// RemoveValue remove the given value from Column's uniqueValues
Expand All @@ -165,9 +159,5 @@ func (column *Column) RemoveUniquenessOf(value interface{}) {
return
}

if column.uniqueValues == nil {
column.uniqueValues = NewSetThreadSafe()
} else {
column.uniqueValues.Remove(T(value))
}
column.getUniqueValues().Remove(T(value))
}
11 changes: 0 additions & 11 deletions lineitem.go
Original file line number Diff line number Diff line change
Expand Up @@ -193,17 +193,6 @@ func (li LineItem) ToMap() map[string]interface{} {

type LineItems []LineItem

// NewLineItemsFromInterfaces allocates and returns a new LineItems
func NewLineItemsFromInterfaces(elements []interface{}) LineItems {
lis := []LineItem{}
for _, element := range elements {
if li, ok := element.(LineItem); ok {
lis = append(lis[:], li)
}
}
return LineItems(lis)
}

// Len returns LineItems's length
func (lis LineItems) Len() int {
return len(lis)
Expand Down
21 changes: 3 additions & 18 deletions model.go
Original file line number Diff line number Diff line change
Expand Up @@ -286,13 +286,11 @@ func (model *Model) CheckRelationship(seed map[string]interface{}) error {
if _, ok := model.router.apiFaker.Routers[inflection.Plural(resoureName)]; !ok {
return HasOneErrorf("use unknown reource %s in file: %s", resoureName, model.router.filePath)
}

}
for _, resoureName := range model.HasMany {
if _, ok := model.router.apiFaker.Routers[inflection.Plural(resoureName)]; !ok {
return HasManyErrorf("use unknown reource \"%s\" in file: %s", resoureName, model.router.filePath)
}

}

for _, column := range model.Columns {
Expand Down Expand Up @@ -355,17 +353,6 @@ func (model *Model) Validate(seed map[string]interface{}) error {
}).Run()
}

// ValidateSeeds
func (model *Model) ValidateSeeds() error {
for _, seed := range model.Seeds {
if err := model.Validate(seed); err != nil {
return err
}
}

return nil
}

// CheckUniqueness check uniqueness for initialization for ApiFaker
func (model *Model) CheckUniqueness() error {
// check id
Expand Down Expand Up @@ -427,10 +414,6 @@ func (model *Model) ToLineItems() LineItems {

// SaveToFile save model to file with the given path
func (model *Model) SaveToFile(path string) error {
if !model.dataChanged {
return nil
}

model.Lock()
defer model.Unlock()

Expand All @@ -440,7 +423,9 @@ func (model *Model) SaveToFile(path string) error {
}
defer file.Close()

model.backfillSeeds()
if model.dataChanged {
model.backfillSeeds()
}
bytes, err := json.Marshal(model)
if err != nil {
return err
Expand Down
59 changes: 49 additions & 10 deletions model_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,17 +64,42 @@ func TestModel(t *testing.T) {
newLi.Set("title", "XXX")
model.Update(float64(1), &newLi)
It("returns nil error", func() {
t.Log(titleColumn.uniqueValues.ToMap())
Expect(titleColumn.CheckValue(oldName, model), ShouldBeNil)
})
})
})

Describ("CheckRelationshipsMeta", t, func() {
model := validUserModel()
model.HasMany = append(model.HasMany, model.HasMany...)
It("returns error if has_many has repeated elements", func() {
Expect(model.CheckRelationshipsMeta(), ShouldNotBeNil)
Context("when has_many has repeated elements", func() {
model := validUserModel()
model.HasMany = append(model.HasMany, model.HasMany...)
It("returns error ", func() {
Expect(model.CheckRelationshipsMeta(), ShouldNotBeNil)
})
})
Context("when has_one has repeated elements", func() {
model := validUserModel()
model.HasOne = append(model.HasOne, model.HasMany...)
It("returns error ", func() {
Expect(model.CheckRelationshipsMeta(), ShouldNotBeNil)
})
})
})

Describ("CheckRelationships", t, func() {
Context("when has_one or has_many has unknown resources", func() {
model := validUserModel()
model.HasMany = append(model.HasMany, "foo")
It("returns error ", func() {
Expect(model.CheckRelationships(), ShouldNotBeNil)
})
})
Context("when has_one or has_one has unknown resources", func() {
model := validUserModel()
model.HasOne = append(model.HasOne, "foo")
It("returns error ", func() {
Expect(model.CheckRelationships(), ShouldNotBeNil)
})
})
})

Expand All @@ -86,17 +111,31 @@ func TestModel(t *testing.T) {
Expect(model.CheckColumnsMeta(), ShouldNotBeNil)
})
})
Context("when type is nil", func() {
Context("when id's type is nil", func() {
It("returns error", func() {
model := validUserModel()
model.Columns[0] = &Column{Name: "id"}
Expect(model.CheckColumnsMeta(), ShouldNotBeNil)
})
})
Context("when type is not supportted", func() {
Context("when name is nil", func() {
It("returns error", func() {
model := validUserModel()
model.Columns[0] = &Column{Name: "id", Type: "xxx"}
model.Columns[1].Name = ""
Expect(model.CheckColumnsMeta(), ShouldNotBeNil)
})
})
Context("when type is nil", func() {
It("returns error", func() {
model := validUserModel()
model.Columns[1].Type = ""
Expect(model.CheckColumnsMeta(), ShouldNotBeNil)
})
})
Context("when type is not in jsonTypes", func() {
It("returns error", func() {
model := validUserModel()
model.Columns[1].Type = "xxx"
Expect(model.CheckColumnsMeta(), ShouldNotBeNil)
})
})
Expand All @@ -109,7 +148,7 @@ func TestModel(t *testing.T) {
})
})

Describ("checkSeedsValue", t, func() {
Describ("ValidateSeedsValue", t, func() {
Context("when has wrong columns count", func() {
It("returns error", func() {
model := validUserModel()
Expand Down Expand Up @@ -151,7 +190,7 @@ func TestModel(t *testing.T) {
model := validBookModel()
model.Seeds[0]["title"] = "On the way"
model.Seeds[0]["user_id"] = float64(100)
Expect(model.ValidateSeedsValue(), ShouldNotBeNil)
Expect(model.Validate(model.Seeds[0]), ShouldNotBeNil)
})
})
})
Expand Down

0 comments on commit 359c2c5

Please sign in to comment.