func main() { QUnit.ModuleLifecycle("A", Scenario{}) QUnit.Test("just a test", func(assert QUnit.QUnitAssert) { QUnit.Expect(1) assert.Ok(true, "") }) QUnit.Module("B") QUnit.Test("test 1", func(assert QUnit.QUnitAssert) { square := func(x int) int { return x * x } result := square(2) assert.DeepEqual(strconv.Itoa(result), strconv.Itoa(4), "square(2) equals 4") }) QUnit.Test("test 2", func(assert QUnit.QUnitAssert) { assert.Ok(true, "true succeeds") }) QUnit.Module("C") QUnit.Test("test 3", func(assert QUnit.QUnitAssert) { assert.Ok(true, "0 means false") }) QUnit.AsyncTest("Async Test", func() *js.Object { QUnit.Expect(1) return js.Global.Call("setTimeout", func() { QUnit.Ok(true, "async test failure") QUnit.Start() }, 500) }) }
func main() { wsBaseURL := getWSBaseURL() qunit.Module("websocket.WebSocket") qunit.Test("Invalid URL", func(assert qunit.QUnitAssert) { qunit.Expect(1) ws, err := websocket.New("blah://blah.example/invalid") if err == nil { ws.Close() assert.Ok(false, "Got no error, but expected an invalid URL error") return } assert.Ok(true, fmt.Sprintf("Received an error: %s", err)) }) qunit.AsyncTest("Immediate close", func() interface{} { qunit.Expect(2) ws, err := websocket.New(wsBaseURL + "immediate-close") if err != nil { qunit.Ok(false, fmt.Sprintf("Error opening WebSocket: %s", err)) qunit.Start() return nil } ws.AddEventListener("open", false, func(ev *js.Object) { qunit.Ok(true, "WebSocket opened") }) ws.AddEventListener("close", false, func(ev *js.Object) { const ( CloseNormal = 1000 CloseNoReasonSpecified = 1005 // IE10 hates it when the server closes without sending a close reason ) closeEvent := dom.WrapEvent(ev).(*dom.CloseEvent) if closeEvent.Code != CloseNormal && closeEvent.Code != CloseNoReasonSpecified { qunit.Ok(false, fmt.Sprintf("WebSocket close was not clean (code %d)", closeEvent.Code)) qunit.Start() return } qunit.Ok(true, "WebSocket closed") qunit.Start() }) return nil }) qunit.Module("websocket.Conn") qunit.AsyncTest("Immediate close", func() interface{} { go func() { defer qunit.Start() ws, err := websocket.Dial(wsBaseURL + "immediate-close") if err != nil { qunit.Ok(false, fmt.Sprintf("Error opening WebSocket: %s", err)) return } qunit.Ok(true, "WebSocket opened") _, err = ws.Read(nil) if err == io.EOF { qunit.Ok(true, "Received EOF") } else if err != nil { qunit.Ok(false, fmt.Sprintf("Unexpected error in second read: %s", err)) } else { qunit.Ok(false, "Expected EOF in second read, got no error") } }() return nil }) qunit.AsyncTest("Failed open", func() interface{} { go func() { defer qunit.Start() ws, err := websocket.Dial(wsBaseURL + "404-not-found") if err == nil { ws.Close() qunit.Ok(false, "Got no error, but expected an error in opening the WebSocket.") return } qunit.Ok(true, fmt.Sprintf("WebSocket failed to open: %s", err)) }() return nil }) qunit.AsyncTest("Binary read", func() interface{} { qunit.Expect(3) go func() { defer qunit.Start() ws, err := websocket.Dial(wsBaseURL + "binary-static") if err != nil { qunit.Ok(false, fmt.Sprintf("Error opening WebSocket: %s", err)) return } qunit.Ok(true, "WebSocket opened") var expectedData = []byte{0x00, 0x01, 0x02, 0x03, 0x04} receivedData := make([]byte, len(expectedData)) n, err := ws.Read(receivedData) if err != nil { qunit.Ok(false, fmt.Sprintf("Error in first read: %s", err)) return } receivedData = receivedData[:n] if !bytes.Equal(receivedData, expectedData) { qunit.Ok(false, fmt.Sprintf("Received data did not match expected data. Got % x, expected % x.", receivedData, expectedData)) } else { qunit.Ok(true, fmt.Sprintf("Received data: % x", receivedData)) } _, err = ws.Read(receivedData) if err == io.EOF { qunit.Ok(true, "Received EOF") } else if err != nil { qunit.Ok(false, fmt.Sprintf("Unexpected error in second read: %s", err)) } else { qunit.Ok(false, "Expected EOF in second read, got no error") } }() return nil }) qunit.AsyncTest("Timeout", func() interface{} { qunit.Expect(2) go func() { defer qunit.Start() ws, err := websocket.Dial(wsBaseURL + "wait-30s") if err != nil { qunit.Ok(false, fmt.Sprintf("Error opening WebSocket: %s", err)) return } qunit.Ok(true, "WebSocket opened") start := time.Now() ws.SetReadDeadline(start.Add(1 * time.Second)) _, err = ws.Read(nil) if err != nil && err.Error() == "i/o timeout: deadline reached" { totalTime := time.Now().Sub(start) if totalTime < 750*time.Millisecond { qunit.Ok(false, fmt.Sprintf("Timeout was too short: Received timeout after %s", totalTime)) return } qunit.Ok(true, fmt.Sprintf("Received timeout after %s", totalTime)) } else if err != nil { qunit.Ok(false, fmt.Sprintf("Unexpected error in read: %s", err)) } else { qunit.Ok(false, "Expected timeout in read, got no error") } }() return nil }) }
func main() { qunit.Test("SetAndGet", func(assert qunit.QUnitAssert) { err := locstor.SetItem("foo", "bar") assert.Equal(err, nil, "Error in SetItem") gotItem, err := locstor.GetItem("foo") assert.Equal(err, nil, "Error in GetItem") assert.Equal(gotItem, "bar", "") }) qunit.Test("Key", func(assert qunit.QUnitAssert) { err := locstor.SetItem("foo", "bar") assert.Equal(err, nil, "Error in SetItem") gotKey, err := locstor.Key("bar") assert.Equal(err, nil, "Error in Key") assert.Equal(gotKey, "foo", "") }) qunit.Test("RemoveItem", func(assert qunit.QUnitAssert) { err := locstor.SetItem("foo", "bar") assert.Equal(err, nil, "Error in SetItem") err = locstor.RemoveItem("foo") assert.Equal(err, nil, "Error in RemoveItem") _, err = locstor.GetItem("foo") assert.NotEqual(err, nil, "Expected error but got nil") assert.DeepEqual(reflect.TypeOf(err), reflect.TypeOf(locstor.ItemNotFoundError{}), "Error was not correct the correct type") }) qunit.Test("Length", func(assert qunit.QUnitAssert) { err := locstor.SetItem("foo", "bar") assert.Equal(err, nil, "Error in SetItem") err = locstor.SetItem("biz", "baz") assert.Equal(err, nil, "Error in SetItem") gotLength, err := locstor.Length() assert.Equal(err, nil, "Error in Length") assert.Equal(gotLength, 2, "") }) qunit.Test("Clear", func(assert qunit.QUnitAssert) { err := locstor.SetItem("foo", "bar") assert.Equal(err, nil, "Error in SetItem") err = locstor.SetItem("biz", "baz") assert.Equal(err, nil, "Error in SetItem") err = locstor.Clear() assert.Equal(err, nil, "Error in Clear") gotLength, err := locstor.Length() assert.Equal(err, nil, "Error in Length") assert.Equal(gotLength, 0, "") }) testObjects := []interface{}{ "foo", 123, true, []string{"a", "b", "c"}, map[string]bool{"yes": true, "false": false}, struct { Foo string Bar int }{ Foo: "fiz", Bar: 42, }, } qunit.Test("JSONEncoderDecoder", func(assert qunit.QUnitAssert) { for _, original := range testObjects { encoded, err := locstor.JSONEncoding.Encode(original) assert.Equal(err, nil, fmt.Sprintf("Error in Encode: %v", err)) decoded := reflect.New(reflect.TypeOf(original)).Interface() err = locstor.JSONEncoding.Decode(encoded, &decoded) assert.Equal(err, nil, fmt.Sprintf("Error in Decode: %v", err)) assert.DeepEqual(decoded, original, "") } }) qunit.Test("BinaryEncoderDecoder", func(assert qunit.QUnitAssert) { for _, original := range testObjects { encoded, err := locstor.BinaryEncoding.Encode(original) assert.Equal(err, nil, fmt.Sprintf("Error in Encode: %v", err)) decoded := reflect.New(reflect.TypeOf(original)).Interface() err = locstor.BinaryEncoding.Decode(encoded, decoded) assert.Equal(err, nil, fmt.Sprintf("Error in Decode: %v", err)) assert.DeepEqual(decoded, original, "") } }) qunit.Test("DataStoreSave", func(assert qunit.QUnitAssert) { store := locstor.NewDataStore(locstor.JSONEncoding) for _, original := range testObjects { err := store.Save("foo", original) assert.Equal(err, nil, fmt.Sprintf("Error in Save: %v", err)) got := reflect.New(reflect.TypeOf(original)).Interface() err = store.Find("foo", got) assert.Equal(err, nil, fmt.Sprintf("Error in Find: %v", err)) assert.DeepEqual(got, original, "") } }) qunit.Test("DataStoreDelete", func(assert qunit.QUnitAssert) { store := locstor.NewDataStore(locstor.JSONEncoding) for _, original := range testObjects { err := store.Save("foo", original) assert.Equal(err, nil, fmt.Sprintf("Error in Save: %v", err)) err = store.Delete("foo") assert.Equal(err, nil, fmt.Sprintf("Error in Delete: %v", err)) err = store.Find("foo", nil) assert.NotEqual(err, nil, fmt.Sprintf("Expected error in Find but got nil")) assert.DeepEqual(reflect.TypeOf(err), reflect.TypeOf(locstor.ItemNotFoundError{}), "Error was not correct the correct type") } }) }
func main() { qunit.Test("GetString", func(assert qunit.QUnitAssert) { defer reset() // Create a form with some inputs and values. All the input types here // should be convertible to strings via GetString. container.SetInnerHTML(`<form> <input name="default" value="foo" > <input type="email" name="email" value="*****@*****.**" > <input type="hidden" name="secret" value="this is a secret" > <input type="password" name="password" value="password123" > <input type="search" name="search" value="foo bar" > <input type="tel" name="phone" value="867-5309" > <input type="text" name="text" value="This is some text." > <input type="url" name="url" value="http://example.com" > </form>`) formEl := container.QuerySelector("form") form, err := form.Parse(formEl) assertNoError(assert, err, "") expectedValues := map[string]string{ "default": "foo", "email": "*****@*****.**", "secret": "this is a secret", "password": "******", "search": "foo bar", "phone": "867-5309", "text": "This is some text.", "url": "http://example.com", } // Check that the parsed value for each input is correct. for name, expectedValue := range expectedValues { got, err := form.GetString(name) assertNoError(assert, err, "") assert.Equal(got, expectedValue, "Incorrect value for field: "+name) } }) qunit.Test("GetInt", func(assert qunit.QUnitAssert) { defer reset() // Create a form with some inputs and values. All the input types here // should be convertible to ints via GetInt. container.SetInnerHTML(`<form> <input name="default" value="23" > <input type="tel" name="tel" value="8675309" > <input type="text" name="text" value="-789" > <input type="number" name="number" value="123456789" > </form>`) formEl := container.QuerySelector("form") form, err := form.Parse(formEl) assertNoError(assert, err, "") expectedValues := map[string]int{ "default": 23, "tel": 8675309, "text": -789, "number": 123456789, } // Check that the parsed value for each input is correct. for name, expectedValue := range expectedValues { got, err := form.GetInt(name) assertNoError(assert, err, "") assert.Equal(got, expectedValue, "Incorrect value for field: "+name) } }) qunit.Test("GetUint", func(assert qunit.QUnitAssert) { defer reset() // Create a form with some inputs and values. All the input types here // should be convertible to uints via GetUint. container.SetInnerHTML(`<form> <input name="default" value="23" > <input type="tel" name="tel" value="8675309" > <input type="text" name="text" value="789" > <input type="number" name="number" value="123456789" > </form>`) formEl := container.QuerySelector("form") form, err := form.Parse(formEl) assertNoError(assert, err, "") expectedValues := map[string]uint{ "default": 23, "tel": 8675309, "text": 789, "number": 123456789, } // Check that the parsed value for each input is correct. for name, expectedValue := range expectedValues { got, err := form.GetUint(name) assertNoError(assert, err, "") assert.Equal(got, expectedValue, "Incorrect value for field: "+name) } }) qunit.Test("GetFloat", func(assert qunit.QUnitAssert) { defer reset() // Create a form with some inputs and values. All the input types here // should be convertible to floats via GetFloat. container.SetInnerHTML(`<form> <input name="default" value="23.0" > <input type="text" name="text" value="789.6" > <input type="number" name="number" value="123456789.7" > </form>`) formEl := container.QuerySelector("form") form, err := form.Parse(formEl) assertNoError(assert, err, "") expectedValues := map[string]float64{ "default": 23.0, "text": 789.6, "number": 123456789.7, } // Check that the parsed value for each input is correct. for name, expectedValue := range expectedValues { got, err := form.GetFloat(name) assertNoError(assert, err, "") assert.Equal(got, expectedValue, "Incorrect value for field: "+name) } }) qunit.Test("GetBool", func(assert qunit.QUnitAssert) { defer reset() // Create a form with some inputs and values. All the input types here // should be convertible to booleans via GetBool. container.SetInnerHTML(`<form> <input name="default" value="true" > <input type="text" name="text" value="true" > <input type="checkbox" name="checkbox" checked > <input type="radio" name="radio" checked > <input type="checkbox" name="checkbox-false" > <input type="radio" name="radio-false" > </form>`) formEl := container.QuerySelector("form") form, err := form.Parse(formEl) assertNoError(assert, err, "") expectedValues := map[string]bool{ "default": true, "text": true, "checkbox": true, "radio": true, "checkbox-false": false, "radio-false": false, } // Check that the parsed value for each input is correct. for name, expectedValue := range expectedValues { got, err := form.GetBool(name) assertNoError(assert, err, "") assert.Equal(got, expectedValue, "Incorrect value for field: "+name) } }) qunit.Test("GetTime", func(assert qunit.QUnitAssert) { defer reset() // Create a form with some inputs and values. All the input types here // should be convertible to time.Time via GetTime. container.SetInnerHTML(`<form> <input name="date" type="date" value="1992-09-29" > <input name="datetime" type="datetime" value="1985-12-03T23:59:34-08:00" > <input name="datetime-local" type="datetime-local" value="1985-04-12T23:20:50.52" > </form>`) formEl := container.QuerySelector("form") form, err := form.Parse(formEl) assertNoError(assert, err, "") rfc3339Date := "2006-01-02" rfc3339DatetimeLocal := "2006-01-02T15:04:05.999999999" expectedValues := map[string]time.Time{ "date": mustParseTime(rfc3339Date, "1992-09-29"), "datetime": mustParseTime(time.RFC3339, "1985-12-03T23:59:34-08:00"), "datetime-local": mustParseTime(rfc3339DatetimeLocal, "1985-04-12T23:20:50.52"), } // Check that the parsed value for each input is correct. for name, expectedValue := range expectedValues { got, err := form.GetTime(name) assertNoError(assert, err, "Error for field: "+name) assert.DeepEqual(got, expectedValue, "Incorrect value for field: "+name) } }) qunit.Test("ValidateRequired", func(assert qunit.QUnitAssert) { defer reset() // Create a form with some inputs and values. container.SetInnerHTML(`<form> <input name="non-empty" value="foo" > <input name="empty" value="" > </form>`) formEl := container.QuerySelector("form") form, err := form.Parse(formEl) assertNoError(assert, err, "") // Check that a non-empty input does not add a validation error. form.Validate("non-empty").Required() assert.Equal(form.HasErrors(), false, "Expected form to have no errors") // Check that an empty input does add a validation error with a custom // message. customMessage := "empty cannot be blank." form.Validate("empty").Requiredf(customMessage) assert.Equal(len(form.Errors), 1, "Expected form to have 1 error because 'empty' is required.") assert.Equal(form.Errors[0].Error(), customMessage, "Custom message was not set with Requiredf") // Check that a non-existing input does add a validation error. form.Validate("non-existing").Required() assert.Equal(len(form.Errors), 2, "Expected form to have 2 errorss because 'non-existing' and 'empty' are required.") }) qunit.Test("ValidateLess", func(assert qunit.QUnitAssert) { defer reset() // Create a form with some inputs and values. container.SetInnerHTML(`<form> <input name="valid" value="5" > <input name="invalid" value="10" > <input name="non-integer" value="foo" > </form>`) formEl := container.QuerySelector("form") form, err := form.Parse(formEl) assertNoError(assert, err, "") // Check that a valid input does not add any validation errors. form.Validate("valid").Less(10) assert.Equal(form.HasErrors(), false, "Expected form to have no errors") // Check that a non-existing input does not add any validation errors. form.Validate("non-existing").Less(10) assert.Equal(form.HasErrors(), false, "Expected form to have no errors") // Check that an invalid input does add a validation error with a custom // message. customMessage := "invalid input was invalid becase it was not less than 10." form.Validate("invalid").Lessf(10, customMessage) assert.Equal(len(form.Errors), 1, "Expected form to have 1 error because 'invalid' is not less than 10.") assert.Equal(form.Errors[0].Error(), customMessage, "Custom message was not set with Lessf") // Check that a input which is not an integer adds the correct error // message. form.Validate("non-integer").Less(10) assert.Equal(len(form.Errors), 2, "Expected form to have 2 errors because 'non-integer' is not an integer.") assert.Equal(form.Errors[1].Error(), "non-integer must be an integer.", "Error was not added when input was a non-integer.") }) qunit.Test("ValidateLessOrEqual", func(assert qunit.QUnitAssert) { defer reset() // Create a form with some inputs and values. container.SetInnerHTML(`<form> <input name="valid" value="5" > <input name="invalid" value="11" > <input name="non-integer" value="foo" > </form>`) formEl := container.QuerySelector("form") form, err := form.Parse(formEl) assertNoError(assert, err, "") // Check that a valid input does not add any validation errors. form.Validate("valid").LessOrEqual(10) assert.Equal(form.HasErrors(), false, "Expected form to have no errors") // Check that a non-existing input does not add any validation errors. form.Validate("non-existing").LessOrEqual(10) assert.Equal(form.HasErrors(), false, "Expected form to have no errors") // Check that an invalid input does add a validation error with a custom // message. customMessage := "invalid input was invalid becase it was not less than or equal to 10." form.Validate("invalid").LessOrEqualf(10, customMessage) assert.Equal(len(form.Errors), 1, "Expected form to have 1 error because 'invalid' is not less than or equal to 10.") assert.Equal(form.Errors[0].Error(), customMessage, "Custom message was not set with LessOrEqualf") // Check that a input which is not an integer adds the correct error // message. form.Validate("non-integer").LessOrEqual(10) assert.Equal(len(form.Errors), 2, "Expected form to have 2 errors because 'non-integer' is not an integer.") assert.Equal(form.Errors[1].Error(), "non-integer must be an integer.", "Error was not added when input was a non-integer.") }) qunit.Test("ValidateGreater", func(assert qunit.QUnitAssert) { defer reset() // Create a form with some inputs and values. container.SetInnerHTML(`<form> <input name="valid" value="15" > <input name="invalid" value="10" > <input name="non-integer" value="foo" > </form>`) formEl := container.QuerySelector("form") form, err := form.Parse(formEl) assertNoError(assert, err, "") // Check that a valid input does not add any validation errors. form.Validate("valid").Greater(10) assert.Equal(form.HasErrors(), false, "Expected form to have no errors") // Check that a non-existing input does not add any validation errors. form.Validate("non-existing").Greater(10) assert.Equal(form.HasErrors(), false, "Expected form to have no errors") // Check that an invalid input does add a validation error with a custom // message. customMessage := "invalid input was invalid becase it was not greater than 10." form.Validate("invalid").Greaterf(10, customMessage) assert.Equal(len(form.Errors), 1, "Expected form to have 1 error because 'invalid' is not greater than 10.") assert.Equal(form.Errors[0].Error(), customMessage, "Custom message was not set with Greaterf") // Check that a input which is not an integer adds the correct error // message. form.Validate("non-integer").Greater(10) assert.Equal(len(form.Errors), 2, "Expected form to have 2 errors because 'non-integer' is not an integer.") assert.Equal(form.Errors[1].Error(), "non-integer must be an integer.", "Error was not added when input was a non-integer.") }) qunit.Test("ValidateGreaterOrEqual", func(assert qunit.QUnitAssert) { defer reset() // Create a form with some inputs and values. container.SetInnerHTML(`<form> <input name="valid" value="15" > <input name="invalid" value="9" > <input name="non-integer" value="foo" > </form>`) formEl := container.QuerySelector("form") form, err := form.Parse(formEl) assertNoError(assert, err, "") // Check that a valid input does not add any validation errors. form.Validate("valid").GreaterOrEqual(10) assert.Equal(form.HasErrors(), false, "Expected form to have no errors") // Check that a non-existing input does not add any validation errors. form.Validate("non-existing").GreaterOrEqual(10) assert.Equal(form.HasErrors(), false, "Expected form to have no errors") // Check that an invalid input does add a validation error with a custom // message. customMessage := "invalid input was invalid becase it was not greater than or equal to 10." form.Validate("invalid").GreaterOrEqualf(10, customMessage) assert.Equal(len(form.Errors), 1, "Expected form to have 1 error because 'invalid' is not greater than or equal to 10.") assert.Equal(form.Errors[0].Error(), customMessage, "Custom message was not set with GreaterOrEqualf") // Check that a input which is not an integer adds the correct error // message. form.Validate("non-integer").GreaterOrEqual(10) assert.Equal(len(form.Errors), 2, "Expected form to have 2 errors because 'non-integer' is not an integer.") assert.Equal(form.Errors[1].Error(), "non-integer must be an integer.", "Error was not added when input was a non-integer.") }) qunit.Test("ValidateIsInt", func(assert qunit.QUnitAssert) { defer reset() // Create a form with some inputs and values. container.SetInnerHTML(`<form> <input name="valid" value="5" > <input name="invalid" value="foo" > </form>`) formEl := container.QuerySelector("form") form, err := form.Parse(formEl) assertNoError(assert, err, "") // Check that a valid input does not add any validation errors. form.Validate("valid").IsInt() assert.Equal(form.HasErrors(), false, "Expected form to have no errors") // Check that a non-existing input does not add any validation errors. form.Validate("non-existing").IsInt() assert.Equal(form.HasErrors(), false, "Expected form to have no errors") // Check that an invalid input does add a validation error with a custom // message. customMessage := "invalid input was invalid becase it not an integer." form.Validate("invalid").IsIntf(customMessage) assert.Equal(len(form.Errors), 1, "Expected form to have 1 error because 'invalid' is not an integer.") assert.Equal(form.Errors[0].Error(), customMessage, "Custom message was not set with IsIntf") }) qunit.Test("ValidateLessFloat", func(assert qunit.QUnitAssert) { defer reset() // Create a form with some inputs and values. container.SetInnerHTML(`<form> <input name="valid" value="5.4" > <input name="invalid" value="10.0" > <input name="non-float" value="foo" > </form>`) formEl := container.QuerySelector("form") form, err := form.Parse(formEl) assertNoError(assert, err, "") // Check that a valid input does not add any validation errors. form.Validate("valid").LessFloat(10.0) assert.Equal(form.HasErrors(), false, "Expected form to have no errors") // Check that a non-existing input does not add any validation errors. form.Validate("non-existing").LessFloat(10.0) assert.Equal(form.HasErrors(), false, "Expected form to have no errors") // Check that an invalid input does add a validation error with a custom // message. customMessage := "invalid input was invalid becase it was not less than 10.0." form.Validate("invalid").LessFloatf(10.0, customMessage) assert.Equal(len(form.Errors), 1, "Expected form to have 1 error because 'invalid' is not less than 10.0.") assert.Equal(form.Errors[0].Error(), customMessage, "Custom message was not set with LessFloatf") // Check that a input which is not a float adds the correct error // message. form.Validate("non-float").LessFloat(10.0) assert.Equal(len(form.Errors), 2, "Expected form to have 2 errors because 'non-float' is not a number.") assert.Equal(form.Errors[1].Error(), "non-float must be a number.", "Error was not added when input was a non-float.") }) qunit.Test("ValidateLessOrEqualFloat", func(assert qunit.QUnitAssert) { defer reset() // Create a form with some inputs and values. container.SetInnerHTML(`<form> <input name="valid" value="5.4" > <input name="invalid" value="10.1" > <input name="non-float" value="foo" > </form>`) formEl := container.QuerySelector("form") form, err := form.Parse(formEl) assertNoError(assert, err, "") // Check that a valid input does not add any validation errors. form.Validate("valid").LessOrEqualFloat(10.0) assert.Equal(form.HasErrors(), false, "Expected form to have no errors") // Check that a non-existing input does not add any validation errors. form.Validate("non-existing").LessOrEqualFloat(10.0) assert.Equal(form.HasErrors(), false, "Expected form to have no errors") // Check that an invalid input does add a validation error with a custom // message. customMessage := "invalid input was invalid becase it was not less than or equal to 10.0." form.Validate("invalid").LessOrEqualFloatf(10.0, customMessage) assert.Equal(len(form.Errors), 1, "Expected form to have 1 error because 'invalid' is not less than or equal to 10.0.") assert.Equal(form.Errors[0].Error(), customMessage, "Custom message was not set with LessOrEqualFloatf") // Check that a input which is not a float adds the correct error // message. form.Validate("non-float").LessOrEqualFloat(10.0) assert.Equal(len(form.Errors), 2, "Expected form to have 2 errors because 'non-float' is not a number.") assert.Equal(form.Errors[1].Error(), "non-float must be a number.", "Error was not added when input was a non-float.") }) qunit.Test("ValidateGreaterFloat", func(assert qunit.QUnitAssert) { defer reset() // Create a form with some inputs and values. container.SetInnerHTML(`<form> <input name="valid" value="15.7" > <input name="invalid" value="10.0" > <input name="non-float" value="foo" > </form>`) formEl := container.QuerySelector("form") form, err := form.Parse(formEl) assertNoError(assert, err, "") // Check that a valid input does not add any validation errors. form.Validate("valid").GreaterFloat(10.0) assert.Equal(form.HasErrors(), false, "Expected form to have no errors") // Check that a non-existing input does not add any validation errors. form.Validate("non-existing").GreaterFloat(10.0) assert.Equal(form.HasErrors(), false, "Expected form to have no errors") // Check that an invalid input does add a validation error with a custom // message. customMessage := "invalid input was invalid becase it was not greater than 10.0." form.Validate("invalid").GreaterFloatf(10.0, customMessage) assert.Equal(len(form.Errors), 1, "Expected form to have 1 error because 'invalid' is not greater than 10.0.") assert.Equal(form.Errors[0].Error(), customMessage, "Custom message was not set with GreaterFloatf") // Check that a input which is not a float adds the correct error // message. form.Validate("non-float").GreaterFloat(10.0) assert.Equal(len(form.Errors), 2, "Expected form to have 2 errors because 'non-float' is not a number.") assert.Equal(form.Errors[1].Error(), "non-float must be a number.", "Error was not added when input was a non-float.") }) qunit.Test("ValidateGreaterOrEqualFloat", func(assert qunit.QUnitAssert) { defer reset() // Create a form with some inputs and values. container.SetInnerHTML(`<form> <input name="valid" value="15.7" > <input name="invalid" value="9.9" > <input name="non-float" value="foo" > </form>`) formEl := container.QuerySelector("form") form, err := form.Parse(formEl) assertNoError(assert, err, "") // Check that a valid input does not add any validation errors. form.Validate("valid").GreaterOrEqualFloat(10.0) assert.Equal(form.HasErrors(), false, "Expected form to have no errors") // Check that a non-existing input does not add any validation errors. form.Validate("non-existing").GreaterOrEqualFloat(10.0) assert.Equal(form.HasErrors(), false, "Expected form to have no errors") // Check that an invalid input does add a validation error with a custom // message. customMessage := "invalid input was invalid becase it was not greater than or equal to 10.0." form.Validate("invalid").GreaterOrEqualFloatf(10.0, customMessage) assert.Equal(len(form.Errors), 1, "Expected form to have 1 error because 'invalid' is not greater than or equal to 10.0.") assert.Equal(form.Errors[0].Error(), customMessage, "Custom message was not set with GreaterOrEqualFloatf") // Check that a input which is not a float adds the correct error // message. form.Validate("non-float").GreaterOrEqualFloat(10.0) assert.Equal(len(form.Errors), 2, "Expected form to have 2 errors because 'non-float' is not a number.") assert.Equal(form.Errors[1].Error(), "non-float must be a number.", "Error was not added when input was a non-float.") }) qunit.Test("ValidateIsFloat", func(assert qunit.QUnitAssert) { defer reset() // Create a form with some inputs and values. container.SetInnerHTML(`<form> <input name="valid" value="5.3" > <input name="invalid" value="foo" > </form>`) formEl := container.QuerySelector("form") form, err := form.Parse(formEl) assertNoError(assert, err, "") // Check that a valid input does not add any validation errors. form.Validate("valid").IsFloat() assert.Equal(form.HasErrors(), false, "Expected form to have no errors") // Check that a non-existing input does not add any validation errors. form.Validate("non-existing").IsFloat() assert.Equal(form.HasErrors(), false, "Expected form to have no errors") // Check that an invalid input does add a validation error with a custom // message. customMessage := "invalid input was invalid becase it not a float." form.Validate("invalid").IsFloatf(customMessage) assert.Equal(len(form.Errors), 1, "Expected form to have 1 error because 'invalid' is not a float.") assert.Equal(form.Errors[0].Error(), customMessage, "Custom message was not set with IsFloatf") }) qunit.Test("ValidateIsBool", func(assert qunit.QUnitAssert) { defer reset() // Create a form with some inputs and values. container.SetInnerHTML(`<form> <input name="valid" value="true" > <input type="checkbox" name="checkbox" checked > <input name="invalid" value="foo" > </form>`) formEl := container.QuerySelector("form") form, err := form.Parse(formEl) assertNoError(assert, err, "") // Check that a valid input does not add any validation errors. form.Validate("valid").IsBool() assert.Equal(form.HasErrors(), false, "Expected form to have no errors") // Check that the checkbox input does not add any validation errors. form.Validate("checkbox").IsBool() assert.Equal(form.HasErrors(), false, "Expected form to have no errors") // Check that a non-existing input does not add any validation errors. form.Validate("non-existing").IsBool() assert.Equal(form.HasErrors(), false, "Expected form to have no errors") // Check that an invalid input does add a validation error with a custom // message. customMessage := "invalid input was invalid becase it not a boolean." form.Validate("invalid").IsBoolf(customMessage) assert.Equal(len(form.Errors), 1, "Expected form to have 1 error because 'invalid' is not a boolean.") assert.Equal(form.Errors[0].Error(), customMessage, "Custom message was not set with IsBoolf") }) qunit.Test("Bind", func(assert qunit.QUnitAssert) { defer reset() // Create a form with some inputs and values. container.SetInnerHTML(`<form> <input name="string" value="foo" > <input name="bytes" value="bar" > <input type="number" name="int" value="4" > <input type="number" name="int8" value="8" > <input type="number" name="int16" value="15" > <input type="number" name="int32" value="16" > <input type="number" name="int64" value="23" > <input type="number" name="uint" value="42" > <input type="number" name="uint8" value="1" > <input type="number" name="uint16" value="2" > <input type="number" name="uint32" value="3" > <input type="number" name="uint64" value="4" > <input type="number" name="float32" value="39.7" > <input type="number" name="float64" value="12.6" > <input type="checkbox" name="bool" checked > <input type="datetime" name="time" value="1985-12-03T23:59:34-08:00" > </form>`) formEl := container.QuerySelector("form") form, err := form.Parse(formEl) assertNoError(assert, err, "") // Bind the form to some target and check the results. target := struct { String string Bytes []byte Int int Int8 int8 Int16 int16 Int32 int32 Int64 int64 Uint uint Uint8 uint8 Uint16 uint16 Uint32 uint32 Uint64 uint64 Float32 float32 Float64 float64 Bool bool Time time.Time }{} err = form.Bind(&target) assertNoError(assert, err, "") assert.Equal(target.String, "foo", "target.String was not correct.") assert.DeepEqual(target.Bytes, []byte("bar"), "target.Bytes was not correct.") assert.Equal(target.Int, 4, "target.Int was not correct.") assert.Equal(target.Int8, 8, "target.Int8 was not correct.") assert.Equal(target.Int16, 15, "target.Int16 was not correct.") assert.Equal(target.Int32, 16, "target.Int32 was not correct.") assert.Equal(target.Int64, 23, "target.Int64 was not correct.") assert.Equal(target.Uint, 42, "target.Uint was not correct.") assert.Equal(target.Uint8, 1, "target.Uint8 was not correct.") assert.Equal(target.Uint16, 2, "target.Uint16 was not correct.") assert.Equal(target.Uint32, 3, "target.Uint32 was not correct.") assert.Equal(target.Uint64, 4, "target.Uint64 was not correct.") assert.Equal(target.Bool, true, "target.Bool was not correct.") assert.DeepEqual(target.Time, mustParseTime(time.RFC3339, "1985-12-03T23:59:34-08:00"), "target.Time was not correct.") }) qunit.Test("BindWithPointers", func(assert qunit.QUnitAssert) { defer reset() // Create a form with some inputs and values. container.SetInnerHTML(`<form> <input name="string" value="foo" > <input name="bytes" value="bar" > <input type="number" name="int" value="4" > <input type="number" name="int8" value="8" > <input type="number" name="int16" value="15" > <input type="number" name="int32" value="16" > <input type="number" name="int64" value="23" > <input type="number" name="uint" value="42" > <input type="number" name="uint8" value="1" > <input type="number" name="uint16" value="2" > <input type="number" name="uint32" value="3" > <input type="number" name="uint64" value="4" > <input type="number" name="float32" value="39.7" > <input type="number" name="float64" value="12.6" > <input type="checkbox" name="bool" checked > <input type="datetime" name="time" value="1985-12-03T23:59:34-08:00" > </form>`) formEl := container.QuerySelector("form") form, err := form.Parse(formEl) assertNoError(assert, err, "") // Bind the form to some target and check the results. target := struct { String *string Bytes *[]byte Int *int Int8 *int8 Int16 *int16 Int32 *int32 Int64 *int64 Uint *uint Uint8 *uint8 Uint16 *uint16 Uint32 *uint32 Uint64 *uint64 Float32 *float32 Float64 *float64 Bool *bool Time *time.Time }{} err = form.Bind(&target) assertNoError(assert, err, "") assert.Equal(*target.String, "foo", "target.String was not correct.") assert.DeepEqual(*target.Bytes, []byte("bar"), "target.Bytes was not correct.") assert.Equal(*target.Int, 4, "target.Int was not correct.") assert.Equal(*target.Int8, 8, "target.Int8 was not correct.") assert.Equal(*target.Int16, 15, "target.Int16 was not correct.") assert.Equal(*target.Int32, 16, "target.Int32 was not correct.") assert.Equal(*target.Int64, 23, "target.Int64 was not correct.") assert.Equal(*target.Uint, 42, "target.Uint was not correct.") assert.Equal(*target.Uint8, 1, "target.Uint8 was not correct.") assert.Equal(*target.Uint16, 2, "target.Uint16 was not correct.") assert.Equal(*target.Uint32, 3, "target.Uint32 was not correct.") assert.Equal(*target.Uint64, 4, "target.Uint64 was not correct.") assert.Equal(*target.Bool, true, "target.Bool was not correct.") assert.DeepEqual(*target.Time, mustParseTime(time.RFC3339, "1985-12-03T23:59:34-08:00"), "target.Time was not correct.") }) qunit.Test("Binder", func(assert qunit.QUnitAssert) { defer reset() // Create a form with some inputs and values. container.SetInnerHTML(`<form> <input name="string" value="foo" > <input name="int" type="number" value="42" > </form>`) formEl := container.QuerySelector("form") form, err := form.Parse(formEl) assertNoError(assert, err, "") // Bind the form to our CustomBinder type and check the results. binder := &CustomBinder{} err = form.Bind(binder) assertNoError(assert, err, "") assert.Equal(binder.String, "_foo", "binder.String was not correct.") assert.Equal(binder.Int, 43, "binder.Int was not correct.") }) qunit.Test("InputBinder", func(assert qunit.QUnitAssert) { defer reset() // Create a form with some inputs and values. container.SetInnerHTML(`<form> <input name="name" value="Foo Bar" > </form>`) formEl := container.QuerySelector("form") form, err := form.Parse(formEl) assertNoError(assert, err, "") // Bind the form to our CustomInputBinder type and check the results. binder := &CustomInputBinder{} err = form.Bind(binder) assertNoError(assert, err, "") assert.Equal(binder.Name.First, "Foo", "binder.Name.First was not correct.") assert.Equal(binder.Name.Last, "Bar", "binder.Name.Last was not correct.") }) }
func main() { QUnit.Module("Core") QUnit.Test("jQuery Properties", func(assert QUnit.QUnitAssert) { assert.Equal(jQuery().Jquery, "2.1.1", "JQuery Version") assert.Equal(jQuery().Length, 0, "jQuery().Length") jQ2 := jQuery("body") assert.Equal(jQ2.Selector, "body", `jQ2 := jQuery("body"); jQ2.Selector.Selector`) assert.Equal(jQuery("body").Selector, "body", `jQuery("body").Selector`) }) //start dom tests QUnit.Test("Test Setup", func(assert QUnit.QUnitAssert) { test := jQuery(getDocumentBody()).Find(FIX) assert.Equal(test.Selector, FIX, "#qunit-fixture find Selector") assert.Equal(test.Context, getDocumentBody(), "#qunit-fixture find Context") }) QUnit.Test("Static Functions", func(assert QUnit.QUnitAssert) { jquery.GlobalEval("var globalEvalTest = 2;") assert.Equal(js.Global.Get("globalEvalTest").Int(), 2, "GlobalEval: Test variable declarations are global") assert.Equal(jquery.Trim(" GopherJS "), "GopherJS", "Trim: leading and trailing space") assert.Equal(jquery.Type(true), "boolean", "Type: Boolean") assert.Equal(jquery.Type(time.Now()), "date", "Type: Date") assert.Equal(jquery.Type("GopherJS"), "string", "Type: String") assert.Equal(jquery.Type(12.21), "number", "Type: Number") assert.Equal(jquery.Type(nil), "null", "Type: Null") assert.Equal(jquery.Type([2]string{"go", "lang"}), "array", "Type: Array") assert.Equal(jquery.Type([]string{"go", "lang"}), "array", "Type: Array") o := map[string]interface{}{"a": true, "b": 1.1, "c": "more"} assert.Equal(jquery.Type(o), "object", "Type: Object") assert.Equal(jquery.Type(getDocumentBody), "function", "Type: Function") assert.Ok(!jquery.IsPlainObject(""), "IsPlainObject: string") assert.Ok(jquery.IsPlainObject(o), "IsPlainObject: Object") assert.Ok(!jquery.IsEmptyObject(o), "IsEmptyObject: Object") assert.Ok(jquery.IsEmptyObject(map[string]interface{}{}), "IsEmptyObject: Object") assert.Ok(!jquery.IsFunction(""), "IsFunction: string") assert.Ok(jquery.IsFunction(getDocumentBody), "IsFunction: getDocumentBody") assert.Ok(!jquery.IsNumeric("a3a"), "IsNumeric: string") assert.Ok(jquery.IsNumeric("0xFFF"), "IsNumeric: hex") assert.Ok(jquery.IsNumeric("8e-2"), "IsNumeric: exponential") assert.Ok(!jquery.IsXMLDoc(getDocumentBody), "HTML Body element") assert.Ok(jquery.IsWindow(js.Global), "window") }) QUnit.Test("ToArray,InArray", func(assert QUnit.QUnitAssert) { jQuery(`<div>a</div> <div>b</div> <div>c</div>`).AppendTo(FIX) divs := jQuery(FIX).Find("div") assert.Equal(divs.Length, 3, "3 divs in Fixture inserted") str := "" for _, v := range divs.ToArray() { str += jQuery(v).Text() } assert.Equal(str, "abc", "ToArray() allows range over selection") arr := []interface{}{"a", 3, true, 2.2, "GopherJS"} assert.Equal(jquery.InArray(4, arr), -1, "InArray") assert.Equal(jquery.InArray(3, arr), 1, "InArray") assert.Equal(jquery.InArray("a", arr), 0, "InArray") assert.Equal(jquery.InArray("b", arr), -1, "InArray") assert.Equal(jquery.InArray("GopherJS", arr), 4, "InArray") }) QUnit.Test("ParseHTML, ParseXML, ParseJSON", func(assert QUnit.QUnitAssert) { str := `<ul> <li class="firstclass">list item 1</li> <li>list item 2</li> <li>list item 3</li> <li>list item 4</li> <li class="lastclass">list item 5</li> </ul>` arr := jquery.ParseHTML(str) jQuery(arr).AppendTo(FIX) assert.Equal(jQuery(FIX).Find("ul li").Length, 5, "ParseHTML") xml := "<rss version='2.0'><channel><title>RSS Title</title></channel></rss>" xmlDoc := jquery.ParseXML(xml) assert.Equal(jQuery(xmlDoc).Find("title").Text(), "RSS Title", "ParseXML") obj := jquery.ParseJSON(`{ "language": "go" }`) language := obj.(map[string]interface{})["language"].(string) assert.Equal(language, "go", "ParseJSON") }) QUnit.Test("Grep", func(assert QUnit.QUnitAssert) { arr := []interface{}{1, 9, 3, 8, 6, 1, 5, 9, 4, 7, 3, 8, 6, 9, 1} arr2 := jquery.Grep(arr, func(n interface{}, idx int) bool { return n.(float64) != float64(5) && idx > 4 }) assert.Equal(len(arr2), 9, "Grep") }) QUnit.Test("Noop,Now", func(assert QUnit.QUnitAssert) { callSth := func(fn func() interface{}) interface{} { return fn() } _ = callSth(jquery.Noop) _ = jquery.Noop() assert.Ok(jquery.IsFunction(jquery.Noop), "jquery.Noop") date := js.Global.Get("Date").New() time := date.Call("getTime").Float() assert.Ok(time <= jquery.Now(), "jquery.Now()") }) QUnit.Module("Dom") QUnit.Test("AddClass,Clone,Add,AppendTo,Find", func(assert QUnit.QUnitAssert) { jQuery("p").AddClass("wow").Clone().Add("<span id='dom02'>WhatADay</span>").AppendTo(FIX) txt := jQuery(FIX).Find("span#dom02").Text() assert.Equal(txt, "WhatADay", "Test of Clone, Add, AppendTo, Find, Text Functions") jQuery(FIX).Empty() html := ` <div>This div should be white</div> <div class="red">This div will be green because it now has the "green" and "red" classes. It would be red if the addClass function failed.</div> <div>This div should be white</div> <p>There are zero green divs</p> <button>some btn</button>` jQuery(html).AppendTo(FIX) jQuery(FIX).Find("div").AddClass(func(index int, currentClass string) string { addedClass := "" if currentClass == "red" { addedClass = "green" jQuery("p").SetText("There is one green div") } return addedClass }) jQuery(FIX).Find("button").AddClass("red") assert.Ok(jQuery(FIX).Find("button").HasClass("red"), "button hasClass red") assert.Ok(jQuery(FIX).Find("p").Text() == "There is one green div", "There is one green div") assert.Ok(jQuery(FIX).Find("div:eq(1)").HasClass("green"), "one div hasClass green") jQuery(FIX).Empty() }) QUnit.Test("Children,Append", func(assert QUnit.QUnitAssert) { var j = jQuery(`<div class="pipe animated"><div class="pipe_upper" style="height: 79px;"></div><div class="guess top" style="top: 114px;"></div><div class="pipe_middle" style="height: 100px; top: 179px;"></div><div class="guess bottom" style="bottom: 76px;"></div><div class="pipe_lower" style="height: 41px;"></div><div class="question"></div></div>`) assert.Ok(len(j.Html()) == 301, "jQuery html len") j.Children(".question").Append(jQuery(`<div class = "question_digit first" style = "background-image: url('assets/font_big_3.png');"></div>`)) assert.Ok(len(j.Html()) == 397, "jquery html len after 1st jquery object append") j.Children(".question").Append(jQuery(`<div class = "question_digit symbol" style="background-image: url('assets/font_shitty_x.png');"></div>`)) assert.Ok(len(j.Html()) == 497, "jquery htm len after 2nd jquery object append") j.Children(".question").Append(`<div class = "question_digit second" style = "background-image: url('assets/font_big_1.png');"></div>`) assert.Ok(len(j.Html()) == 594, "jquery html len after html append") }) QUnit.Test("ApiOnly:ScollFn,SetCss,CssArray,FadeOut", func(assert QUnit.QUnitAssert) { //QUnit.Expect(0) for i := 0; i < 3; i++ { jQuery("p").Clone().AppendTo(FIX) } jQuery(FIX).Scroll(func(e jquery.Event) { jQuery("span").SetCss("display", "inline").FadeOut("slow") }) htmlsnippet := `<style> div { height: 50px; margin: 5px; padding: 5px; float: left; } #box1 { width: 50px; color: yellow; background-color: blue; } #box2 { width: 80px; color: rgb(255, 255, 255); background-color: rgb(15, 99, 30); } #box3 { width: 40px; color: #fcc; background-color: #123456; } #box4 { width: 70px; background-color: #f11; } </style> <p id="result"> </p> <div id="box1">1</div> <div id="box2">2</div> <div id="box3">3</div> <div id="box4">4</div>` jQuery(htmlsnippet).AppendTo(FIX) jQuery(FIX).Find("div").On("click", func(evt jquery.Event) { html := []string{"The clicked div has the following styles:"} var styleProps = jQuery(evt.Target).CssArray("width", "height") for prop, value := range styleProps { html = append(html, prop+": "+value.(string)) } jQuery(FIX).Find("#result").SetHtml(strings.Join(html, "<br>")) }) jQuery(FIX).Find("div:eq(0)").Trigger("click") assert.Ok(jQuery(FIX).Find("#result").Html() == "The clicked div has the following styles:<br>width: 50px<br>height: 50px", "CssArray read properties") }) QUnit.Test("ApiOnly:SelectFn,SetText,Show,FadeOut", func(assert QUnit.QUnitAssert) { QUnit.Expect(0) jQuery(`<p>Click and drag the mouse to select text in the inputs.</p> <input type="text" value="Some text"> <input type="text" value="to test on"> <div></div>`).AppendTo(FIX) jQuery(":input").Select(func(e jquery.Event) { jQuery("div").SetText("Something was selected").Show().FadeOut("1000") }) }) QUnit.Test("Eq,Find", func(assert QUnit.QUnitAssert) { jQuery(`<div></div> <div></div> <div class="test"></div> <div></div> <div></div> <div></div>`).AppendTo(FIX) assert.Ok(jQuery(FIX).Find("div").Eq(2).HasClass("test"), "Eq(2) has class test") assert.Ok(!jQuery(FIX).Find("div").Eq(0).HasClass("test"), "Eq(0) has no class test") }) QUnit.Test("Find,End", func(assert QUnit.QUnitAssert) { jQuery(`<p class='ok'><span class='notok'>Hello</span>, how are you?</p>`).AppendTo(FIX) assert.Ok(jQuery(FIX).Find("p").Find("span").HasClass("notok"), "before call to end") assert.Ok(jQuery(FIX).Find("p").Find("span").End().HasClass("ok"), "after call to end") }) QUnit.Test("Slice,Attr,First,Last", func(assert QUnit.QUnitAssert) { jQuery(`<ul> <li class="firstclass">list item 1</li> <li>list item 2</li> <li>list item 3</li> <li>list item 4</li> <li class="lastclass">list item 5</li> </ul>`).AppendTo(FIX) assert.Equal(jQuery(FIX).Find("li").Slice(2).Length, 3, "Slice") assert.Equal(jQuery(FIX).Find("li").Slice(2, 4).Length, 2, "SliceByEnd") assert.Equal(jQuery(FIX).Find("li").First().Attr("class"), "firstclass", "First") assert.Equal(jQuery(FIX).Find("li").Last().Attr("class"), "lastclass", "Last") }) QUnit.Test("Css", func(assert QUnit.QUnitAssert) { jQuery(FIX).SetCss(map[string]interface{}{"color": "red", "background": "blue", "width": "20px", "height": "10px"}) assert.Ok(jQuery(FIX).Css("width") == "20px" && jQuery(FIX).Css("height") == "10px", "SetCssMap") div := jQuery("<div style='display: inline'/>").Show().AppendTo(FIX) assert.Equal(div.Css("display"), "inline", "Make sure that element has same display when it was created.") div.Remove() span := jQuery("<span/>").Hide().Show() assert.Equal(span.Get(0).Get("style").Get("display"), "inline", "For detached span elements, display should always be inline") span.Remove() }) QUnit.Test("Attributes", func(assert QUnit.QUnitAssert) { jQuery("<form id='testForm'></form>").AppendTo(FIX) extras := jQuery("<input id='id' name='id' /><input id='name' name='name' /><input id='target' name='target' />").AppendTo("#testForm") assert.Equal(jQuery("#testForm").Attr("target"), "", "Attr") assert.Equal(jQuery("#testForm").SetAttr("target", "newTarget").Attr("target"), "newTarget", "SetAttr2") assert.Equal(jQuery("#testForm").RemoveAttr("id").Attr("id"), "", "RemoveAttr ") assert.Equal(jQuery("#testForm").Attr("name"), "", "Attr undefined") extras.Remove() jQuery("<a/>").SetAttr(map[string]interface{}{"id": "tAnchor5", "href": "#5"}).AppendTo(FIX) assert.Equal(jQuery("#tAnchor5").Attr("href"), "#5", "Attr") jQuery("<a id='tAnchor6' href='#5' />").AppendTo(FIX) assert.Equal(jQuery("#tAnchor5").Prop("href"), jQuery("#tAnchor6").Prop("href"), "Prop") input := jQuery("<input name='tester' />") assert.StrictEqual(input.Clone(true).SetAttr("name", "test").Underlying().Index(0).Get("name"), "test", "Clone") jQuery(FIX).Empty() jQuery(`<input type="checkbox" checked="checked"> <input type="checkbox"> <input type="checkbox"> <input type="checkbox" checked="checked">`).AppendTo(FIX) jQuery(FIX).Find("input[type='checkbox']").SetProp("disabled", true) assert.Ok(jQuery(FIX).Find("input[type='checkbox']").Prop("disabled"), "SetProp") }) QUnit.Test("Unique", func(assert QUnit.QUnitAssert) { jQuery(`<div>There are 6 divs in this document.</div> <div></div> <div class="dup"></div> <div class="dup"></div> <div class="dup"></div> <div></div>`).AppendTo(FIX) divs := jQuery(FIX).Find("div").Get() assert.Equal(divs.Get("length"), 6, "6 divs inserted") jQuery(FIX).Find(".dup").Clone(true).AppendTo(FIX) divs2 := jQuery(FIX).Find("div").Get() assert.Equal(divs2.Get("length"), 9, "9 divs inserted") divs3 := jquery.Unique(divs) assert.Equal(divs3.Get("length"), 6, "post-qunique should be 6 elements") }) QUnit.Test("Serialize,SerializeArray,Trigger,Submit", func(assert QUnit.QUnitAssert) { QUnit.Expect(2) jQuery(`<form> <div><input type="text" name="a" value="1" id="a"></div> <div><input type="text" name="b" value="2" id="b"></div> <div><input type="hidden" name="c" value="3" id="c"></div> <div> <textarea name="d" rows="8" cols="40">4</textarea> </div> <div><select name="e"> <option value="5" selected="selected">5</option> <option value="6">6</option> <option value="7">7</option> </select></div> <div> <input type="checkbox" name="f" value="8" id="f"> </div> <div> <input type="submit" name="g" value="Submit" id="g"> </div> </form>`).AppendTo(FIX) var collectResults string jQuery(FIX).Find("form").Submit(func(evt jquery.Event) { sa := jQuery(evt.Target).SerializeArray() for i := 0; i < sa.Length(); i++ { collectResults += sa.Index(i).Get("name").String() } assert.Equal(collectResults, "abcde", "SerializeArray") evt.PreventDefault() }) serializedString := "a=1&b=2&c=3&d=4&e=5" assert.Equal(jQuery(FIX).Find("form").Serialize(), serializedString, "Serialize") jQuery(FIX).Find("form").Trigger("submit") }) QUnit.ModuleLifecycle("Events", EvtScenario{}) QUnit.Test("On,One,Off,Trigger", func(assert QUnit.QUnitAssert) { fn := func(ev jquery.Event) { assert.Ok(ev.Data != js.Undefined, "on() with data, check passed data exists") assert.Equal(ev.Data.Get("foo"), "bar", "on() with data, Check value of passed data") } data := map[string]interface{}{"foo": "bar"} jQuery("#firstp").On(jquery.CLICK, data, fn).Trigger(jquery.CLICK).Off(jquery.CLICK, fn) var clickCounter, mouseoverCounter int handler := func(ev jquery.Event) { if ev.Type == jquery.CLICK { clickCounter++ } else if ev.Type == jquery.MOUSEOVER { mouseoverCounter++ } } handlerWithData := func(ev jquery.Event) { if ev.Type == jquery.CLICK { clickCounter += ev.Data.Get("data").Int() } else if ev.Type == jquery.MOUSEOVER { mouseoverCounter += ev.Data.Get("data").Int() } } data2 := map[string]interface{}{"data": 2} elem := jQuery("#firstp").On(jquery.CLICK, handler).On(jquery.MOUSEOVER, handler).One(jquery.CLICK, data2, handlerWithData).One(jquery.MOUSEOVER, data2, handlerWithData) assert.Equal(clickCounter, 0, "clickCounter initialization ok") assert.Equal(mouseoverCounter, 0, "mouseoverCounter initialization ok") elem.Trigger(jquery.CLICK).Trigger(jquery.MOUSEOVER) assert.Equal(clickCounter, 3, "clickCounter Increased after Trigger/On/One") assert.Equal(mouseoverCounter, 3, "mouseoverCounter Increased after Trigger/On/One") elem.Trigger(jquery.CLICK).Trigger(jquery.MOUSEOVER) assert.Equal(clickCounter, 4, "clickCounter Increased after Trigger/On") assert.Equal(mouseoverCounter, 4, "a) mouseoverCounter Increased after TriggerOn") elem.Trigger(jquery.CLICK).Trigger(jquery.MOUSEOVER) assert.Equal(clickCounter, 5, "b) clickCounter not Increased after Off") assert.Equal(mouseoverCounter, 5, "c) mouseoverCounter not Increased after Off") elem.Off(jquery.CLICK).Off(jquery.MOUSEOVER) //2do: elem.Off(jquery.CLICK, handlerWithData).Off(jquery.MOUSEOVER, handlerWithData) elem.Trigger(jquery.CLICK).Trigger(jquery.MOUSEOVER) assert.Equal(clickCounter, 5, "clickCounter not Increased after Off") assert.Equal(mouseoverCounter, 5, "mouseoverCounter not Increased after Off") }) QUnit.Test("Each", func(assert QUnit.QUnitAssert) { jQuery(FIX).Empty() html := `<style> div { color: red; text-align: center; cursor: pointer; font-weight: bolder; width: 300px; } </style> <div>Click here</div> <div>to iterate through</div> <div>these divs.</div>` jQuery(html).AppendTo(FIX) blueCount := 0 jQuery(FIX).On(jquery.CLICK, func(e jquery.Event) { //jQuery(FIX).Find("div").Each(func(i int, elem interface{}) interface{} { jQuery(FIX).Find("div").Each(func(i int, elem interface{}) { style := jQuery(elem).Get(0).Get("style") if style.Get("color").String() != "blue" { style.Set("color", "blue") } else { blueCount += 1 style.Set("color", "") } }) }) for i := 0; i < 6; i++ { jQuery(FIX).Find("div:eq(0)").Trigger("click") } assert.Equal(jQuery(FIX).Find("div").Length, 3, "Test setup problem: 3 divs expected") assert.Equal(blueCount, 9, "blueCount Counter should be 9") }) QUnit.Test("Filter, Resize", func(assert QUnit.QUnitAssert) { jQuery(FIX).Empty() html := `<style> div { width: 60px; height: 60px; margin: 5px; float: left; border: 2px white solid; } </style> <div></div> <div class="middle"></div> <div class="middle"></div> <div class="middle"></div> <div class="middle"></div> <div></div>` jQuery(html).AppendTo(FIX) jQuery(FIX).Find("div").SetCss("background", "silver").Filter(func(index int) bool { return index%3 == 2 }).SetCss("font-weight", "bold") countFontweight := 0 jQuery(FIX).Find("div").Each(func(i int, elem interface{}) { fw := jQuery(elem).Css("font-weight") if fw == "bold" || fw == "700" { countFontweight += 1 } }) assert.Equal(countFontweight, 2, "2 divs should have font-weight = 'bold'") jQuery(js.Global).Resize(func() { jQuery(FIX).Find("div:eq(0)").SetText(strconv.Itoa(jQuery("div:eq(0)").Width())) }).Resize() assert.Equal(jQuery(FIX).Find("div:eq(0)").Text(), "60", "text of first div should be 60") }) QUnit.Test("Not,Offset", func(assert QUnit.QUnitAssert) { QUnit.Expect(0) //api test only jQuery(FIX).Empty() html := `<div></div> <div id="blueone"></div> <div></div> <div class="green"></div> <div class="green"></div> <div class="gray"></div> <div></div>` jQuery(html).AppendTo(FIX) jQuery(FIX).Find("div").Not(".green,#blueone").SetCss("border-color", "red") jQuery("*", "body").On("click", func(event jquery.Event) { offset := jQuery(event.Target).Offset() event.StopPropagation() tag := jQuery(event.Target).Prop("tagName").(string) jQuery("#result").SetText(tag + " coords ( " + strconv.Itoa(offset.Left) + ", " + strconv.Itoa(offset.Top) + " )") }) }) QUnit.Module("Ajax") QUnit.AsyncTest("Async Dummy Test", func() interface{} { QUnit.Expect(1) return js.Global.Call("setTimeout", func() { QUnit.Ok(true, " async ok") QUnit.Start() }, 1000) }) QUnit.AsyncTest("Ajax Call", func() interface{} { QUnit.Expect(1) ajaxopt := Object{ "async": true, "type": "POST", "url": ROOT + "/nestedjson/", "contentType": "application/json charset=utf-8", "dataType": "json", "data": nil, "beforeSend": func(data Object) { if SHOWCONSOLE { print(" before:", data) } }, "success": func(data Object) { dataStr := stringify(data) expected := `{"message":"Welcome!","nested":{"level":1,"moresuccess":true},"success":true}` QUnit.Ok(dataStr == expected, "Ajax call did not returns expected result") QUnit.Start() if SHOWCONSOLE { print(" ajax call success:", data) for k, v := range data { switch v.(type) { case bool: print(k, v.(bool)) case string: print(k, v.(string)) case float64: print(k, v.(float64)) default: print("sth. else:", k, v) } } } }, "error": func(status interface{}) { if SHOWCONSOLE { print(" ajax call error:", status) } }, } //ajax call: jquery.Ajax(ajaxopt) return nil }) QUnit.AsyncTest("Load", func() interface{} { QUnit.Expect(1) jQuery(FIX).Load("/resources/load.html", func() { if SHOWCONSOLE { print(" load got: ", jQuery(FIX).Html() == `<div>load successful!</div>`) } QUnit.Ok(jQuery(FIX).Html() == `<div>load successful!</div>`, "Load call did not returns expected result") QUnit.Start() }) return nil }) QUnit.AsyncTest("Get", func() interface{} { QUnit.Expect(1) jquery.Get("/resources/get.html", func(data interface{}, status string, xhr interface{}) { if SHOWCONSOLE { print(" data: ", data) print(" status: ", status) print(" xhr: ", xhr) } QUnit.Ok(data == `<div>get successful!</div>`, "Get call did not returns expected result") QUnit.Start() }) return nil }) QUnit.AsyncTest("Post", func() interface{} { QUnit.Expect(1) jquery.Post("/gopher", func(data interface{}, status string, xhr interface{}) { if SHOWCONSOLE { print(" data: ", data) print(" status: ", status) print(" xhr: ", xhr) } QUnit.Ok(data == `<div>Welcome gopher</div>`, "Post call did not returns expected result") QUnit.Start() }) return nil }) QUnit.AsyncTest("GetJSON", func() interface{} { QUnit.Expect(1) jquery.GetJSON("/json/1", func(data interface{}) { if val, ok := data.(map[string]interface{})["json"]; ok { if SHOWCONSOLE { print("GetJSON call returns: ", val) } QUnit.Ok(val == `1`, "Json call did not returns expected result") QUnit.Start() } }) return nil }) QUnit.AsyncTest("GetScript", func() interface{} { QUnit.Expect(1) jquery.GetScript("/script", func(data interface{}) { if SHOWCONSOLE { print("GetScript call returns script of length: ", len(data.(string))) } QUnit.Ok(len(data.(string)) == 29, "GetScript call did not returns expected result") QUnit.Start() }) return nil }) QUnit.AsyncTest("AjaxSetup", func() interface{} { QUnit.Expect(1) ajaxSetupOptions := Object{ "async": true, "type": "POST", "url": "/nestedjson/", "contentType": "application/json charset=utf-8", } jquery.AjaxSetup(ajaxSetupOptions) ajaxopt := Object{ "dataType": "json", "data": nil, "beforeSend": func(data Object) { if SHOWCONSOLE { print(" ajaxSetup call, before:", data) } }, "success": func(data Object) { dataStr := stringify(data) expected := `{"message":"Welcome!","nested":{"level":1,"moresuccess":true},"success":true}` QUnit.Ok(dataStr == expected, "AjaxSetup call did not returns expected result") QUnit.Start() if SHOWCONSOLE { print(" ajaxSetup call success:", data) for k, v := range data { switch v.(type) { case bool: print(k, v.(bool)) case string: print(k, v.(string)) case float64: print(k, v.(float64)) default: print("sth. else:", k, v) } } } }, "error": func(status interface{}) { if SHOWCONSOLE { print(" ajaxSetup Call error:", status) } }, } //ajax jquery.Ajax(ajaxopt) return nil }) QUnit.AsyncTest("AjaxPrefilter", func() interface{} { QUnit.Expect(1) jquery.AjaxPrefilter("+json", func(options interface{}, originalOptions string, jqXHR interface{}) { if SHOWCONSOLE { print(" ajax prefilter options:", options.(map[string]interface{})["url"].(string)) } //API Test only }) jquery.GetJSON("/json/3", func(data interface{}) { if val, ok := data.(map[string]interface{})["json"]; ok { if SHOWCONSOLE { print("ajaxPrefilter result: ", val.(string)) } QUnit.Ok(val.(string) == "3", "AjaxPrefilter call did not returns expected result") QUnit.Start() } }) return nil }) QUnit.AsyncTest("AjaxTransport", func() interface{} { QUnit.Expect(1) jquery.AjaxTransport("+json", func(options interface{}, originalOptions string, jqXHR interface{}) { if SHOWCONSOLE { print(" ajax transport options:", options) } //API Test only }) jquery.GetJSON("/json/4", func(data interface{}) { if val, ok := data.(map[string]interface{})["json"]; ok { QUnit.Ok(val.(string) == "4", "AjaxTransport call did not returns expected result") QUnit.Start() } }) return nil }) QUnit.Module("Deferreds") QUnit.AsyncTest("Deferreds Test 01", func() interface{} { QUnit.Expect(1) pass, fail, progress := 0, 0, 0 for i := 0; i < 10; i++ { jquery.When(asyncEvent(i%2 == 0, i)).Then( func(status interface{}) { if SHOWCONSOLE { log(status, "things are going well") } pass += 1 }, func(status interface{}) { if SHOWCONSOLE { log(status, ", you fail this time") } fail += 1 }, func(status interface{}) { if SHOWCONSOLE { log("Progress: ", status.(string)) } progress += 1 }, ).Done(func() { if SHOWCONSOLE { log(" Done. pass, fail, notify = ", pass, fail, progress) } if pass >= 5 { QUnit.Start() QUnit.Ok(pass >= 5 && fail >= 4 && progress >= 20, "Deferred Test 01 fail") } }) } return nil }) QUnit.Test("Deferreds Test 02", func(assert QUnit.QUnitAssert) { QUnit.Expect(1) o := NewWorking(jquery.NewDeferred()) o.Resolve("John") o.Done(func(name string) { o.hi(name) }).Done(func(name string) { o.hi("John") if SHOWCONSOLE { log(" test 02 done: ", countJohn /*2*/, countKarl /*0*/) } }) o.hi("Karl") if SHOWCONSOLE { log(" test 02 end : ", countJohn /*2*/, countKarl /*1*/) } assert.Ok(countJohn == 2 && countKarl == 1, "Deferred Test 02 fail") }) QUnit.AsyncTest("Deferreds Test 03", func() interface{} { QUnit.Expect(1) jquery.Get("/get.html").Always(func() { if SHOWCONSOLE { log("TEST 03: $.get completed with success or error callback arguments") } QUnit.Start() QUnit.Ok(true, "Deferred Test 03 fail") }) return nil }) QUnit.AsyncTest("Deferreds Test 04", func() interface{} { QUnit.Expect(2) jquery.Get("/get.html").Done(func() { QUnit.Ok(true, "Deferred Test 04 fail") if SHOWCONSOLE { log("$.get done: test 04") } }).Fail(func() { if SHOWCONSOLE { log("$.get fail: test 04") } }) jquery.Get("/shouldnotexist.html").Done(func() { if SHOWCONSOLE { log("$.get done: test 04 part 2") } }).Fail(func() { if SHOWCONSOLE { log("$.get fail: test 04 part 2") } QUnit.Start() QUnit.Ok(true, "Deferred Test 04 fail") }) return nil }) QUnit.AsyncTest("Deferreds Test 05", func() interface{} { QUnit.Expect(2) jquery.Get("/get.html").Then(func() { if SHOWCONSOLE { log("$.get done: with success, test 05") } QUnit.Ok(true, "Deferred Test 05 fail") }, func() { if SHOWCONSOLE { log("$.get fail: test 05 part 1") } }) jquery.Get("/shouldnotexist.html").Then(func() { if SHOWCONSOLE { log("$.get done: test 05 part 2") } }, func() { if SHOWCONSOLE { log("$.get fail: test 05 part 1") } QUnit.Start() QUnit.Ok(true, "Deferred Test 05, 2nd part, fail") }) return nil }) QUnit.Test("Deferreds Test 06", func(assert QUnit.QUnitAssert) { QUnit.Expect(1) o := jquery.NewDeferred() filtered := o.Then(func(value int) int { return value * 2 }) o.Resolve(5) filtered.Done(func(value int) { if SHOWCONSOLE { log("test 06: value is ( 2*5 ) = ", value) } assert.Ok(value == 10, "Deferred Test 06 fail") }) }) QUnit.Test("Deferreds Test 07", func(assert QUnit.QUnitAssert) { o := jquery.NewDeferred() filtered := o.Then(nil, func(value int) int { return value * 3 }) o.Reject(6) filtered.Fail(func(value int) { if SHOWCONSOLE { log("Value is ( 3*6 ) = ", value) } assert.Ok(value == 18, "Deferred Test 07 fail") }) }) }