plugin/kubernetes: Enable protobuf, Update client api package (#1114)

* vendor

* code
This commit is contained in:
Chris O'Haver 2017-09-29 15:58:50 -04:00 committed by John Belamaric
parent 45b0252c1a
commit 4b3a430ff2
1511 changed files with 286873 additions and 253612 deletions

26
vendor/github.com/go-openapi/strfmt/.editorconfig generated vendored Normal file
View file

@ -0,0 +1,26 @@
# top-most EditorConfig file
root = true
# Unix-style newlines with a newline ending every file
[*]
end_of_line = lf
insert_final_newline = true
indent_style = space
indent_size = 2
trim_trailing_whitespace = true
# Set default charset
[*.{js,py,go,scala,rb,java,html,css,less,sass,md}]
charset = utf-8
# Tab indentation (no size specified)
[*.go]
indent_style = tab
[*.md]
trim_trailing_whitespace = false
# Matches the exact files either package.json or .travis.yml
[{package.json,.travis.yml}]
indent_style = space
indent_size = 2

2
vendor/github.com/go-openapi/strfmt/.gitignore generated vendored Normal file
View file

@ -0,0 +1,2 @@
secrets.yml
coverage.out

18
vendor/github.com/go-openapi/strfmt/.travis.yml generated vendored Normal file
View file

@ -0,0 +1,18 @@
language: go
go:
- 1.7.1
install:
- go get -u github.com/stretchr/testify/assert
- go get -u github.com/pborman/uuid
- go get -u github.com/asaskevich/govalidator
- go get -u github.com/mailru/easyjson
- go get -u github.com/go-openapi/errors
- go get -u github.com/mitchellh/mapstructure
- go get -u gopkg.in/mgo.v2/bson
script:
- ./hack/coverage
after_success:
- bash <(curl -s https://codecov.io/bash)
notifications:
slack:
secure: zE5AtIYTpYfQPnTzP+EaQPN7JKtfFAGv6PrJqoIZLOXa8B6zGb6+J1JRNNxWi7faWbyJOxa4FSSsuPsKZMycUK6wlLFIdhDxwqeo7Ew8r6rdZKdfUHQggfNS9wO79ARoNYUDHtmnaBUS+eWSM1YqSc4i99QxyyfuURLOeAaA/q14YbdlTlaw3lrZ0qT92ot1FnVGNOx064zuHtFeUf+jAVRMZ6Q3rvqllwIlPszE6rmHGXBt2VoJxRaBetdwd7FgkcYw9FPXKHhadwC7/75ZAdmxIukhxNMw4Tr5NuPcqNcnbYLenDP7B3lssGVIrP4BRSqekS1d/tqvdvnnFWHMwrNCkSnSc065G5+qWTlXKAemIclgiXXqE2furBNLm05MDdG8fn5epS0UNarkjD+zX336RiqwBlOX4KbF+vPyqcO98CsN0lnd+H6loc9reiTHs37orFFpQ+309av9be2GGsHUsRB9ssIyrewmhAccOmkRtr2dVTZJNFQwa5Kph5TNJuTjnZEwG/xUkEX2YSfwShOsb062JWiflV6PJdnl80pc9Tn7D5sO5Bf9DbijGRJwwP+YiiJtwtr+vsvS+n4sM0b5eqm4UoRo+JJO8ffoJtHS7ItuyRbVQCwEPJ4221WLcf5PquEEDdAPwR+K4Gj8qTXqTDdxOiES1xFUKVgmzhI=

74
vendor/github.com/go-openapi/strfmt/CODE_OF_CONDUCT.md generated vendored Normal file
View file

@ -0,0 +1,74 @@
# Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to making participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, gender identity and expression, level of experience,
nationality, personal appearance, race, religion, or sexual identity and
orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment
include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or
advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic
address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.
## Scope
This Code of Conduct applies both within project spaces and in public spaces
when an individual is representing the project or its community. Examples of
representing a project or community include using an official project e-mail
address, posting via an official social media account, or acting as an appointed
representative at an online or offline event. Representation of a project may be
further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting the project team at ivan+abuse@flanders.co.nz. All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. The project team is
obligated to maintain confidentiality with regard to the reporter of an incident.
Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good
faith may face temporary or permanent repercussions as determined by other
members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
available at [http://contributor-covenant.org/version/1/4][version]
[homepage]: http://contributor-covenant.org
[version]: http://contributor-covenant.org/version/1/4/

202
vendor/github.com/go-openapi/strfmt/LICENSE generated vendored Normal file
View file

@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

5
vendor/github.com/go-openapi/strfmt/README.md generated vendored Normal file
View file

@ -0,0 +1,5 @@
# Strfmt [![Build Status](https://travis-ci.org/go-openapi/strfmt.svg?branch=master)](https://travis-ci.org/go-openapi/strfmt) [![codecov](https://codecov.io/gh/go-openapi/strfmt/branch/master/graph/badge.svg)](https://codecov.io/gh/go-openapi/strfmt) [![Slack Status](https://slackin.goswagger.io/badge.svg)](https://slackin.goswagger.io)
[![license](http://img.shields.io/badge/license-Apache%20v2-orange.svg)](https://raw.githubusercontent.com/go-openapi/strfmt/master/LICENSE) [![GoDoc](https://godoc.org/github.com/go-openapi/strfmt?status.svg)](http://godoc.org/github.com/go-openapi/strfmt)
strfmt represents a well known string format such as credit card or email. The go toolkit for open api specifications knows how to deal with those.

124
vendor/github.com/go-openapi/strfmt/bson.go generated vendored Normal file
View file

@ -0,0 +1,124 @@
// Copyright 2015 go-swagger maintainers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package strfmt
import (
"database/sql/driver"
"errors"
"fmt"
"github.com/mailru/easyjson/jlexer"
"github.com/mailru/easyjson/jwriter"
"gopkg.in/mgo.v2/bson"
)
func init() {
var id ObjectId
Default.Add("bsonobjectid", &id, IsBSONObjectID)
}
// IsBSONObjectID returns true when the string is a valid BSON.ObjectId
func IsBSONObjectID(str string) bool {
var id bson.ObjectId
return id.UnmarshalText([]byte(str)) == nil
}
type ObjectId bson.ObjectId
// NewObjectId creates a ObjectId from a Hex String
func NewObjectId(hex string) ObjectId {
return ObjectId(bson.ObjectIdHex(hex))
}
// MarshalText turns this instance into text
func (id *ObjectId) MarshalText() ([]byte, error) {
return []byte(bson.ObjectId(*id).Hex()), nil
}
// UnmarshalText hydrates this instance from text
func (id *ObjectId) UnmarshalText(data []byte) error { // validation is performed later on
var rawID bson.ObjectId
if err := rawID.UnmarshalText(data); err != nil {
return err
}
*id = ObjectId(rawID)
return nil
}
// Scan read a value from a database driver
func (id *ObjectId) Scan(raw interface{}) error {
var data []byte
switch v := raw.(type) {
case []byte:
data = v
case string:
data = []byte(v)
default:
return fmt.Errorf("cannot sql.Scan() strfmt.URI from: %#v", v)
}
return id.UnmarshalText(data)
}
// Value converts a value to a database driver value
func (id *ObjectId) Value() (driver.Value, error) {
return driver.Value(string(*id)), nil
}
func (id *ObjectId) String() string {
return string(*id)
}
func (id *ObjectId) MarshalJSON() ([]byte, error) {
var w jwriter.Writer
id.MarshalEasyJSON(&w)
return w.BuildBytes()
}
func (id *ObjectId) MarshalEasyJSON(w *jwriter.Writer) {
w.String(bson.ObjectId(*id).Hex())
}
func (id *ObjectId) UnmarshalJSON(data []byte) error {
l := jlexer.Lexer{Data: data}
id.UnmarshalEasyJSON(&l)
return l.Error()
}
func (id *ObjectId) UnmarshalEasyJSON(in *jlexer.Lexer) {
if data := in.String(); in.Ok() {
*id = NewObjectId(data)
}
}
func (id *ObjectId) GetBSON() (interface{}, error) {
return bson.M{"data": bson.ObjectId(*id).Hex()}, nil
}
func (id *ObjectId) SetBSON(raw bson.Raw) error {
var m bson.M
if err := raw.Unmarshal(&m); err != nil {
return err
}
if data, ok := m["data"].(string); ok {
*id = NewObjectId(data)
return nil
}
return errors.New("couldn't unmarshal bson raw value as ObjectId")
}

53
vendor/github.com/go-openapi/strfmt/bson_test.go generated vendored Normal file
View file

@ -0,0 +1,53 @@
// Copyright 2015 go-swagger maintainers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package strfmt
import (
"testing"
"gopkg.in/mgo.v2/bson"
"github.com/stretchr/testify/assert"
)
func TestBSONObjectId_fullCycle(t *testing.T) {
id := NewObjectId("507f1f77bcf86cd799439011")
bytes, err := id.MarshalText()
assert.NoError(t, err)
var idCopy ObjectId
err = idCopy.Scan(bytes)
assert.NoError(t, err)
assert.Equal(t, id, idCopy)
err = idCopy.UnmarshalText(bytes)
assert.NoError(t, err)
assert.Equal(t, id, idCopy)
jsonBytes, err := id.MarshalJSON()
assert.NoError(t, err)
err = idCopy.UnmarshalJSON(jsonBytes)
assert.NoError(t, err)
assert.Equal(t, id, idCopy)
bsonBytes, err := bson.Marshal(&id)
assert.NoError(t, err)
err = bson.Unmarshal(bsonBytes, &idCopy)
assert.NoError(t, err)
assert.Equal(t, id, idCopy)
}

152
vendor/github.com/go-openapi/strfmt/date.go generated vendored Normal file
View file

@ -0,0 +1,152 @@
// Copyright 2015 go-swagger maintainers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package strfmt
import (
"database/sql/driver"
"errors"
"fmt"
"regexp"
"time"
"gopkg.in/mgo.v2/bson"
"github.com/mailru/easyjson/jlexer"
"github.com/mailru/easyjson/jwriter"
)
func init() {
d := Date{}
Default.Add("date", &d, IsDate)
}
// IsDate returns true when the string is a valid date
func IsDate(str string) bool {
matches := rxDate.FindAllStringSubmatch(str, -1)
if len(matches) == 0 || len(matches[0]) == 0 {
return false
}
m := matches[0]
return !(m[2] < "01" || m[2] > "12" || m[3] < "01" || m[3] > "31")
}
const (
// RFC3339FullDate represents a full-date as specified by RFC3339
// See: http://goo.gl/xXOvVd
RFC3339FullDate = "2006-01-02"
// DatePattern pattern to match for the date format from http://tools.ietf.org/html/rfc3339#section-5.6
DatePattern = `^([0-9]{4})-([0-9]{2})-([0-9]{2})`
)
var (
rxDate = regexp.MustCompile(DatePattern)
)
// Date represents a date from the API
//
// swagger:strfmt date
type Date time.Time
// String converts this date into a string
func (d Date) String() string {
return time.Time(d).Format(RFC3339FullDate)
}
// UnmarshalText parses a text representation into a date type
func (d *Date) UnmarshalText(text []byte) error {
if len(text) == 0 {
return nil
}
dd, err := time.Parse(RFC3339FullDate, string(text))
if err != nil {
return err
}
*d = Date(dd)
return nil
}
// MarshalText serializes this date type to string
func (d Date) MarshalText() ([]byte, error) {
return []byte(d.String()), nil
}
// Scan scans a Date value from database driver type.
func (d *Date) Scan(raw interface{}) error {
switch v := raw.(type) {
case []byte:
return d.UnmarshalText(v)
case string:
return d.UnmarshalText([]byte(v))
case time.Time:
*d = Date(v)
return nil
case nil:
*d = Date{}
return nil
default:
return fmt.Errorf("cannot sql.Scan() strfmt.Date from: %#v", v)
}
}
// Value converts Date to a primitive value ready to written to a database.
func (d Date) Value() (driver.Value, error) {
return driver.Value(d.String()), nil
}
func (t Date) MarshalJSON() ([]byte, error) {
var w jwriter.Writer
t.MarshalEasyJSON(&w)
return w.BuildBytes()
}
func (t Date) MarshalEasyJSON(w *jwriter.Writer) {
w.String(time.Time(t).Format(RFC3339FullDate))
}
func (t *Date) UnmarshalJSON(data []byte) error {
l := jlexer.Lexer{Data: data}
t.UnmarshalEasyJSON(&l)
return l.Error()
}
func (t *Date) UnmarshalEasyJSON(in *jlexer.Lexer) {
if data := in.String(); in.Ok() {
tt, err := time.Parse(RFC3339FullDate, data)
if err != nil {
in.AddError(err)
return
}
*t = Date(tt)
}
}
func (t *Date) GetBSON() (interface{}, error) {
return bson.M{"data": t.String()}, nil
}
func (t *Date) SetBSON(raw bson.Raw) error {
var m bson.M
if err := raw.Unmarshal(&m); err != nil {
return err
}
if data, ok := m["data"].(string); ok {
rd, err := time.Parse(RFC3339FullDate, data)
*t = Date(rd)
return err
}
return errors.New("couldn't unmarshal bson raw value as Duration")
}

83
vendor/github.com/go-openapi/strfmt/date_test.go generated vendored Normal file
View file

@ -0,0 +1,83 @@
// Copyright 2015 go-swagger maintainers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package strfmt
import (
"database/sql"
"database/sql/driver"
"testing"
"time"
"gopkg.in/mgo.v2/bson"
"github.com/stretchr/testify/assert"
)
var _ sql.Scanner = &Date{}
var _ driver.Valuer = Date{}
func TestDate(t *testing.T) {
pp := Date{}
err := pp.UnmarshalText([]byte{})
assert.NoError(t, err)
err = pp.UnmarshalText([]byte("yada"))
assert.Error(t, err)
orig := "2014-12-15"
b := []byte(orig)
bj := []byte("\"" + orig + "\"")
err = pp.UnmarshalText([]byte(orig))
assert.NoError(t, err)
txt, err := pp.MarshalText()
assert.NoError(t, err)
assert.Equal(t, orig, string(txt))
err = pp.UnmarshalJSON(bj)
assert.NoError(t, err)
assert.EqualValues(t, orig, pp.String())
b, err = pp.MarshalJSON()
assert.NoError(t, err)
assert.Equal(t, bj, b)
dateOriginal := Date(time.Date(2014, 10, 10, 0, 0, 0, 0, time.UTC))
bsonData, err := bson.Marshal(&dateOriginal)
assert.NoError(t, err)
var dateCopy Date
err = bson.Unmarshal(bsonData, &dateCopy)
assert.NoError(t, err)
assert.Equal(t, dateOriginal, dateCopy)
}
func TestDate_Scan(t *testing.T) {
ref := time.Now().Truncate(24 * time.Hour).UTC()
date, str := Date(ref), ref.Format(RFC3339FullDate)
values := []interface{}{str, []byte(str), ref}
for _, value := range values {
result := Date{}
(&result).Scan(value)
assert.Equal(t, date, result, "value: %#v", value)
}
}
func TestDate_Value(t *testing.T) {
ref := time.Now().Truncate(24 * time.Hour).UTC()
date := Date(ref)
dbv, err := date.Value()
assert.NoError(t, err)
assert.EqualValues(t, dbv, ref.Format("2006-01-02"))
}

1697
vendor/github.com/go-openapi/strfmt/default.go generated vendored Normal file

File diff suppressed because it is too large Load diff

691
vendor/github.com/go-openapi/strfmt/default_test.go generated vendored Normal file
View file

@ -0,0 +1,691 @@
// Copyright 2015 go-swagger maintainers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package strfmt
import (
"testing"
"github.com/pborman/uuid"
"github.com/stretchr/testify/assert"
"gopkg.in/mgo.v2/bson"
)
func testValid(t *testing.T, name, value string) {
ok := Default.Validates(name, value)
if !ok {
t.Errorf("expected %s of type %s to be valid", value, name)
}
}
func testInvalid(t *testing.T, name, value string) {
ok := Default.Validates(name, value)
if ok {
t.Errorf("expected %s of type %s to be invalid", value, name)
}
}
func TestFormatURI(t *testing.T) {
uri := URI("http://somewhere.com")
str := string("http://somewhereelse.com")
b := []byte(str)
bj := []byte("\"" + str + "\"")
err := uri.UnmarshalText(b)
assert.NoError(t, err)
assert.EqualValues(t, URI("http://somewhereelse.com"), string(b))
b, err = uri.MarshalText()
assert.NoError(t, err)
assert.Equal(t, []byte("http://somewhereelse.com"), b)
err = uri.UnmarshalJSON(bj)
assert.NoError(t, err)
assert.EqualValues(t, URI("http://somewhereelse.com"), string(b))
b, err = uri.MarshalJSON()
assert.NoError(t, err)
assert.Equal(t, bj, b)
bsonData, err := bson.Marshal(&uri)
assert.NoError(t, err)
var uriCopy URI
err = bson.Unmarshal(bsonData, &uriCopy)
assert.NoError(t, err)
assert.Equal(t, uri, uriCopy)
testValid(t, "uri", str)
testInvalid(t, "uri", "somewhere.com")
}
func TestFormatEmail(t *testing.T) {
email := Email("somebody@somewhere.com")
str := string("somebodyelse@somewhere.com")
b := []byte(str)
bj := []byte("\"" + str + "\"")
err := email.UnmarshalText(b)
assert.NoError(t, err)
assert.EqualValues(t, Email("somebodyelse@somewhere.com"), string(b))
b, err = email.MarshalText()
assert.NoError(t, err)
assert.Equal(t, []byte("somebodyelse@somewhere.com"), b)
err = email.UnmarshalJSON(bj)
assert.NoError(t, err)
assert.EqualValues(t, Email(str), string(b))
b, err = email.MarshalJSON()
assert.NoError(t, err)
assert.Equal(t, bj, b)
bsonData, err := bson.Marshal(&email)
assert.NoError(t, err)
var emailCopy Email
err = bson.Unmarshal(bsonData, &emailCopy)
assert.NoError(t, err)
assert.Equal(t, email, emailCopy)
testValid(t, "email", str)
testInvalid(t, "email", "somebody@somewhere@com")
}
func TestFormatHostname(t *testing.T) {
hostname := Hostname("somewhere.com")
str := string("somewhere.com")
b := []byte(str)
bj := []byte("\"" + str + "\"")
err := hostname.UnmarshalText(b)
assert.NoError(t, err)
assert.EqualValues(t, Hostname("somewhere.com"), string(b))
b, err = hostname.MarshalText()
assert.NoError(t, err)
assert.Equal(t, []byte("somewhere.com"), b)
err = hostname.UnmarshalJSON(bj)
assert.NoError(t, err)
assert.EqualValues(t, Hostname(str), string(b))
b, err = hostname.MarshalJSON()
assert.NoError(t, err)
assert.Equal(t, bj, b)
bsonData, err := bson.Marshal(&hostname)
assert.NoError(t, err)
var hostnameCopy Hostname
err = bson.Unmarshal(bsonData, &hostnameCopy)
assert.NoError(t, err)
assert.Equal(t, hostname, hostnameCopy)
testValid(t, "hostname", str)
testInvalid(t, "hostname", "somewhere.com!")
}
func TestFormatIPv4(t *testing.T) {
ipv4 := IPv4("192.168.254.1")
str := string("192.168.254.2")
b := []byte(str)
bj := []byte("\"" + str + "\"")
err := ipv4.UnmarshalText(b)
assert.NoError(t, err)
assert.EqualValues(t, IPv4("192.168.254.2"), string(b))
b, err = ipv4.MarshalText()
assert.NoError(t, err)
assert.Equal(t, []byte("192.168.254.2"), b)
err = ipv4.UnmarshalJSON(bj)
assert.NoError(t, err)
assert.EqualValues(t, IPv4(str), string(b))
b, err = ipv4.MarshalJSON()
assert.NoError(t, err)
assert.Equal(t, bj, b)
bsonData, err := bson.Marshal(&ipv4)
assert.NoError(t, err)
var ipv4Copy IPv4
err = bson.Unmarshal(bsonData, &ipv4Copy)
assert.NoError(t, err)
assert.Equal(t, ipv4, ipv4Copy)
testValid(t, "ipv4", str)
testInvalid(t, "ipv4", "192.168.254.2.2")
}
func TestFormatIPv6(t *testing.T) {
ipv6 := IPv6("::1")
str := string("::2")
b := []byte(str)
bj := []byte("\"" + str + "\"")
err := ipv6.UnmarshalText(b)
assert.NoError(t, err)
assert.EqualValues(t, IPv6("::2"), string(b))
b, err = ipv6.MarshalText()
assert.NoError(t, err)
assert.Equal(t, []byte("::2"), b)
err = ipv6.UnmarshalJSON(bj)
assert.NoError(t, err)
assert.EqualValues(t, IPv6(str), string(b))
b, err = ipv6.MarshalJSON()
assert.NoError(t, err)
assert.Equal(t, bj, b)
bsonData, err := bson.Marshal(&ipv6)
assert.NoError(t, err)
var ipv6Copy IPv6
err = bson.Unmarshal(bsonData, &ipv6Copy)
assert.NoError(t, err)
assert.Equal(t, ipv6, ipv6Copy)
testValid(t, "ipv6", str)
testInvalid(t, "ipv6", "127.0.0.1")
}
func TestFormatMAC(t *testing.T) {
mac := MAC("01:02:03:04:05:06")
str := string("06:05:04:03:02:01")
b := []byte(str)
bj := []byte("\"" + str + "\"")
err := mac.UnmarshalText(b)
assert.NoError(t, err)
assert.EqualValues(t, MAC("06:05:04:03:02:01"), string(b))
b, err = mac.MarshalText()
assert.NoError(t, err)
assert.Equal(t, []byte("06:05:04:03:02:01"), b)
err = mac.UnmarshalJSON(bj)
assert.NoError(t, err)
assert.EqualValues(t, MAC(str), string(b))
b, err = mac.MarshalJSON()
assert.NoError(t, err)
assert.Equal(t, bj, b)
bsonData, err := bson.Marshal(&mac)
assert.NoError(t, err)
var macCopy MAC
err = bson.Unmarshal(bsonData, &macCopy)
assert.NoError(t, err)
assert.Equal(t, mac, macCopy)
testValid(t, "mac", str)
testInvalid(t, "mac", "01:02:03:04:05")
}
func TestFormatUUID3(t *testing.T) {
first3 := uuid.NewMD5(uuid.NameSpace_URL, []byte("somewhere.com"))
other3 := uuid.NewMD5(uuid.NameSpace_URL, []byte("somewhereelse.com"))
uuid3 := UUID3(first3.String())
str := string(other3.String())
b := []byte(str)
bj := []byte("\"" + str + "\"")
err := uuid3.UnmarshalText(b)
assert.NoError(t, err)
assert.EqualValues(t, UUID3(other3.String()), string(b))
b, err = uuid3.MarshalText()
assert.NoError(t, err)
assert.EqualValues(t, []byte(other3.String()), b)
err = uuid3.UnmarshalJSON(bj)
assert.NoError(t, err)
assert.EqualValues(t, UUID3(str), string(b))
b, err = uuid3.MarshalJSON()
assert.NoError(t, err)
assert.Equal(t, bj, b)
bsonData, err := bson.Marshal(&uuid3)
assert.NoError(t, err)
var uuid3Copy UUID3
err = bson.Unmarshal(bsonData, &uuid3Copy)
assert.NoError(t, err)
assert.Equal(t, uuid3, uuid3Copy)
testValid(t, "uuid3", str)
testInvalid(t, "uuid3", "not-a-uuid")
}
func TestFormatUUID4(t *testing.T) {
first4 := uuid.NewRandom()
other4 := uuid.NewRandom()
uuid4 := UUID4(first4.String())
str := string(other4.String())
b := []byte(str)
bj := []byte("\"" + str + "\"")
err := uuid4.UnmarshalText(b)
assert.NoError(t, err)
assert.EqualValues(t, UUID4(other4.String()), string(b))
b, err = uuid4.MarshalText()
assert.NoError(t, err)
assert.Equal(t, []byte(other4.String()), b)
err = uuid4.UnmarshalJSON(bj)
assert.NoError(t, err)
assert.EqualValues(t, UUID4(str), string(b))
b, err = uuid4.MarshalJSON()
assert.NoError(t, err)
assert.Equal(t, bj, b)
bsonData, err := bson.Marshal(&uuid4)
assert.NoError(t, err)
var uuid4Copy UUID4
err = bson.Unmarshal(bsonData, &uuid4Copy)
assert.NoError(t, err)
assert.Equal(t, uuid4, uuid4Copy)
testValid(t, "uuid4", str)
testInvalid(t, "uuid4", "not-a-uuid")
}
func TestFormatUUID5(t *testing.T) {
first5 := uuid.NewSHA1(uuid.NameSpace_URL, []byte("somewhere.com"))
other5 := uuid.NewSHA1(uuid.NameSpace_URL, []byte("somewhereelse.com"))
uuid5 := UUID5(first5.String())
str := string(other5.String())
b := []byte(str)
bj := []byte("\"" + str + "\"")
err := uuid5.UnmarshalText(b)
assert.NoError(t, err)
assert.EqualValues(t, UUID5(other5.String()), string(b))
b, err = uuid5.MarshalText()
assert.NoError(t, err)
assert.Equal(t, []byte(other5.String()), b)
err = uuid5.UnmarshalJSON(bj)
assert.NoError(t, err)
assert.EqualValues(t, UUID5(str), string(b))
b, err = uuid5.MarshalJSON()
assert.NoError(t, err)
assert.Equal(t, bj, b)
bsonData, err := bson.Marshal(&uuid5)
assert.NoError(t, err)
var uuid5Copy UUID5
err = bson.Unmarshal(bsonData, &uuid5Copy)
assert.NoError(t, err)
assert.Equal(t, uuid5, uuid5Copy)
testValid(t, "uuid5", str)
testInvalid(t, "uuid5", "not-a-uuid")
}
func TestFormatUUID(t *testing.T) {
first5 := uuid.NewSHA1(uuid.NameSpace_URL, []byte("somewhere.com"))
other5 := uuid.NewSHA1(uuid.NameSpace_URL, []byte("somewhereelse.com"))
uuid := UUID(first5.String())
str := string(other5.String())
b := []byte(str)
bj := []byte("\"" + str + "\"")
err := uuid.UnmarshalText(b)
assert.NoError(t, err)
assert.EqualValues(t, UUID(other5.String()), string(b))
b, err = uuid.MarshalText()
assert.NoError(t, err)
assert.Equal(t, []byte(other5.String()), b)
err = uuid.UnmarshalJSON(bj)
assert.NoError(t, err)
assert.EqualValues(t, UUID(str), string(b))
b, err = uuid.MarshalJSON()
assert.NoError(t, err)
assert.Equal(t, bj, b)
bsonData, err := bson.Marshal(&uuid)
assert.NoError(t, err)
var uuidCopy UUID
err = bson.Unmarshal(bsonData, &uuidCopy)
assert.NoError(t, err)
assert.Equal(t, uuid, uuidCopy)
testValid(t, "uuid", str)
testInvalid(t, "uuid", "not-a-uuid")
}
func TestFormatISBN(t *testing.T) {
isbn := ISBN("0321751043")
str := string("0321751043")
b := []byte(str)
bj := []byte("\"" + str + "\"")
err := isbn.UnmarshalText(b)
assert.NoError(t, err)
assert.EqualValues(t, ISBN("0321751043"), string(b))
b, err = isbn.MarshalText()
assert.NoError(t, err)
assert.Equal(t, []byte("0321751043"), b)
err = isbn.UnmarshalJSON(bj)
assert.NoError(t, err)
assert.EqualValues(t, ISBN(str), string(b))
b, err = isbn.MarshalJSON()
assert.NoError(t, err)
assert.Equal(t, bj, b)
bsonData, err := bson.Marshal(&isbn)
assert.NoError(t, err)
var isbnCopy ISBN
err = bson.Unmarshal(bsonData, &isbnCopy)
assert.NoError(t, err)
assert.Equal(t, isbn, isbnCopy)
testValid(t, "isbn", str)
testInvalid(t, "isbn", "836217463") // bad checksum
}
func TestFormatISBN10(t *testing.T) {
isbn10 := ISBN10("0321751043")
str := string("0321751043")
b := []byte(str)
bj := []byte("\"" + str + "\"")
err := isbn10.UnmarshalText(b)
assert.NoError(t, err)
assert.EqualValues(t, ISBN10("0321751043"), string(b))
b, err = isbn10.MarshalText()
assert.NoError(t, err)
assert.Equal(t, []byte("0321751043"), b)
err = isbn10.UnmarshalJSON(bj)
assert.NoError(t, err)
assert.EqualValues(t, ISBN10(str), string(b))
b, err = isbn10.MarshalJSON()
assert.NoError(t, err)
assert.Equal(t, bj, b)
bsonData, err := bson.Marshal(&isbn10)
assert.NoError(t, err)
var isbn10Copy ISBN10
err = bson.Unmarshal(bsonData, &isbn10Copy)
assert.NoError(t, err)
assert.Equal(t, isbn10, isbn10Copy)
testValid(t, "isbn10", str)
testInvalid(t, "isbn10", "836217463") // bad checksum
}
func TestFormatISBN13(t *testing.T) {
isbn13 := ISBN13("978-0321751041")
str := string("978-0321751041")
b := []byte(str)
bj := []byte("\"" + str + "\"")
err := isbn13.UnmarshalText(b)
assert.NoError(t, err)
assert.EqualValues(t, ISBN13("978-0321751041"), string(b))
b, err = isbn13.MarshalText()
assert.NoError(t, err)
assert.Equal(t, []byte("978-0321751041"), b)
err = isbn13.UnmarshalJSON(bj)
assert.NoError(t, err)
assert.EqualValues(t, ISBN13(str), string(b))
b, err = isbn13.MarshalJSON()
assert.NoError(t, err)
assert.Equal(t, bj, b)
bsonData, err := bson.Marshal(&isbn13)
assert.NoError(t, err)
var isbn13Copy ISBN13
err = bson.Unmarshal(bsonData, &isbn13Copy)
assert.NoError(t, err)
assert.Equal(t, isbn13, isbn13Copy)
testValid(t, "isbn13", str)
testInvalid(t, "isbn13", "978-0321751042") // bad checksum
}
func TestFormatHexColor(t *testing.T) {
hexColor := HexColor("#FFFFFF")
str := string("#000000")
b := []byte(str)
bj := []byte("\"" + str + "\"")
err := hexColor.UnmarshalText(b)
assert.NoError(t, err)
assert.EqualValues(t, HexColor("#000000"), string(b))
b, err = hexColor.MarshalText()
assert.NoError(t, err)
assert.Equal(t, []byte("#000000"), b)
err = hexColor.UnmarshalJSON(bj)
assert.NoError(t, err)
assert.EqualValues(t, HexColor(str), string(b))
b, err = hexColor.MarshalJSON()
assert.NoError(t, err)
assert.Equal(t, bj, b)
bsonData, err := bson.Marshal(&hexColor)
assert.NoError(t, err)
var hexColorCopy HexColor
err = bson.Unmarshal(bsonData, &hexColorCopy)
assert.NoError(t, err)
assert.Equal(t, hexColor, hexColorCopy)
testValid(t, "hexcolor", str)
testInvalid(t, "hexcolor", "#fffffffz")
}
func TestFormatRGBColor(t *testing.T) {
rgbColor := RGBColor("rgb(255,255,255)")
str := string("rgb(0,0,0)")
b := []byte(str)
bj := []byte("\"" + str + "\"")
err := rgbColor.UnmarshalText(b)
assert.NoError(t, err)
assert.EqualValues(t, RGBColor("rgb(0,0,0)"), string(b))
b, err = rgbColor.MarshalText()
assert.NoError(t, err)
assert.Equal(t, []byte("rgb(0,0,0)"), b)
err = rgbColor.UnmarshalJSON(bj)
assert.NoError(t, err)
assert.EqualValues(t, RGBColor(str), string(b))
b, err = rgbColor.MarshalJSON()
assert.NoError(t, err)
assert.Equal(t, bj, b)
bsonData, err := bson.Marshal(&rgbColor)
assert.NoError(t, err)
var rgbColorCopy RGBColor
err = bson.Unmarshal(bsonData, &rgbColorCopy)
assert.NoError(t, err)
assert.Equal(t, rgbColor, rgbColorCopy)
testValid(t, "rgbcolor", str)
testInvalid(t, "rgbcolor", "rgb(300,0,0)")
}
func TestFormatSSN(t *testing.T) {
ssn := SSN("111-11-1111")
str := string("999 99 9999")
b := []byte(str)
bj := []byte("\"" + str + "\"")
err := ssn.UnmarshalText(b)
assert.NoError(t, err)
assert.EqualValues(t, SSN("999 99 9999"), string(b))
b, err = ssn.MarshalText()
assert.NoError(t, err)
assert.Equal(t, []byte("999 99 9999"), b)
err = ssn.UnmarshalJSON(bj)
assert.NoError(t, err)
assert.EqualValues(t, SSN(str), string(b))
b, err = ssn.MarshalJSON()
assert.NoError(t, err)
assert.Equal(t, bj, b)
bsonData, err := bson.Marshal(&ssn)
assert.NoError(t, err)
var ssnCopy SSN
err = bson.Unmarshal(bsonData, &ssnCopy)
assert.NoError(t, err)
assert.Equal(t, ssn, ssnCopy)
testValid(t, "ssn", str)
testInvalid(t, "ssn", "999 99 999")
}
func TestFormatCreditCard(t *testing.T) {
creditCard := CreditCard("4111-1111-1111-1111")
str := string("4012-8888-8888-1881")
b := []byte(str)
bj := []byte("\"" + str + "\"")
err := creditCard.UnmarshalText(b)
assert.NoError(t, err)
assert.EqualValues(t, CreditCard("4012-8888-8888-1881"), string(b))
b, err = creditCard.MarshalText()
assert.NoError(t, err)
assert.Equal(t, []byte("4012-8888-8888-1881"), b)
err = creditCard.UnmarshalJSON(bj)
assert.NoError(t, err)
assert.EqualValues(t, CreditCard(str), string(b))
b, err = creditCard.MarshalJSON()
assert.NoError(t, err)
assert.Equal(t, bj, b)
bsonData, err := bson.Marshal(&creditCard)
assert.NoError(t, err)
var creditCardCopy CreditCard
err = bson.Unmarshal(bsonData, &creditCardCopy)
assert.NoError(t, err)
assert.Equal(t, creditCard, creditCardCopy)
testValid(t, "creditcard", str)
testInvalid(t, "creditcard", "9999-9999-9999-999") // bad checksum
}
func TestFormatPassword(t *testing.T) {
password := Password("super secret stuff here")
str := string("even more secret")
b := []byte(str)
bj := []byte("\"" + str + "\"")
err := password.UnmarshalText(b)
assert.NoError(t, err)
assert.EqualValues(t, Password("even more secret"), string(b))
b, err = password.MarshalText()
assert.NoError(t, err)
assert.Equal(t, []byte("even more secret"), b)
err = password.UnmarshalJSON(bj)
assert.NoError(t, err)
assert.EqualValues(t, Password(str), string(b))
b, err = password.MarshalJSON()
assert.NoError(t, err)
assert.Equal(t, bj, b)
bsonData, err := bson.Marshal(&password)
assert.NoError(t, err)
var passwordCopy Password
err = bson.Unmarshal(bsonData, &passwordCopy)
assert.NoError(t, err)
assert.Equal(t, password, passwordCopy)
// everything is valid
testValid(t, "password", str)
}
func TestFormatBase64(t *testing.T) {
b64 := Base64("ZWxpemFiZXRocG9zZXk=")
str := string("ZWxpemFiZXRocG9zZXk=")
b := []byte(str)
bj := []byte("\"" + str + "\"")
err := b64.UnmarshalText(b)
assert.NoError(t, err)
assert.EqualValues(t, Base64("ZWxpemFiZXRocG9zZXk="), string(b))
b, err = b64.MarshalText()
assert.NoError(t, err)
assert.Equal(t, []byte("ZWxpemFiZXRocG9zZXk="), b)
err = b64.UnmarshalJSON(bj)
assert.NoError(t, err)
assert.EqualValues(t, Base64(str), string(b))
b, err = b64.MarshalJSON()
assert.NoError(t, err)
assert.Equal(t, bj, b)
bsonData, err := bson.Marshal(&b64)
assert.NoError(t, err)
var b64Copy Base64
err = bson.Unmarshal(bsonData, &b64Copy)
assert.NoError(t, err)
assert.Equal(t, b64, b64Copy)
testValid(t, "byte", str)
testInvalid(t, "byte", "ZWxpemFiZXRocG9zZXk") // missing pad char
}

18
vendor/github.com/go-openapi/strfmt/doc.go generated vendored Normal file
View file

@ -0,0 +1,18 @@
// Copyright 2015 go-swagger maintainers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package strfmt contains custom string formats
//
// TODO: add info on how to define and register a custom format
package strfmt

194
vendor/github.com/go-openapi/strfmt/duration.go generated vendored Normal file
View file

@ -0,0 +1,194 @@
// Copyright 2015 go-swagger maintainers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package strfmt
import (
"database/sql/driver"
"errors"
"fmt"
"regexp"
"strconv"
"strings"
"time"
"gopkg.in/mgo.v2/bson"
"github.com/mailru/easyjson/jlexer"
"github.com/mailru/easyjson/jwriter"
)
func init() {
d := Duration(0)
Default.Add("duration", &d, IsDuration)
}
var (
timeUnits = [][]string{
{"ns", "nano"},
{"us", "µs", "micro"},
{"ms", "milli"},
{"s", "sec"},
{"m", "min"},
{"h", "hr", "hour"},
{"d", "day"},
{"w", "wk", "week"},
}
timeMultiplier = map[string]time.Duration{
"ns": time.Nanosecond,
"us": time.Microsecond,
"ms": time.Millisecond,
"s": time.Second,
"m": time.Minute,
"h": time.Hour,
"d": 24 * time.Hour,
"w": 7 * 24 * time.Hour,
}
durationMatcher = regexp.MustCompile(`((\d+)\s*([A-Za-zµ]+))`)
)
// IsDuration returns true if the provided string is a valid duration
func IsDuration(str string) bool {
_, err := ParseDuration(str)
return err == nil
}
// Duration represents a duration
//
// swagger:strfmt duration
type Duration time.Duration
// MarshalText turns this instance into text
func (d Duration) MarshalText() ([]byte, error) {
return []byte(time.Duration(d).String()), nil
}
// UnmarshalText hydrates this instance from text
func (d *Duration) UnmarshalText(data []byte) error { // validation is performed later on
dd, err := ParseDuration(string(data))
if err != nil {
return err
}
*d = Duration(dd)
return nil
}
// ParseDuration parses a duration from a string, compatible with scala duration syntax
func ParseDuration(cand string) (time.Duration, error) {
if dur, err := time.ParseDuration(cand); err == nil {
return dur, nil
}
var dur time.Duration
ok := false
for _, match := range durationMatcher.FindAllStringSubmatch(cand, -1) {
factor, err := strconv.Atoi(match[2]) // converts string to int
if err != nil {
return 0, err
}
unit := strings.ToLower(strings.TrimSpace(match[3]))
for _, variants := range timeUnits {
last := len(variants) - 1
multiplier := timeMultiplier[variants[0]]
for i, variant := range variants {
if (last == i && strings.HasPrefix(unit, variant)) || strings.EqualFold(variant, unit) {
ok = true
dur += (time.Duration(factor) * multiplier)
}
}
}
}
if ok {
return dur, nil
}
return 0, fmt.Errorf("Unable to parse %s as duration", cand)
}
// Scan reads a Duration value from database driver type.
func (d *Duration) Scan(raw interface{}) error {
switch v := raw.(type) {
// TODO: case []byte: // ?
case int64:
*d = Duration(v)
case float64:
*d = Duration(int64(v))
case nil:
*d = Duration(0)
default:
return fmt.Errorf("cannot sql.Scan() strfmt.Duration from: %#v", v)
}
return nil
}
// Value converts Duration to a primitive value ready to written to a database.
func (d Duration) Value() (driver.Value, error) {
return driver.Value(int64(d)), nil
}
// String converts this duration to a string
func (d Duration) String() string {
return time.Duration(d).String()
}
func (d Duration) MarshalJSON() ([]byte, error) {
var w jwriter.Writer
d.MarshalEasyJSON(&w)
return w.BuildBytes()
}
func (d Duration) MarshalEasyJSON(w *jwriter.Writer) {
w.String(time.Duration(d).String())
}
func (d *Duration) UnmarshalJSON(data []byte) error {
l := jlexer.Lexer{Data: data}
d.UnmarshalEasyJSON(&l)
return l.Error()
}
func (d *Duration) UnmarshalEasyJSON(in *jlexer.Lexer) {
if data := in.String(); in.Ok() {
tt, err := ParseDuration(data)
if err != nil {
in.AddError(err)
return
}
*d = Duration(tt)
}
}
func (d *Duration) GetBSON() (interface{}, error) {
return bson.M{"data": int64(*d)}, nil
}
func (d *Duration) SetBSON(raw bson.Raw) error {
var m bson.M
if err := raw.Unmarshal(&m); err != nil {
return err
}
if data, ok := m["data"].(int64); ok {
*d = Duration(data)
return nil
}
return errors.New("couldn't unmarshal bson raw value as Duration")
}

143
vendor/github.com/go-openapi/strfmt/duration_test.go generated vendored Normal file
View file

@ -0,0 +1,143 @@
// Copyright 2015 go-swagger maintainers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package strfmt
import (
"testing"
"time"
"gopkg.in/mgo.v2/bson"
"github.com/stretchr/testify/assert"
)
func TestDuration(t *testing.T) {
pp := Duration(0)
err := pp.UnmarshalText([]byte("0ms"))
assert.NoError(t, err)
err = pp.UnmarshalText([]byte("yada"))
assert.Error(t, err)
orig := "2ms"
b := []byte(orig)
bj := []byte("\"" + orig + "\"")
err = pp.UnmarshalText(b)
assert.NoError(t, err)
txt, err := pp.MarshalText()
assert.NoError(t, err)
assert.Equal(t, orig, string(txt))
err = pp.UnmarshalJSON(bj)
assert.NoError(t, err)
assert.EqualValues(t, orig, pp.String())
b, err = pp.MarshalJSON()
assert.NoError(t, err)
assert.Equal(t, bj, b)
dur := Duration(42)
bsonData, err := bson.Marshal(&dur)
assert.NoError(t, err)
var durCopy Duration
err = bson.Unmarshal(bsonData, &durCopy)
assert.NoError(t, err)
assert.Equal(t, dur, durCopy)
}
func testDurationParser(t *testing.T, toParse string, expected time.Duration) {
r, e := ParseDuration(toParse)
assert.NoError(t, e)
assert.Equal(t, expected, r)
}
func testDurationSQLScanner(t *testing.T, dur time.Duration) {
values := []interface{}{int64(dur), float64(dur)}
for _, value := range values {
var result Duration
err := result.Scan(value)
assert.NoError(t, err)
assert.Equal(t, dur, time.Duration(result))
}
}
func TestDurationParser(t *testing.T) {
testcases := map[string]time.Duration{
// parse the short forms without spaces
"1ns": 1 * time.Nanosecond,
"1us": 1 * time.Microsecond,
"1µs": 1 * time.Microsecond,
"1ms": 1 * time.Millisecond,
"1s": 1 * time.Second,
"1m": 1 * time.Minute,
"1h": 1 * time.Hour,
"1hr": 1 * time.Hour,
"1d": 24 * time.Hour,
"1w": 7 * 24 * time.Hour,
"1wk": 7 * 24 * time.Hour,
// parse the long forms without spaces
"1nanoseconds": 1 * time.Nanosecond,
"1nanos": 1 * time.Nanosecond,
"1microseconds": 1 * time.Microsecond,
"1micros": 1 * time.Microsecond,
"1millis": 1 * time.Millisecond,
"1milliseconds": 1 * time.Millisecond,
"1second": 1 * time.Second,
"1sec": 1 * time.Second,
"1min": 1 * time.Minute,
"1minute": 1 * time.Minute,
"1hour": 1 * time.Hour,
"1day": 24 * time.Hour,
"1week": 7 * 24 * time.Hour,
// parse the short forms with spaces
"1 ns": 1 * time.Nanosecond,
"1 us": 1 * time.Microsecond,
"1 µs": 1 * time.Microsecond,
"1 ms": 1 * time.Millisecond,
"1 s": 1 * time.Second,
"1 m": 1 * time.Minute,
"1 h": 1 * time.Hour,
"1 hr": 1 * time.Hour,
"1 d": 24 * time.Hour,
"1 w": 7 * 24 * time.Hour,
"1 wk": 7 * 24 * time.Hour,
// parse the long forms without spaces
"1 nanoseconds": 1 * time.Nanosecond,
"1 nanos": 1 * time.Nanosecond,
"1 microseconds": 1 * time.Microsecond,
"1 micros": 1 * time.Microsecond,
"1 millis": 1 * time.Millisecond,
"1 milliseconds": 1 * time.Millisecond,
"1 second": 1 * time.Second,
"1 sec": 1 * time.Second,
"1 min": 1 * time.Minute,
"1 minute": 1 * time.Minute,
"1 hour": 1 * time.Hour,
"1 day": 24 * time.Hour,
"1 week": 7 * 24 * time.Hour,
}
for str, dur := range testcases {
testDurationParser(t, str, dur)
testDurationSQLScanner(t, dur)
}
}

298
vendor/github.com/go-openapi/strfmt/format.go generated vendored Normal file
View file

@ -0,0 +1,298 @@
// Copyright 2015 go-swagger maintainers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package strfmt
import (
"encoding"
"reflect"
"strings"
"sync"
"time"
"github.com/go-openapi/errors"
"github.com/mitchellh/mapstructure"
)
// Default is the default formats registry
var Default = NewSeededFormats(nil, nil)
// Validator represents a validator for a string format
type Validator func(string) bool
// Format represents a string format
type Format interface {
String() string
encoding.TextMarshaler
encoding.TextUnmarshaler
}
// Registry is a registry of string formats
type Registry interface {
Add(string, Format, Validator) bool
DelByName(string) bool
GetType(string) (reflect.Type, bool)
ContainsName(string) bool
Validates(string, string) bool
Parse(string, string) (interface{}, error)
MapStructureHookFunc() mapstructure.DecodeHookFunc
}
type knownFormat struct {
Name string
OrigName string
Type reflect.Type
Validator Validator
}
// NameNormalizer is a function that normalizes a format name
type NameNormalizer func(string) string
// DefaultNameNormalizer removes all dashes
func DefaultNameNormalizer(name string) string {
return strings.Replace(name, "-", "", -1)
}
type defaultFormats struct {
sync.Mutex
data []knownFormat
normalizeName NameNormalizer
}
// NewFormats creates a new formats registry seeded with the values from the default
func NewFormats() Registry {
return NewSeededFormats(Default.(*defaultFormats).data, nil)
}
// NewSeededFormats creates a new formats registry
func NewSeededFormats(seeds []knownFormat, normalizer NameNormalizer) Registry {
if normalizer == nil {
normalizer = DefaultNameNormalizer
}
// copy here, don't modify original
d := append([]knownFormat(nil), seeds...)
return &defaultFormats{
data: d,
normalizeName: normalizer,
}
}
// MapStructureHookFunc is a decode hook function for mapstructure
func (f *defaultFormats) MapStructureHookFunc() mapstructure.DecodeHookFunc {
return func(from reflect.Type, to reflect.Type, data interface{}) (interface{}, error) {
if from.Kind() != reflect.String {
return data, nil
}
for _, v := range f.data {
tpe, _ := f.GetType(v.Name)
if to == tpe {
switch v.Name {
case "date":
d, err := time.Parse(RFC3339FullDate, data.(string))
if err != nil {
return nil, err
}
return Date(d), nil
case "datetime":
return ParseDateTime(data.(string))
case "duration":
dur, err := ParseDuration(data.(string))
if err != nil {
return nil, err
}
return Duration(dur), nil
case "uri":
return URI(data.(string)), nil
case "email":
return Email(data.(string)), nil
case "uuid":
return UUID(data.(string)), nil
case "uuid3":
return UUID3(data.(string)), nil
case "uuid4":
return UUID4(data.(string)), nil
case "uuid5":
return UUID5(data.(string)), nil
case "hostname":
return Hostname(data.(string)), nil
case "ipv4":
return IPv4(data.(string)), nil
case "ipv6":
return IPv6(data.(string)), nil
case "mac":
return MAC(data.(string)), nil
case "isbn":
return ISBN(data.(string)), nil
case "isbn10":
return ISBN10(data.(string)), nil
case "isbn13":
return ISBN13(data.(string)), nil
case "creditcard":
return CreditCard(data.(string)), nil
case "ssn":
return SSN(data.(string)), nil
case "hexcolor":
return HexColor(data.(string)), nil
case "rgbcolor":
return RGBColor(data.(string)), nil
case "byte":
return Base64(data.(string)), nil
case "password":
return Password(data.(string)), nil
default:
return nil, errors.InvalidTypeName(v.Name)
}
}
}
return data, nil
}
}
// Add adds a new format, return true if this was a new item instead of a replacement
func (f *defaultFormats) Add(name string, strfmt Format, validator Validator) bool {
f.Lock()
defer f.Unlock()
nme := f.normalizeName(name)
tpe := reflect.TypeOf(strfmt)
if tpe.Kind() == reflect.Ptr {
tpe = tpe.Elem()
}
for i := range f.data {
v := &f.data[i]
if v.Name == nme {
v.Type = tpe
v.Validator = validator
return false
}
}
// turns out it's new after all
f.data = append(f.data, knownFormat{Name: nme, OrigName: name, Type: tpe, Validator: validator})
return true
}
// GetType gets the type for the specified name
func (f *defaultFormats) GetType(name string) (reflect.Type, bool) {
f.Lock()
defer f.Unlock()
nme := f.normalizeName(name)
for _, v := range f.data {
if v.Name == nme {
return v.Type, true
}
}
return nil, false
}
// DelByName removes the format by the specified name, returns true when an item was actually removed
func (f *defaultFormats) DelByName(name string) bool {
f.Lock()
defer f.Unlock()
nme := f.normalizeName(name)
for i, v := range f.data {
if v.Name == nme {
f.data[i] = knownFormat{} // release
f.data = append(f.data[:i], f.data[i+1:]...)
return true
}
}
return false
}
// DelByType removes the specified format, returns true when an item was actually removed
func (f *defaultFormats) DelByFormat(strfmt Format) bool {
f.Lock()
defer f.Unlock()
tpe := reflect.TypeOf(strfmt)
if tpe.Kind() == reflect.Ptr {
tpe = tpe.Elem()
}
for i, v := range f.data {
if v.Type == tpe {
f.data[i] = knownFormat{} // release
f.data = append(f.data[:i], f.data[i+1:]...)
return true
}
}
return false
}
// ContainsName returns true if this registry contains the specified name
func (f *defaultFormats) ContainsName(name string) bool {
f.Lock()
defer f.Unlock()
nme := f.normalizeName(name)
for _, v := range f.data {
if v.Name == nme {
return true
}
}
return false
}
// ContainsFormat returns true if this registry contains the specified format
func (f *defaultFormats) ContainsFormat(strfmt Format) bool {
f.Lock()
defer f.Unlock()
tpe := reflect.TypeOf(strfmt)
if tpe.Kind() == reflect.Ptr {
tpe = tpe.Elem()
}
for _, v := range f.data {
if v.Type == tpe {
return true
}
}
return false
}
func (f *defaultFormats) Validates(name, data string) bool {
f.Lock()
defer f.Unlock()
nme := f.normalizeName(name)
for _, v := range f.data {
if v.Name == nme {
return v.Validator(data)
}
}
return false
}
func (f *defaultFormats) Parse(name, data string) (interface{}, error) {
f.Lock()
defer f.Unlock()
nme := f.normalizeName(name)
for _, v := range f.data {
if v.Name == nme {
nw := reflect.New(v.Type).Interface()
if dec, ok := nw.(encoding.TextUnmarshaler); ok {
if err := dec.UnmarshalText([]byte(data)); err != nil {
return nil, err
}
return nw, nil
}
return nil, errors.InvalidTypeName(name)
}
}
return nil, errors.InvalidTypeName(name)
}

223
vendor/github.com/go-openapi/strfmt/format_test.go generated vendored Normal file
View file

@ -0,0 +1,223 @@
// Copyright 2015 go-swagger maintainers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package strfmt
import (
"strings"
"testing"
"time"
"github.com/mitchellh/mapstructure"
"github.com/stretchr/testify/assert"
)
type testFormat string
func (t testFormat) MarshalText() ([]byte, error) {
return []byte(string(t)), nil
}
func (t *testFormat) UnmarshalText(b []byte) error {
*t = testFormat(string(b))
return nil
}
func (t testFormat) String() string {
return string(t)
}
func isTestFormat(s string) bool {
return strings.HasPrefix(s, "tf")
}
type tf2 string
func (t tf2) MarshalText() ([]byte, error) {
return []byte(string(t)), nil
}
func (t *tf2) UnmarshalText(b []byte) error {
*t = tf2(string(b))
return nil
}
func istf2(s string) bool {
return strings.HasPrefix(s, "af")
}
func (t tf2) String() string {
return string(t)
}
type bf string
func (t bf) MarshalText() ([]byte, error) {
return []byte(string(t)), nil
}
func (t *bf) UnmarshalText(b []byte) error {
*t = bf(string(b))
return nil
}
func (t bf) String() string {
return string(t)
}
func isbf(s string) bool {
return strings.HasPrefix(s, "bf")
}
func istf3(s string) bool {
return strings.HasPrefix(s, "ff")
}
func init() {
tf := testFormat("")
Default.Add("test-format", &tf, isTestFormat)
}
func TestFormatRegistry(t *testing.T) {
f2 := tf2("")
f3 := bf("")
registry := NewFormats()
assert.True(t, registry.ContainsName("test-format"))
assert.True(t, registry.ContainsName("testformat"))
assert.False(t, registry.ContainsName("ttt"))
assert.True(t, registry.Validates("testformat", "tfa"))
assert.False(t, registry.Validates("testformat", "ffa"))
assert.True(t, registry.Add("tf2", &f2, istf2))
assert.True(t, registry.ContainsName("tf2"))
assert.False(t, registry.ContainsName("tfw"))
assert.True(t, registry.Validates("tf2", "afa"))
assert.False(t, registry.Add("tf2", &f3, isbf))
assert.True(t, registry.ContainsName("tf2"))
assert.False(t, registry.ContainsName("tfw"))
assert.True(t, registry.Validates("tf2", "bfa"))
assert.False(t, registry.Validates("tf2", "afa"))
assert.False(t, registry.Add("tf2", &f2, istf2))
assert.True(t, registry.Add("tf3", &f2, istf3))
assert.True(t, registry.ContainsName("tf3"))
assert.True(t, registry.ContainsName("tf2"))
assert.False(t, registry.ContainsName("tfw"))
assert.True(t, registry.Validates("tf3", "ffa"))
assert.True(t, registry.DelByName("tf3"))
assert.True(t, registry.Add("tf3", &f2, istf3))
assert.True(t, registry.DelByName("tf3"))
assert.False(t, registry.DelByName("unknown"))
assert.False(t, registry.Validates("unknown", ""))
}
type testStruct struct {
D Date `json:"d,omitempty"`
DT DateTime `json:"dt,omitempty"`
Dur Duration `json:"dur,omitempty"`
Uri URI `json:"uri,omitempty"`
Eml Email `json:"eml,omitempty"`
Uuid UUID `json:"uuid,omitempty"`
Uuid3 UUID3 `json:"uuid3,omitempty"`
Uuid4 UUID4 `json:"uuid4,omitempty"`
Uuid5 UUID5 `json:"uuid5,omitempty"`
Hn Hostname `json:"hn,omitempty"`
Ipv4 IPv4 `json:"ipv4,omitempty"`
Ipv6 IPv6 `json:"ipv6,omitempty"`
Mac MAC `json:"mac,omitempty"`
Isbn ISBN `json:"isbn,omitempty"`
Isbn10 ISBN10 `json:"isbn10,omitempty"`
Isbn13 ISBN13 `json:"isbn13,omitempty"`
Creditcard CreditCard `json:"creditcard,omitempty"`
Ssn SSN `json:"ssn,omitempty"`
Hexcolor HexColor `json:"hexcolor,omitempty"`
Rgbcolor RGBColor `json:"rgbcolor,omitempty"`
B64 Base64 `json:"b64,omitempty"`
Pw Password `json:"pw,omitempty"`
}
func TestDecodeHook(t *testing.T) {
registry := NewFormats()
m := map[string]interface{}{
"d": "2014-12-15",
"dt": "2012-03-02T15:06:05.999999999Z",
"dur": "5s",
"uri": "http://www.dummy.com",
"eml": "dummy@dummy.com",
"uuid": "a8098c1a-f86e-11da-bd1a-00112444be1e",
"uuid3": "bcd02e22-68f0-3046-a512-327cca9def8f",
"uuid4": "025b0d74-00a2-4048-bf57-227c5111bb34",
"uuid5": "886313e1-3b8a-5372-9b90-0c9aee199e5d",
"hn": "somewhere.com",
"ipv4": "192.168.254.1",
"ipv6": "::1",
"mac": "01:02:03:04:05:06",
"isbn": "0321751043",
"isbn10": "0321751043",
"isbn13": "978-0321751041",
"hexcolor": "#FFFFFF",
"rgbcolor": "rgb(255,255,255)",
"pw": "super secret stuff here",
"ssn": "111-11-1111",
"creditcard": "4111-1111-1111-1111",
"b64": "ZWxpemFiZXRocG9zZXk=",
}
date, _ := time.Parse(RFC3339FullDate, "2014-12-15")
dur, _ := ParseDuration("5s")
dt, _ := ParseDateTime("2012-03-02T15:06:05.999999999Z")
exp := &testStruct{
D: Date(date),
DT: dt,
Dur: Duration(dur),
Uri: URI("http://www.dummy.com"),
Eml: Email("dummy@dummy.com"),
Uuid: UUID("a8098c1a-f86e-11da-bd1a-00112444be1e"),
Uuid3: UUID3("bcd02e22-68f0-3046-a512-327cca9def8f"),
Uuid4: UUID4("025b0d74-00a2-4048-bf57-227c5111bb34"),
Uuid5: UUID5("886313e1-3b8a-5372-9b90-0c9aee199e5d"),
Hn: Hostname("somewhere.com"),
Ipv4: IPv4("192.168.254.1"),
Ipv6: IPv6("::1"),
Mac: MAC("01:02:03:04:05:06"),
Isbn: ISBN("0321751043"),
Isbn10: ISBN10("0321751043"),
Isbn13: ISBN13("978-0321751041"),
Creditcard: CreditCard("4111-1111-1111-1111"),
Ssn: SSN("111-11-1111"),
Hexcolor: HexColor("#FFFFFF"),
Rgbcolor: RGBColor("rgb(255,255,255)"),
B64: Base64("ZWxpemFiZXRocG9zZXk="),
Pw: Password("super secret stuff here"),
}
test := new(testStruct)
cfg := &mapstructure.DecoderConfig{
DecodeHook: registry.MapStructureHookFunc(),
// weakly typed will pass if this passes
WeaklyTypedInput: false,
Result: test,
}
d, err := mapstructure.NewDecoder(cfg)
assert.Nil(t, err)
err = d.Decode(m)
assert.Nil(t, err)
assert.Equal(t, exp, test)
}

188
vendor/github.com/go-openapi/strfmt/time.go generated vendored Normal file
View file

@ -0,0 +1,188 @@
// Copyright 2015 go-swagger maintainers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package strfmt
import (
"database/sql/driver"
"errors"
"fmt"
"regexp"
"strings"
"time"
"gopkg.in/mgo.v2/bson"
"github.com/mailru/easyjson/jlexer"
"github.com/mailru/easyjson/jwriter"
)
func init() {
dt := DateTime{}
Default.Add("datetime", &dt, IsDateTime)
}
// IsDateTime returns true when the string is a valid date-time
func IsDateTime(str string) bool {
if len(str) < 4 {
return false
}
s := strings.Split(strings.ToLower(str), "t")
if len(s) < 2 || !IsDate(s[0]) {
return false
}
matches := rxDateTime.FindAllStringSubmatch(s[1], -1)
if len(matches) == 0 || len(matches[0]) == 0 {
return false
}
m := matches[0]
res := m[1] <= "23" && m[2] <= "59" && m[3] <= "59"
return res
}
const (
// RFC3339Millis represents a ISO8601 format to millis instead of to nanos
RFC3339Millis = "2006-01-02T15:04:05.000Z07:00"
// RFC3339Micro represents a ISO8601 format to micro instead of to nano
RFC3339Micro = "2006-01-02T15:04:05.000000Z07:00"
// DateTimePattern pattern to match for the date-time format from http://tools.ietf.org/html/rfc3339#section-5.6
DateTimePattern = `^([0-9]{2}):([0-9]{2}):([0-9]{2})(.[0-9]+)?(z|([+-][0-9]{2}:[0-9]{2}))$`
)
var (
dateTimeFormats = []string{RFC3339Micro, RFC3339Millis, time.RFC3339, time.RFC3339Nano}
rxDateTime = regexp.MustCompile(DateTimePattern)
MarshalFormat = RFC3339Millis
)
// ParseDateTime parses a string that represents an ISO8601 time or a unix epoch
func ParseDateTime(data string) (DateTime, error) {
if data == "" {
return NewDateTime(), nil
}
var lastError error
for _, layout := range dateTimeFormats {
dd, err := time.Parse(layout, data)
if err != nil {
lastError = err
continue
}
lastError = nil
return DateTime(dd), nil
}
return DateTime{}, lastError
}
// DateTime is a time but it serializes to ISO8601 format with millis
// It knows how to read 3 different variations of a RFC3339 date time.
// Most APIs we encounter want either millisecond or second precision times.
// This just tries to make it worry-free.
//
// swagger:strfmt date-time
type DateTime time.Time
// NewDateTime is a representation of zero value for DateTime type
func NewDateTime() DateTime {
return DateTime(time.Unix(0, 0).UTC())
}
func (t DateTime) String() string {
return time.Time(t).Format(MarshalFormat)
}
// MarshalText implements the text marshaller interface
func (t DateTime) MarshalText() ([]byte, error) {
return []byte(t.String()), nil
}
// UnmarshalText implements the text unmarshaller interface
func (t *DateTime) UnmarshalText(text []byte) error {
tt, err := ParseDateTime(string(text))
if err != nil {
return err
}
*t = tt
return nil
}
// Scan scans a DateTime value from database driver type.
func (t *DateTime) Scan(raw interface{}) error {
// TODO: case int64: and case float64: ?
switch v := raw.(type) {
case []byte:
return t.UnmarshalText(v)
case string:
return t.UnmarshalText([]byte(v))
case time.Time:
*t = DateTime(v)
case nil:
*t = DateTime{}
default:
return fmt.Errorf("cannot sql.Scan() strfmt.DateTime from: %#v", v)
}
return nil
}
// Value converts DateTime to a primitive value ready to written to a database.
func (t DateTime) Value() (driver.Value, error) {
return driver.Value(t.String()), nil
}
func (t DateTime) MarshalJSON() ([]byte, error) {
var w jwriter.Writer
t.MarshalEasyJSON(&w)
return w.BuildBytes()
}
func (t DateTime) MarshalEasyJSON(w *jwriter.Writer) {
w.String(time.Time(t).Format(MarshalFormat))
}
func (t *DateTime) UnmarshalJSON(data []byte) error {
l := jlexer.Lexer{Data: data}
t.UnmarshalEasyJSON(&l)
return l.Error()
}
func (t *DateTime) UnmarshalEasyJSON(in *jlexer.Lexer) {
if data := in.String(); in.Ok() {
tt, err := ParseDateTime(data)
if err != nil {
in.AddError(err)
return
}
*t = tt
}
}
func (t *DateTime) GetBSON() (interface{}, error) {
return bson.M{"data": t.String()}, nil
}
func (t *DateTime) SetBSON(raw bson.Raw) error {
var m bson.M
if err := raw.Unmarshal(&m); err != nil {
return err
}
if data, ok := m["data"].(string); ok {
var err error
*t, err = ParseDateTime(data)
return err
}
return errors.New("couldn't unmarshal bson raw value as Duration")
}

154
vendor/github.com/go-openapi/strfmt/time_test.go generated vendored Normal file
View file

@ -0,0 +1,154 @@
// Copyright 2015 go-swagger maintainers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package strfmt
import (
"bytes"
"testing"
"time"
"gopkg.in/mgo.v2/bson"
"github.com/stretchr/testify/assert"
)
var (
p, _ = time.Parse(time.RFC3339Nano, "2011-08-18T19:03:37.000000000+01:00")
testCases = []struct {
in []byte // externally sourced data -- to be unmarshalled
time time.Time // its representation in time.Time
str string // its marshalled representation
}{
{[]byte("2014-12-15T08:00:00.000Z"), time.Date(2014, 12, 15, 8, 0, 0, 0, time.UTC), "2014-12-15T08:00:00.000Z"},
{[]byte("2011-08-18T19:03:37.000000000+01:00"), time.Date(2011, 8, 18, 19, 3, 37, 0, p.Location()), "2011-08-18T19:03:37.000+01:00"},
{[]byte("2014-12-15T19:30:20Z"), time.Date(2014, 12, 15, 19, 30, 20, 0, time.UTC), "2014-12-15T19:30:20.000Z"},
{[]byte("0001-01-01T00:00:00Z"), time.Time{}.UTC(), "0001-01-01T00:00:00.000Z"},
{[]byte(""), time.Unix(0, 0).UTC(), "1970-01-01T00:00:00.000Z"},
{[]byte(nil), time.Unix(0, 0).UTC(), "1970-01-01T00:00:00.000Z"},
}
)
func TestNewDateTime(t *testing.T) {
assert.EqualValues(t, time.Unix(0, 0).UTC(), NewDateTime())
}
func TestParseDateTime_errorCases(t *testing.T) {
_, err := ParseDateTime("yada")
assert.Error(t, err)
}
// TestParseDateTime tests the full cycle:
// parsing -> marshalling -> unmarshalling / scanning
func TestParseDateTime_fullCycle(t *testing.T) {
for caseNum, example := range testCases {
t.Logf("Case #%d", caseNum)
parsed, err := ParseDateTime(string(example.in))
assert.NoError(t, err)
assert.EqualValues(t, example.time, parsed)
mt, err := parsed.MarshalText()
assert.NoError(t, err)
assert.Equal(t, []byte(example.str), mt)
pp := NewDateTime()
err = pp.UnmarshalText(mt)
assert.NoError(t, err)
assert.EqualValues(t, example.time, pp)
pp = NewDateTime()
err = pp.Scan(mt)
assert.NoError(t, err)
assert.Equal(t, DateTime(example.time), pp)
}
}
func TestDateTime_UnmarshalText_errorCases(t *testing.T) {
pp := NewDateTime()
err := pp.UnmarshalText([]byte("yada"))
assert.Error(t, err)
err = pp.UnmarshalJSON([]byte("yada"))
assert.Error(t, err)
}
func TestDateTime_UnmarshalText(t *testing.T) {
for caseNum, example := range testCases {
t.Logf("Case #%d", caseNum)
pp := NewDateTime()
err := pp.UnmarshalText(example.in)
assert.NoError(t, err)
assert.EqualValues(t, example.time, pp)
}
}
func TestDateTime_UnmarshalJSON(t *testing.T) {
for caseNum, example := range testCases {
t.Logf("Case #%d", caseNum)
pp := NewDateTime()
err := pp.UnmarshalJSON(esc(example.in))
assert.NoError(t, err)
assert.EqualValues(t, example.time, pp)
}
}
func esc(v []byte) []byte {
var buf bytes.Buffer
buf.WriteByte('"')
buf.Write(v)
buf.WriteByte('"')
return buf.Bytes()
}
func TestDateTime_MarshalText(t *testing.T) {
for caseNum, example := range testCases {
t.Logf("Case #%d", caseNum)
dt := DateTime(example.time)
mt, err := dt.MarshalText()
assert.NoError(t, err)
assert.Equal(t, []byte(example.str), mt)
}
}
func TestDateTime_MarshalJSON(t *testing.T) {
for caseNum, example := range testCases {
t.Logf("Case #%d", caseNum)
dt := DateTime(example.time)
bb, err := dt.MarshalJSON()
assert.NoError(t, err)
assert.EqualValues(t, esc([]byte(example.str)), bb)
}
}
func TestDateTime_Scan(t *testing.T) {
for caseNum, example := range testCases {
t.Logf("Case #%d", caseNum)
pp := NewDateTime()
err := pp.Scan(example.in)
assert.NoError(t, err)
assert.Equal(t, DateTime(example.time), pp)
}
}
func TestDateTime_BSON(t *testing.T) {
for caseNum, example := range testCases {
t.Logf("Case #%d", caseNum)
dt := DateTime(example.time)
bsonData, err := bson.Marshal(&dt)
assert.NoError(t, err)
var dtCopy DateTime
err = bson.Unmarshal(bsonData, &dtCopy)
assert.NoError(t, err)
assert.Equal(t, dt, dtCopy)
}
}