Depenancy upgrades and movign to dep. (#8630)
634
Gopkg.lock
сгенерированный
Обычный файл
@@ -0,0 +1,634 @@
|
||||
# This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'.
|
||||
|
||||
|
||||
[[projects]]
|
||||
name = "github.com/NYTimes/gziphandler"
|
||||
packages = ["."]
|
||||
revision = "2600fb119af974220d3916a5916d6e31176aac1b"
|
||||
version = "v1.0.1"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/alecthomas/log4go"
|
||||
packages = ["."]
|
||||
revision = "9c17fbb2767ccbdda78584f28d545c44a4b29c4f"
|
||||
source = "https://github.com/mattermost/log4go.git"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/armon/go-metrics"
|
||||
packages = ["."]
|
||||
revision = "783273d703149aaeb9897cf58613d5af48861c25"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/avct/uasurfer"
|
||||
packages = ["."]
|
||||
revision = "c4be5581ec9617d04f5c5e02b893903ead0b1eed"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/beorn7/perks"
|
||||
packages = ["quantile"]
|
||||
revision = "3a771d992973f24aa725d07868b467d1ddfceafb"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/corpix/uarand"
|
||||
packages = ["."]
|
||||
revision = "2b8494104d86337cdd41d0a49cbed8e4583c0ab4"
|
||||
|
||||
[[projects]]
|
||||
name = "github.com/davecgh/go-spew"
|
||||
packages = ["spew"]
|
||||
revision = "346938d642f2ec3594ed81d874461961cd0faa76"
|
||||
version = "v1.1.0"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/dgryski/dgoogauth"
|
||||
packages = ["."]
|
||||
revision = "fd153d5969d30bd701e10f3530228f001213047c"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/dimchansky/utfbom"
|
||||
packages = ["."]
|
||||
revision = "6c6132ff69f0f6c088739067407b5d32c52e1d0f"
|
||||
|
||||
[[projects]]
|
||||
name = "github.com/disintegration/imaging"
|
||||
packages = ["."]
|
||||
revision = "fd34ef7671b12cdf1b024d98c6b327b2770d32c4"
|
||||
version = "v1.4.1"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/dustin/go-humanize"
|
||||
packages = ["."]
|
||||
revision = "bb3d318650d48840a39aa21a027c6630e198e626"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/dyatlov/go-opengraph"
|
||||
packages = ["opengraph"]
|
||||
revision = "5e37bb1414a6ab485690294c2f5a3bbad4488e49"
|
||||
|
||||
[[projects]]
|
||||
name = "github.com/fsnotify/fsnotify"
|
||||
packages = ["."]
|
||||
revision = "c2828203cd70a50dcccfb2761f8b1f8ceef9a8e9"
|
||||
version = "v1.4.7"
|
||||
|
||||
[[projects]]
|
||||
name = "github.com/go-ini/ini"
|
||||
packages = ["."]
|
||||
revision = "ace140f73450505f33e8b8418216792275ae82a7"
|
||||
version = "v1.35.0"
|
||||
|
||||
[[projects]]
|
||||
name = "github.com/go-ldap/ldap"
|
||||
packages = ["."]
|
||||
revision = "bb7a9ca6e4fbc2129e3db588a34bc970ffe811a9"
|
||||
version = "v2.5.1"
|
||||
|
||||
[[projects]]
|
||||
name = "github.com/go-redis/redis"
|
||||
packages = [
|
||||
".",
|
||||
"internal",
|
||||
"internal/consistenthash",
|
||||
"internal/hashtag",
|
||||
"internal/pool",
|
||||
"internal/proto",
|
||||
"internal/singleflight",
|
||||
"internal/util"
|
||||
]
|
||||
revision = "877867d2845fbaf86798befe410b6ceb6f5c29a3"
|
||||
version = "v6.10.2"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/go-sql-driver/mysql"
|
||||
packages = ["."]
|
||||
revision = "3287d94d4c6a48a63e16fffaabf27ab20203af2a"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/golang/freetype"
|
||||
packages = [
|
||||
".",
|
||||
"raster",
|
||||
"truetype"
|
||||
]
|
||||
revision = "e2365dfdc4a05e4b8299a783240d4a7d5a65d4e4"
|
||||
|
||||
[[projects]]
|
||||
name = "github.com/golang/protobuf"
|
||||
packages = ["proto"]
|
||||
revision = "925541529c1fa6821df4e44ce2723319eb2be768"
|
||||
version = "v1.0.0"
|
||||
|
||||
[[projects]]
|
||||
name = "github.com/gorilla/context"
|
||||
packages = ["."]
|
||||
revision = "1ea25387ff6f684839d82767c1733ff4d4d15d0a"
|
||||
version = "v1.1"
|
||||
|
||||
[[projects]]
|
||||
name = "github.com/gorilla/handlers"
|
||||
packages = ["."]
|
||||
revision = "90663712d74cb411cbef281bc1e08c19d1a76145"
|
||||
version = "v1.3.0"
|
||||
|
||||
[[projects]]
|
||||
name = "github.com/gorilla/mux"
|
||||
packages = ["."]
|
||||
revision = "53c1911da2b537f792e7cafcb446b05ffe33b996"
|
||||
version = "v1.6.1"
|
||||
|
||||
[[projects]]
|
||||
name = "github.com/gorilla/schema"
|
||||
packages = ["."]
|
||||
revision = "d0e4c24cff97ae983e9847e0ed5a02dc10013d41"
|
||||
version = "v1.0.2"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/gorilla/websocket"
|
||||
packages = ["."]
|
||||
revision = "eb925808374e5ca90c83401a40d711dc08c0c0f6"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/hako/durafmt"
|
||||
packages = ["."]
|
||||
revision = "987f93c94e473e74aadc826871e61ae6b3360ebb"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/hashicorp/errwrap"
|
||||
packages = ["."]
|
||||
revision = "7554cd9344cec97297fa6649b055a8c98c2a1e55"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/hashicorp/go-immutable-radix"
|
||||
packages = ["."]
|
||||
revision = "7f3cd4390caab3250a57f30efdb2a65dd7649ecf"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/hashicorp/go-msgpack"
|
||||
packages = ["codec"]
|
||||
revision = "fa3f63826f7c23912c15263591e65d54d080b458"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/hashicorp/go-multierror"
|
||||
packages = ["."]
|
||||
revision = "b7773ae218740a7be65057fc60b366a49b538a44"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/hashicorp/go-sockaddr"
|
||||
packages = ["."]
|
||||
revision = "6d291a969b86c4b633730bfc6b8b9d64c3aafed9"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/hashicorp/golang-lru"
|
||||
packages = [
|
||||
".",
|
||||
"simplelru"
|
||||
]
|
||||
revision = "0fb14efe8c47ae851c0034ed7a448854d3d34cf3"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/hashicorp/hcl"
|
||||
packages = [
|
||||
".",
|
||||
"hcl/ast",
|
||||
"hcl/parser",
|
||||
"hcl/printer",
|
||||
"hcl/scanner",
|
||||
"hcl/strconv",
|
||||
"hcl/token",
|
||||
"json/parser",
|
||||
"json/scanner",
|
||||
"json/token"
|
||||
]
|
||||
revision = "ef8a98b0bbce4a65b5aa4c368430a80ddc533168"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/hashicorp/memberlist"
|
||||
packages = ["."]
|
||||
revision = "2288bf30e9c8d7b5f6549bf62e07120d72fd4b6c"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/icrowley/fake"
|
||||
packages = ["."]
|
||||
revision = "4178557ae428460c3780a381c824a1f3aceb6325"
|
||||
|
||||
[[projects]]
|
||||
name = "github.com/inconshreveable/mousetrap"
|
||||
packages = ["."]
|
||||
revision = "76626ae9c91c4f2a10f34cad8ce83ea42c93bb75"
|
||||
version = "v1.0"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/jehiah/go-strftime"
|
||||
packages = ["."]
|
||||
revision = "1d33003b386959af197ba96475f198c114627b5e"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/lib/pq"
|
||||
packages = [
|
||||
".",
|
||||
"oid"
|
||||
]
|
||||
revision = "d34b9ff171c21ad295489235aec8b6626023cd04"
|
||||
|
||||
[[projects]]
|
||||
name = "github.com/magiconair/properties"
|
||||
packages = ["."]
|
||||
revision = "c3beff4c2358b44d0493c7dda585e7db7ff28ae6"
|
||||
version = "v1.7.6"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/mailru/easyjson"
|
||||
packages = [
|
||||
".",
|
||||
"buffer",
|
||||
"jlexer",
|
||||
"jwriter"
|
||||
]
|
||||
revision = "8b799c424f57fa123fc63a99d6383bc6e4c02578"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/mattermost/gorp"
|
||||
packages = ["."]
|
||||
revision = "520a119fe3536337cf8feeaf76afae0f5ae193f1"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/mattermost/html2text"
|
||||
packages = ["."]
|
||||
revision = "d47a5532a7bc36ad7b2b8ec3eebe24e975154f94"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/mattermost/rsc"
|
||||
packages = [
|
||||
"gf256",
|
||||
"qr",
|
||||
"qr/coding"
|
||||
]
|
||||
revision = "bbaefb05eaa0389ea712340066837c8ce4d287f9"
|
||||
|
||||
[[projects]]
|
||||
name = "github.com/matttproud/golang_protobuf_extensions"
|
||||
packages = ["pbutil"]
|
||||
revision = "3247c84500bff8d9fb6d579d800f20b3e091582c"
|
||||
version = "v1.0.0"
|
||||
|
||||
[[projects]]
|
||||
name = "github.com/miekg/dns"
|
||||
packages = ["."]
|
||||
revision = "83c435cc65d2862736428b9b4d07d0ab10ad3e4d"
|
||||
version = "v1.0.5"
|
||||
|
||||
[[projects]]
|
||||
branch = "minio-temporary-fixes"
|
||||
name = "github.com/minio/minio-go"
|
||||
packages = [
|
||||
".",
|
||||
"pkg/credentials",
|
||||
"pkg/encrypt",
|
||||
"pkg/policy",
|
||||
"pkg/s3signer",
|
||||
"pkg/s3utils",
|
||||
"pkg/set"
|
||||
]
|
||||
revision = "e30d3b9eaff9a3fbfa74cda4c56cb22bec264ffa"
|
||||
source = "https://github.com/mattermost/minio-go.git"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/mitchellh/go-homedir"
|
||||
packages = ["."]
|
||||
revision = "b8bc1bf767474819792c23f32d8286a45736f1c6"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/mitchellh/mapstructure"
|
||||
packages = ["."]
|
||||
revision = "00c29f56e2386353d58c599509e8dc3801b0d716"
|
||||
|
||||
[[projects]]
|
||||
name = "github.com/nicksnyder/go-i18n"
|
||||
packages = [
|
||||
"i18n",
|
||||
"i18n/bundle",
|
||||
"i18n/language",
|
||||
"i18n/translation"
|
||||
]
|
||||
revision = "0dc1626d56435e9d605a29875701721c54bc9bbd"
|
||||
version = "v1.10.0"
|
||||
|
||||
[[projects]]
|
||||
name = "github.com/pborman/uuid"
|
||||
packages = ["."]
|
||||
revision = "e790cca94e6cc75c7064b1332e63811d4aae1a53"
|
||||
version = "v1.1"
|
||||
|
||||
[[projects]]
|
||||
name = "github.com/pelletier/go-toml"
|
||||
packages = ["."]
|
||||
revision = "acdc4509485b587f5e675510c4f2c63e90ff68a8"
|
||||
version = "v1.1.0"
|
||||
|
||||
[[projects]]
|
||||
name = "github.com/pkg/errors"
|
||||
packages = ["."]
|
||||
revision = "645ef00459ed84a119197bfb8d8205042c6df63d"
|
||||
version = "v0.8.0"
|
||||
|
||||
[[projects]]
|
||||
name = "github.com/pmezard/go-difflib"
|
||||
packages = ["difflib"]
|
||||
revision = "792786c7400a136282c1664665ae0a8db921c6c2"
|
||||
version = "v1.0.0"
|
||||
|
||||
[[projects]]
|
||||
name = "github.com/prometheus/client_golang"
|
||||
packages = [
|
||||
"prometheus",
|
||||
"prometheus/promhttp"
|
||||
]
|
||||
revision = "c5b7fccd204277076155f10851dad72b76a49317"
|
||||
version = "v0.8.0"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/prometheus/client_model"
|
||||
packages = ["go"]
|
||||
revision = "99fa1f4be8e564e8a6b613da7fa6f46c9edafc6c"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/prometheus/common"
|
||||
packages = [
|
||||
"expfmt",
|
||||
"internal/bitbucket.org/ww/goautoneg",
|
||||
"model"
|
||||
]
|
||||
revision = "d0f7cd64bda49e08b22ae8a730aa57aa0db125d6"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/prometheus/procfs"
|
||||
packages = [
|
||||
".",
|
||||
"internal/util",
|
||||
"nfs",
|
||||
"xfs"
|
||||
]
|
||||
revision = "8b1c2da0d56deffdbb9e48d4414b4e674bd8083e"
|
||||
|
||||
[[projects]]
|
||||
branch = "go1"
|
||||
name = "github.com/rwcarlsen/goexif"
|
||||
packages = [
|
||||
"exif",
|
||||
"tiff"
|
||||
]
|
||||
revision = "fb35d3c3290d09f3524b684b5d42d0063c227158"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/sean-/seed"
|
||||
packages = ["."]
|
||||
revision = "e2103e2c35297fb7e17febb81e49b312087a2372"
|
||||
|
||||
[[projects]]
|
||||
name = "github.com/segmentio/analytics-go"
|
||||
packages = ["."]
|
||||
revision = "2d840d861c322bdf5346ba7917af1c2285e653d3"
|
||||
version = "2.1.1"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/segmentio/backo-go"
|
||||
packages = ["."]
|
||||
revision = "204274ad699c0983a70203a566887f17a717fef4"
|
||||
|
||||
[[projects]]
|
||||
name = "github.com/sirupsen/logrus"
|
||||
packages = ["."]
|
||||
revision = "c155da19408a8799da419ed3eeb0cb5db0ad5dbc"
|
||||
version = "v1.0.5"
|
||||
|
||||
[[projects]]
|
||||
name = "github.com/spf13/afero"
|
||||
packages = [
|
||||
".",
|
||||
"mem"
|
||||
]
|
||||
revision = "63644898a8da0bc22138abf860edaf5277b6102e"
|
||||
version = "v1.1.0"
|
||||
|
||||
[[projects]]
|
||||
name = "github.com/spf13/cast"
|
||||
packages = ["."]
|
||||
revision = "8965335b8c7107321228e3e3702cab9832751bac"
|
||||
version = "v1.2.0"
|
||||
|
||||
[[projects]]
|
||||
name = "github.com/spf13/cobra"
|
||||
packages = ["."]
|
||||
revision = "a1f051bc3eba734da4772d60e2d677f47cf93ef4"
|
||||
version = "v0.0.2"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/spf13/jwalterweatherman"
|
||||
packages = ["."]
|
||||
revision = "7c0cea34c8ece3fbeb2b27ab9b59511d360fb394"
|
||||
|
||||
[[projects]]
|
||||
name = "github.com/spf13/pflag"
|
||||
packages = ["."]
|
||||
revision = "583c0c0531f06d5278b7d917446061adc344b5cd"
|
||||
version = "v1.0.1"
|
||||
|
||||
[[projects]]
|
||||
branch = "env-settings"
|
||||
name = "github.com/spf13/viper"
|
||||
packages = ["."]
|
||||
revision = "4f5003aa93559718c866d86fbc795439079484f5"
|
||||
source = "https://github.com/mattermost/viper"
|
||||
|
||||
[[projects]]
|
||||
name = "github.com/stretchr/objx"
|
||||
packages = ["."]
|
||||
revision = "facf9a85c22f48d2f52f2380e4efce1768749a89"
|
||||
version = "v0.1"
|
||||
|
||||
[[projects]]
|
||||
name = "github.com/stretchr/testify"
|
||||
packages = [
|
||||
"assert",
|
||||
"mock",
|
||||
"require",
|
||||
"suite"
|
||||
]
|
||||
revision = "12b6f73e6084dad08a7c6e575284b177ecafbc71"
|
||||
version = "v1.2.1"
|
||||
|
||||
[[projects]]
|
||||
name = "github.com/tylerb/graceful"
|
||||
packages = ["."]
|
||||
revision = "4654dfbb6ad53cb5e27f37d99b02e16c1872fbbb"
|
||||
version = "v1.2.15"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/xtgo/uuid"
|
||||
packages = ["."]
|
||||
revision = "a0b114877d4caeffbd7f87e3757c17fce570fea7"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "golang.org/x/crypto"
|
||||
packages = [
|
||||
"acme",
|
||||
"acme/autocert",
|
||||
"bcrypt",
|
||||
"blowfish",
|
||||
"ed25519",
|
||||
"ed25519/internal/edwards25519",
|
||||
"ssh/terminal"
|
||||
]
|
||||
revision = "d6449816ce06963d9d136eee5a56fca5b0616e7e"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "golang.org/x/image"
|
||||
packages = [
|
||||
"bmp",
|
||||
"font",
|
||||
"math/fixed",
|
||||
"tiff",
|
||||
"tiff/lzw"
|
||||
]
|
||||
revision = "f315e440302883054d0c2bd85486878cb4f8572c"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "golang.org/x/net"
|
||||
packages = [
|
||||
"bpf",
|
||||
"html",
|
||||
"html/atom",
|
||||
"idna",
|
||||
"internal/iana",
|
||||
"internal/socket",
|
||||
"ipv4",
|
||||
"ipv6",
|
||||
"lex/httplex"
|
||||
]
|
||||
revision = "61147c48b25b599e5b561d2e9c4f3e1ef489ca41"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "golang.org/x/sys"
|
||||
packages = [
|
||||
"unix",
|
||||
"windows"
|
||||
]
|
||||
revision = "2281fa97ef7b0c26324634d5a22f04babdac8713"
|
||||
|
||||
[[projects]]
|
||||
name = "golang.org/x/text"
|
||||
packages = [
|
||||
"collate",
|
||||
"collate/build",
|
||||
"internal/colltab",
|
||||
"internal/gen",
|
||||
"internal/tag",
|
||||
"internal/triegen",
|
||||
"internal/ucd",
|
||||
"language",
|
||||
"secure/bidirule",
|
||||
"transform",
|
||||
"unicode/bidi",
|
||||
"unicode/cldr",
|
||||
"unicode/norm",
|
||||
"unicode/rangetable"
|
||||
]
|
||||
revision = "f21a4dfb5e38f5895301dc265a8def02365cc3d0"
|
||||
version = "v0.3.0"
|
||||
|
||||
[[projects]]
|
||||
name = "google.golang.org/appengine"
|
||||
packages = ["cloudsql"]
|
||||
revision = "150dc57a1b433e64154302bdc40b6bb8aefa313a"
|
||||
version = "v1.0.0"
|
||||
|
||||
[[projects]]
|
||||
branch = "v3"
|
||||
name = "gopkg.in/alexcesaro/quotedprintable.v3"
|
||||
packages = ["."]
|
||||
revision = "2caba252f4dc53eaf6b553000885530023f54623"
|
||||
|
||||
[[projects]]
|
||||
name = "gopkg.in/asn1-ber.v1"
|
||||
packages = ["."]
|
||||
revision = "379148ca0225df7a432012b8df0355c2a2063ac0"
|
||||
version = "v1.2"
|
||||
|
||||
[[projects]]
|
||||
name = "gopkg.in/gomail.v2"
|
||||
packages = ["."]
|
||||
revision = "41f3572897373c5538c50a2402db15db079fa4fd"
|
||||
version = "2.0.0"
|
||||
|
||||
[[projects]]
|
||||
name = "gopkg.in/olivere/elastic.v5"
|
||||
packages = [
|
||||
".",
|
||||
"config",
|
||||
"uritemplates"
|
||||
]
|
||||
revision = "dbe820f35164384c998099db63481b583d53f73b"
|
||||
version = "v5.0.66"
|
||||
|
||||
[[projects]]
|
||||
name = "gopkg.in/throttled/throttled.v2"
|
||||
packages = [
|
||||
".",
|
||||
"store/memstore"
|
||||
]
|
||||
revision = "b5675e93f9d999b22f92d859a5bf2138d3641af4"
|
||||
version = "v2.0.3"
|
||||
|
||||
[[projects]]
|
||||
name = "gopkg.in/yaml.v2"
|
||||
packages = ["."]
|
||||
revision = "5420a8b6744d3b0345ab293f6fcba19c978f1183"
|
||||
version = "v2.2.1"
|
||||
|
||||
[solve-meta]
|
||||
analyzer-name = "dep"
|
||||
analyzer-version = 1
|
||||
inputs-digest = "f36b25467f915a202bda7828b5e285c64ab7a1ed7c2582dd921be6a1d066150d"
|
||||
solver-name = "gps-cdcl"
|
||||
solver-version = 1
|
||||
73
Gopkg.toml
Обычный файл
@@ -0,0 +1,73 @@
|
||||
# Gopkg.toml example
|
||||
#
|
||||
# Refer to https://github.com/golang/dep/blob/master/docs/Gopkg.toml.md
|
||||
# for detailed Gopkg.toml documentation.
|
||||
#
|
||||
# required = ["github.com/user/thing/cmd/thing"]
|
||||
# ignored = ["github.com/user/project/pkgX", "bitbucket.org/user/project/pkgA/pkgY"]
|
||||
#
|
||||
# [[constraint]]
|
||||
# name = "github.com/user/project"
|
||||
# version = "1.0.0"
|
||||
#
|
||||
# [[constraint]]
|
||||
# name = "github.com/user/project2"
|
||||
# branch = "dev"
|
||||
# source = "github.com/myfork/project2"
|
||||
#
|
||||
# [[override]]
|
||||
# name = "github.com/x/y"
|
||||
# version = "2.4.0"
|
||||
#
|
||||
# [prune]
|
||||
# non-go = false
|
||||
# go-tests = true
|
||||
# unused-packages = true
|
||||
|
||||
|
||||
# To use our own fork
|
||||
[[constraint]]
|
||||
name = "github.com/alecthomas/log4go"
|
||||
branch = "master"
|
||||
source = "https://github.com/mattermost/log4go.git"
|
||||
|
||||
# To keep us on latest since maintainer stopped releasing versions
|
||||
[[constraint]]
|
||||
name = "github.com/go-sql-driver/mysql"
|
||||
branch = "master"
|
||||
|
||||
# Constaint to bring us to latest master for bug fixes
|
||||
[[constraint]]
|
||||
name = "github.com/gorilla/websocket"
|
||||
branch = "master"
|
||||
|
||||
# To keep us on latest since maintainer stopped releasing versions
|
||||
[[constraint]]
|
||||
name = "github.com/hashicorp/memberlist"
|
||||
branch = "master"
|
||||
|
||||
# To avoid pulling old gorp version, we use master of our fork
|
||||
[[constraint]]
|
||||
name = "github.com/mattermost/gorp"
|
||||
branch = "master"
|
||||
|
||||
# To use our fork
|
||||
[[constraint]]
|
||||
name = "github.com/minio/minio-go"
|
||||
source = "https://github.com/mattermost/minio-go.git"
|
||||
version = "4.0.7.1"
|
||||
|
||||
# Fork for adding our own method to viper EnvSettings
|
||||
[[constraint]]
|
||||
name = "github.com/spf13/viper"
|
||||
source = "https://github.com/mattermost/viper"
|
||||
branch = "env-settings"
|
||||
|
||||
# Keep back because of breaking API changes
|
||||
[[constraint]]
|
||||
name = "github.com/segmentio/analytics-go"
|
||||
version = "2.1.1"
|
||||
|
||||
[prune]
|
||||
go-tests = true
|
||||
unused-packages = true
|
||||
289
glide.lock
сгенерированный
@@ -1,289 +0,0 @@
|
||||
hash: 7d775d1a082e77da96bee605ebea97ba0230e270f7169fade50f64e5fe7842cb
|
||||
updated: 2018-04-05T18:31:48.282177324+02:00
|
||||
imports:
|
||||
- name: github.com/alecthomas/log4go
|
||||
version: 3fbce08846379ec7f4f6bc7fce6dd01ce28fae4c
|
||||
repo: https://github.com/mattermost/log4go.git
|
||||
- name: github.com/armon/go-metrics
|
||||
version: 7aa49fde808223f8dadfdbfd3a20ff6c19e5f9ec
|
||||
- name: github.com/avct/uasurfer
|
||||
version: c4be5581ec9617d04f5c5e02b893903ead0b1eed
|
||||
- name: github.com/beorn7/perks
|
||||
version: 4c0e84591b9aa9e6dcfdf3e020114cd81f89d5f9
|
||||
subpackages:
|
||||
- quantile
|
||||
- name: github.com/corpix/uarand
|
||||
version: 2b8494104d86337cdd41d0a49cbed8e4583c0ab4
|
||||
- name: github.com/davecgh/go-spew
|
||||
version: 87df7c60d5820d0f8ae11afede5aa52325c09717
|
||||
subpackages:
|
||||
- spew
|
||||
- name: github.com/dgryski/dgoogauth
|
||||
version: fd153d5969d30bd701e10f3530228f001213047c
|
||||
- name: github.com/dimchansky/utfbom
|
||||
version: 6c6132ff69f0f6c088739067407b5d32c52e1d0f
|
||||
- name: github.com/disintegration/imaging
|
||||
version: 1884593a19ddc6f2ea050403430d02c1d0fc1283
|
||||
- name: github.com/dyatlov/go-opengraph
|
||||
version: 41a3523719dfbe7e8f853fbd4061867543db5270
|
||||
subpackages:
|
||||
- opengraph
|
||||
- name: github.com/fsnotify/fsnotify
|
||||
version: c2828203cd70a50dcccfb2761f8b1f8ceef9a8e9
|
||||
- name: github.com/go-ini/ini
|
||||
version: 32e4be5f41bb918afb6e37c07426e2ddbcb6647e
|
||||
- name: github.com/go-ldap/ldap
|
||||
version: bb7a9ca6e4fbc2129e3db588a34bc970ffe811a9
|
||||
- name: github.com/go-redis/redis
|
||||
version: 8b4fa6d443e35ca8b1c37be877285252430b06a3
|
||||
subpackages:
|
||||
- internal
|
||||
- internal/consistenthash
|
||||
- internal/hashtag
|
||||
- internal/pool
|
||||
- internal/proto
|
||||
- name: github.com/go-sql-driver/mysql
|
||||
version: bc14601d1bd56421dd60f561e6052c9ed77f9daf
|
||||
- name: github.com/golang/freetype
|
||||
version: e2365dfdc4a05e4b8299a783240d4a7d5a65d4e4
|
||||
subpackages:
|
||||
- raster
|
||||
- truetype
|
||||
- name: github.com/golang/protobuf
|
||||
version: bbd03ef6da3a115852eaf24c8a1c46aeb39aa175
|
||||
subpackages:
|
||||
- proto
|
||||
- name: github.com/gorilla/context
|
||||
version: 08b5f424b9271eedf6f9f0ce86cb9396ed337a42
|
||||
- name: github.com/gorilla/handlers
|
||||
version: 90663712d74cb411cbef281bc1e08c19d1a76145
|
||||
- name: github.com/gorilla/mux
|
||||
version: 53c1911da2b537f792e7cafcb446b05ffe33b996
|
||||
- name: github.com/gorilla/schema
|
||||
version: afe77393c53b66afe9212810d9b2013859d04ae6
|
||||
- name: github.com/gorilla/websocket
|
||||
version: 4ac909741dfa57448bfadfdbca0cf7eeaa68f0e2
|
||||
- name: github.com/hako/durafmt
|
||||
version: 987f93c94e473e74aadc826871e61ae6b3360ebb
|
||||
- name: github.com/hashicorp/errwrap
|
||||
version: 7554cd9344cec97297fa6649b055a8c98c2a1e55
|
||||
- name: github.com/hashicorp/go-immutable-radix
|
||||
version: 7f3cd4390caab3250a57f30efdb2a65dd7649ecf
|
||||
- name: github.com/hashicorp/go-msgpack
|
||||
version: fa3f63826f7c23912c15263591e65d54d080b458
|
||||
subpackages:
|
||||
- codec
|
||||
- name: github.com/hashicorp/go-multierror
|
||||
version: b7773ae218740a7be65057fc60b366a49b538a44
|
||||
- name: github.com/hashicorp/go-sockaddr
|
||||
version: 7165ee14aff120ee3642aa2bcf2dea8eebef29c3
|
||||
- name: github.com/hashicorp/golang-lru
|
||||
version: 0fb14efe8c47ae851c0034ed7a448854d3d34cf3
|
||||
subpackages:
|
||||
- simplelru
|
||||
- name: github.com/hashicorp/hcl
|
||||
version: 23c074d0eceb2b8a5bfdbb271ab780cde70f05a8
|
||||
subpackages:
|
||||
- hcl/ast
|
||||
- hcl/parser
|
||||
- hcl/printer
|
||||
- hcl/scanner
|
||||
- hcl/strconv
|
||||
- hcl/token
|
||||
- json/parser
|
||||
- json/scanner
|
||||
- json/token
|
||||
- name: github.com/hashicorp/memberlist
|
||||
version: 2288bf30e9c8d7b5f6549bf62e07120d72fd4b6c
|
||||
- name: github.com/icrowley/fake
|
||||
version: 4178557ae428460c3780a381c824a1f3aceb6325
|
||||
- name: github.com/inconshreveable/mousetrap
|
||||
version: 76626ae9c91c4f2a10f34cad8ce83ea42c93bb75
|
||||
- name: github.com/jehiah/go-strftime
|
||||
version: 834e15c05a45371503440cc195bbd05c9a0968d9
|
||||
- name: github.com/lib/pq
|
||||
version: 88edab0803230a3898347e77b474f8c1820a1f20
|
||||
subpackages:
|
||||
- oid
|
||||
- name: github.com/magiconair/properties
|
||||
version: c3beff4c2358b44d0493c7dda585e7db7ff28ae6
|
||||
- name: github.com/mailru/easyjson
|
||||
version: 32fa128f234d041f196a9f3e0fea5ac9772c08e1
|
||||
subpackages:
|
||||
- buffer
|
||||
- jlexer
|
||||
- jwriter
|
||||
- name: github.com/mattermost/gorp
|
||||
version: 995ddf2264c4ad45fbaf342f7500e4787ebae84a
|
||||
- name: github.com/mattermost/html2text
|
||||
version: d47a5532a7bc36ad7b2b8ec3eebe24e975154f94
|
||||
- name: github.com/mattermost/minio-go
|
||||
version: e30d3b9eaff9a3fbfa74cda4c56cb22bec264ffa
|
||||
- name: github.com/mattermost/rsc
|
||||
version: bbaefb05eaa0389ea712340066837c8ce4d287f9
|
||||
subpackages:
|
||||
- gf256
|
||||
- qr
|
||||
- qr/coding
|
||||
- name: github.com/matttproud/golang_protobuf_extensions
|
||||
version: c12348ce28de40eed0136aa2b644d0ee0650e56c
|
||||
subpackages:
|
||||
- pbutil
|
||||
- name: github.com/miekg/dns
|
||||
version: 5364553f1ee9cddc7ac8b62dce148309c386695b
|
||||
- name: github.com/minio/minio-go
|
||||
version: e30d3b9eaff9a3fbfa74cda4c56cb22bec264ffa
|
||||
repo: https://github.com/mattermost/minio-go.git
|
||||
subpackages:
|
||||
- pkg/credentials
|
||||
- pkg/encrypt
|
||||
- pkg/policy
|
||||
- pkg/s3signer
|
||||
- pkg/s3utils
|
||||
- pkg/set
|
||||
- name: github.com/mitchellh/go-homedir
|
||||
version: b8bc1bf767474819792c23f32d8286a45736f1c6
|
||||
- name: github.com/mitchellh/mapstructure
|
||||
version: a4e142e9c047c904fa2f1e144d9a84e6133024bc
|
||||
- name: github.com/nicksnyder/go-i18n
|
||||
version: 0dc1626d56435e9d605a29875701721c54bc9bbd
|
||||
subpackages:
|
||||
- i18n
|
||||
- i18n/bundle
|
||||
- i18n/language
|
||||
- i18n/translation
|
||||
- name: github.com/NYTimes/gziphandler
|
||||
version: 289a3b81f5aedc99f8d6eb0f67827c142f1310d8
|
||||
- name: github.com/olivere/elastic
|
||||
version: e852184f51320ab81f9401428bec78e9ffe1355a
|
||||
subpackages:
|
||||
- config
|
||||
- uritemplates
|
||||
- name: github.com/pborman/uuid
|
||||
version: e790cca94e6cc75c7064b1332e63811d4aae1a53
|
||||
- name: github.com/pelletier/go-toml
|
||||
version: acdc4509485b587f5e675510c4f2c63e90ff68a8
|
||||
- name: github.com/pkg/errors
|
||||
version: 645ef00459ed84a119197bfb8d8205042c6df63d
|
||||
- name: github.com/pmezard/go-difflib
|
||||
version: 792786c7400a136282c1664665ae0a8db921c6c2
|
||||
subpackages:
|
||||
- difflib
|
||||
- name: github.com/prometheus/client_golang
|
||||
version: fcc130e101e76c5d303513d0e28f4b6d732845c7
|
||||
subpackages:
|
||||
- prometheus
|
||||
- prometheus/promhttp
|
||||
- name: github.com/prometheus/client_model
|
||||
version: 99fa1f4be8e564e8a6b613da7fa6f46c9edafc6c
|
||||
subpackages:
|
||||
- go
|
||||
- name: github.com/prometheus/common
|
||||
version: 89604d197083d4781071d3c65855d24ecfb0a563
|
||||
subpackages:
|
||||
- expfmt
|
||||
- internal/bitbucket.org/ww/goautoneg
|
||||
- model
|
||||
- name: github.com/prometheus/procfs
|
||||
version: 282c8707aa210456a825798969cc27edda34992a
|
||||
subpackages:
|
||||
- internal/util
|
||||
- nfs
|
||||
- xfs
|
||||
- name: github.com/rwcarlsen/goexif
|
||||
version: 17202558c8d9c3fd047859f1a5e73fd9ae709187
|
||||
subpackages:
|
||||
- exif
|
||||
- tiff
|
||||
- name: github.com/sean-/seed
|
||||
version: e2103e2c35297fb7e17febb81e49b312087a2372
|
||||
- name: github.com/segmentio/analytics-go
|
||||
version: 2d840d861c322bdf5346ba7917af1c2285e653d3
|
||||
- name: github.com/segmentio/backo-go
|
||||
version: 204274ad699c0983a70203a566887f17a717fef4
|
||||
- name: github.com/spf13/afero
|
||||
version: bbf41cb36dffe15dff5bf7e18c447801e7ffe163
|
||||
subpackages:
|
||||
- mem
|
||||
- name: github.com/spf13/cast
|
||||
version: 8965335b8c7107321228e3e3702cab9832751bac
|
||||
- name: github.com/spf13/cobra
|
||||
version: 4f5003aa93559718c866d86fbc795439079484f5
|
||||
- name: github.com/spf13/jwalterweatherman
|
||||
version: 7c0cea34c8ece3fbeb2b27ab9b59511d360fb394
|
||||
- name: github.com/spf13/pflag
|
||||
version: 6a877ebacf28c5fc79846f4fcd380a5d9872b997
|
||||
- name: github.com/spf13/viper
|
||||
version: aafc9e6bc7b7bb53ddaa75a5ef49a17d6e654be5
|
||||
- name: github.com/stretchr/objx
|
||||
version: 8a3f7159479fbc75b30357fbc48f380b7320f08e
|
||||
- name: github.com/stretchr/testify
|
||||
version: 12b6f73e6084dad08a7c6e575284b177ecafbc71
|
||||
subpackages:
|
||||
- assert
|
||||
- mock
|
||||
- require
|
||||
- suite
|
||||
- name: github.com/tylerb/graceful
|
||||
version: d72b0151351a13d0421b763b88f791469c4f5dc7
|
||||
- name: github.com/xtgo/uuid
|
||||
version: a0b114877d4caeffbd7f87e3757c17fce570fea7
|
||||
- name: golang.org/x/crypto
|
||||
version: 650f4a345ab4e5b245a3034b110ebc7299e68186
|
||||
subpackages:
|
||||
- acme
|
||||
- acme/autocert
|
||||
- bcrypt
|
||||
- blowfish
|
||||
- ed25519
|
||||
- ed25519/internal/edwards25519
|
||||
- name: golang.org/x/image
|
||||
version: 12117c17ca67ffa1ce22e9409f3b0b0a93ac08c7
|
||||
subpackages:
|
||||
- bmp
|
||||
- font
|
||||
- math/fixed
|
||||
- tiff
|
||||
- tiff/lzw
|
||||
- name: golang.org/x/net
|
||||
version: dc948dff8834a7fe1ca525f8d04e261c2b56e70d
|
||||
subpackages:
|
||||
- bpf
|
||||
- html
|
||||
- html/atom
|
||||
- idna
|
||||
- internal/iana
|
||||
- internal/socket
|
||||
- ipv4
|
||||
- ipv6
|
||||
- lex/httplex
|
||||
- name: golang.org/x/sys
|
||||
version: 37707fdb30a5b38865cfb95e5aab41707daec7fd
|
||||
subpackages:
|
||||
- unix
|
||||
- name: golang.org/x/text
|
||||
version: 4e4a3210bb54bb31f6ab2cdca2edcc0b50c420c1
|
||||
subpackages:
|
||||
- secure/bidirule
|
||||
- transform
|
||||
- unicode/bidi
|
||||
- unicode/norm
|
||||
- name: google.golang.org/appengine
|
||||
version: 5bee14b453b4c71be47ec1781b0fa61c2ea182db
|
||||
subpackages:
|
||||
- cloudsql
|
||||
- name: gopkg.in/alexcesaro/quotedprintable.v3
|
||||
version: 2caba252f4dc53eaf6b553000885530023f54623
|
||||
- name: gopkg.in/asn1-ber.v1
|
||||
version: 379148ca0225df7a432012b8df0355c2a2063ac0
|
||||
- name: gopkg.in/gomail.v2
|
||||
version: 41f3572897373c5538c50a2402db15db079fa4fd
|
||||
- name: gopkg.in/olivere/elastic.v5
|
||||
version: 9f4560b20fb3bd4bb855fada3e6feea59b26ce66
|
||||
- name: gopkg.in/throttled/throttled.v2
|
||||
version: c4642cff38719000a875f10166ecb9599b002f96
|
||||
subpackages:
|
||||
- store/memstore
|
||||
- name: gopkg.in/yaml.v2
|
||||
version: d670f9405373e636a5a2765eea47fac0c9bc91a4
|
||||
testImports: []
|
||||
83
glide.yaml
@@ -1,83 +0,0 @@
|
||||
package: github.com/mattermost/mattermost-server
|
||||
import:
|
||||
- package: github.com/NYTimes/gziphandler
|
||||
- package: github.com/alecthomas/log4go
|
||||
repo: https://github.com/mattermost/log4go.git
|
||||
- package: github.com/dgryski/dgoogauth
|
||||
- package: github.com/disintegration/imaging
|
||||
version: v1.3.0
|
||||
- package: github.com/dyatlov/go-opengraph
|
||||
subpackages:
|
||||
- opengraph
|
||||
- package: github.com/fsnotify/fsnotify
|
||||
version: v1.4.7
|
||||
- package: github.com/go-ldap/ldap
|
||||
version: v2.5.1
|
||||
- package: github.com/go-redis/redis
|
||||
version: v6.8.3
|
||||
- package: github.com/go-sql-driver/mysql
|
||||
- package: github.com/golang/freetype
|
||||
- package: github.com/gorilla/handlers
|
||||
version: v1.3.0
|
||||
- package: github.com/gorilla/mux
|
||||
version: v1.6.1
|
||||
- package: github.com/gorilla/websocket
|
||||
- package: github.com/hashicorp/memberlist
|
||||
- package: github.com/icrowley/fake
|
||||
- package: github.com/lib/pq
|
||||
- package: github.com/mattermost/gorp
|
||||
- package: github.com/mattermost/html2text
|
||||
- package: github.com/mattermost/rsc
|
||||
subpackages:
|
||||
- qr
|
||||
- package: github.com/minio/minio-go
|
||||
repo: https://github.com/mattermost/minio-go.git
|
||||
version: 4.0.7.1
|
||||
subpackages:
|
||||
- pkg/credentials
|
||||
- package: github.com/nicksnyder/go-i18n
|
||||
version: v1.10.0
|
||||
subpackages:
|
||||
- i18n
|
||||
- package: github.com/pborman/uuid
|
||||
version: v1.1
|
||||
- package: github.com/pkg/errors
|
||||
version: v0.8.0
|
||||
- package: github.com/rwcarlsen/goexif
|
||||
subpackages:
|
||||
- exif
|
||||
- package: github.com/segmentio/analytics-go
|
||||
version: 2.1.1
|
||||
- package: github.com/spf13/cobra
|
||||
- package: github.com/spf13/viper
|
||||
vcs: git
|
||||
repo: https://github.com/hmhealey/viper.git
|
||||
- package: github.com/stretchr/testify
|
||||
version: v1.2.1
|
||||
subpackages:
|
||||
- assert
|
||||
- mock
|
||||
- require
|
||||
- package: golang.org/x/crypto
|
||||
subpackages:
|
||||
- bcrypt
|
||||
- package: golang.org/x/image
|
||||
subpackages:
|
||||
- bmp
|
||||
- package: golang.org/x/net
|
||||
subpackages:
|
||||
- bpf
|
||||
- package: golang.org/x/sys
|
||||
subpackages:
|
||||
- unix
|
||||
- package: gopkg.in/gomail.v2
|
||||
version: 2.0.0
|
||||
- package: gopkg.in/olivere/elastic.v5
|
||||
version: v6.1.7
|
||||
- package: gopkg.in/throttled/throttled.v2
|
||||
version: v2.1.0
|
||||
subpackages:
|
||||
- store/memstore
|
||||
- package: gopkg.in/yaml.v2
|
||||
- package: github.com/avct/uasurfer
|
||||
- package: github.com/hako/durafmt
|
||||
4
main.go
@@ -18,15 +18,13 @@ import (
|
||||
// Enterprise Deps
|
||||
_ "github.com/dgryski/dgoogauth"
|
||||
_ "github.com/go-ldap/ldap"
|
||||
_ "github.com/hako/durafmt"
|
||||
_ "github.com/hashicorp/memberlist"
|
||||
_ "github.com/mattermost/rsc/qr"
|
||||
_ "github.com/prometheus/client_golang/prometheus"
|
||||
_ "github.com/prometheus/client_golang/prometheus/promhttp"
|
||||
_ "github.com/tylerb/graceful"
|
||||
_ "gopkg.in/olivere/elastic.v5"
|
||||
|
||||
// Temp imports for new dependencies
|
||||
_ "github.com/gorilla/schema"
|
||||
)
|
||||
|
||||
func main() {
|
||||
|
||||
7
vendor/github.com/NYTimes/gziphandler/gzip.go
сгенерированный
поставляемый
@@ -28,9 +28,10 @@ const (
|
||||
// The examples seem to indicate that it is.
|
||||
DefaultQValue = 1.0
|
||||
|
||||
// DefaultMinSize defines the minimum size to reach to enable compression.
|
||||
// It's 512 bytes.
|
||||
DefaultMinSize = 512
|
||||
// 1500 bytes is the MTU size for the internet since that is the largest size allowed at the network layer.
|
||||
// If you take a file that is 1300 bytes and compress it to 800 bytes, it’s still transmitted in that same 1500 byte packet regardless, so you’ve gained nothing.
|
||||
// That being the case, you should restrict the gzip compression to files with a size greater than a single packet, 1400 bytes (1.4KB) is a safe value.
|
||||
DefaultMinSize = 1400
|
||||
)
|
||||
|
||||
// gzipWriterPools stores a sync.Pool for each compression level for reuse of
|
||||
|
||||
70
vendor/github.com/NYTimes/gziphandler/gzip_go18_test.go
сгенерированный
поставляемый
@@ -1,70 +0,0 @@
|
||||
// +build go1.8
|
||||
|
||||
package gziphandler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestSetAcceptEncodingForPushOptionsWithoutHeaders(t *testing.T) {
|
||||
var opts *http.PushOptions
|
||||
opts = setAcceptEncodingForPushOptions(opts)
|
||||
|
||||
assert.NotNil(t, opts)
|
||||
assert.NotNil(t, opts.Header)
|
||||
|
||||
for k, v := range opts.Header {
|
||||
assert.Equal(t, "Accept-Encoding", k)
|
||||
assert.Len(t, v, 1)
|
||||
assert.Equal(t, "gzip", v[0])
|
||||
}
|
||||
|
||||
opts = &http.PushOptions{}
|
||||
opts = setAcceptEncodingForPushOptions(opts)
|
||||
|
||||
assert.NotNil(t, opts)
|
||||
assert.NotNil(t, opts.Header)
|
||||
|
||||
for k, v := range opts.Header {
|
||||
assert.Equal(t, "Accept-Encoding", k)
|
||||
assert.Len(t, v, 1)
|
||||
assert.Equal(t, "gzip", v[0])
|
||||
}
|
||||
}
|
||||
|
||||
func TestSetAcceptEncodingForPushOptionsWithHeaders(t *testing.T) {
|
||||
opts := &http.PushOptions{
|
||||
Header: http.Header{
|
||||
"User-Agent": []string{"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.98 Safari/537.36"},
|
||||
},
|
||||
}
|
||||
opts = setAcceptEncodingForPushOptions(opts)
|
||||
|
||||
assert.NotNil(t, opts)
|
||||
assert.NotNil(t, opts.Header)
|
||||
|
||||
assert.Equal(t, "gzip", opts.Header.Get("Accept-Encoding"))
|
||||
assert.Equal(t, "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.98 Safari/537.36", opts.Header.Get("User-Agent"))
|
||||
|
||||
opts = &http.PushOptions{
|
||||
Header: http.Header{
|
||||
"User-Agent": []string{"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.98 Safari/537.36"},
|
||||
acceptEncoding: []string{"deflate"},
|
||||
},
|
||||
}
|
||||
opts = setAcceptEncodingForPushOptions(opts)
|
||||
|
||||
assert.NotNil(t, opts)
|
||||
assert.NotNil(t, opts.Header)
|
||||
|
||||
e, found := opts.Header["Accept-Encoding"]
|
||||
if !found {
|
||||
assert.Fail(t, "Missing Accept-Encoding header value")
|
||||
}
|
||||
assert.Len(t, e, 1)
|
||||
assert.Equal(t, "deflate", e[0])
|
||||
assert.Equal(t, "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.98 Safari/537.36", opts.Header.Get("User-Agent"))
|
||||
}
|
||||
540
vendor/github.com/NYTimes/gziphandler/gzip_test.go
сгенерированный
поставляемый
@@ -1,540 +0,0 @@
|
||||
package gziphandler
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"compress/gzip"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
const (
|
||||
smallTestBody = "aaabbcaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbccc"
|
||||
testBody = "aaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbccc"
|
||||
)
|
||||
|
||||
func TestParseEncodings(t *testing.T) {
|
||||
examples := map[string]codings{
|
||||
|
||||
// Examples from RFC 2616
|
||||
"compress, gzip": {"compress": 1.0, "gzip": 1.0},
|
||||
"": {},
|
||||
"*": {"*": 1.0},
|
||||
"compress;q=0.5, gzip;q=1.0": {"compress": 0.5, "gzip": 1.0},
|
||||
"gzip;q=1.0, identity; q=0.5, *;q=0": {"gzip": 1.0, "identity": 0.5, "*": 0.0},
|
||||
|
||||
// More random stuff
|
||||
"AAA;q=1": {"aaa": 1.0},
|
||||
"BBB ; q = 2": {"bbb": 1.0},
|
||||
}
|
||||
|
||||
for eg, exp := range examples {
|
||||
act, _ := parseEncodings(eg)
|
||||
assert.Equal(t, exp, act)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGzipHandler(t *testing.T) {
|
||||
// This just exists to provide something for GzipHandler to wrap.
|
||||
handler := newTestHandler(testBody)
|
||||
|
||||
// requests without accept-encoding are passed along as-is
|
||||
|
||||
req1, _ := http.NewRequest("GET", "/whatever", nil)
|
||||
resp1 := httptest.NewRecorder()
|
||||
handler.ServeHTTP(resp1, req1)
|
||||
res1 := resp1.Result()
|
||||
|
||||
assert.Equal(t, 200, res1.StatusCode)
|
||||
assert.Equal(t, "", res1.Header.Get("Content-Encoding"))
|
||||
assert.Equal(t, "Accept-Encoding", res1.Header.Get("Vary"))
|
||||
assert.Equal(t, testBody, resp1.Body.String())
|
||||
|
||||
// but requests with accept-encoding:gzip are compressed if possible
|
||||
|
||||
req2, _ := http.NewRequest("GET", "/whatever", nil)
|
||||
req2.Header.Set("Accept-Encoding", "gzip")
|
||||
resp2 := httptest.NewRecorder()
|
||||
handler.ServeHTTP(resp2, req2)
|
||||
res2 := resp2.Result()
|
||||
|
||||
assert.Equal(t, 200, res2.StatusCode)
|
||||
assert.Equal(t, "gzip", res2.Header.Get("Content-Encoding"))
|
||||
assert.Equal(t, "Accept-Encoding", res2.Header.Get("Vary"))
|
||||
assert.Equal(t, gzipStrLevel(testBody, gzip.DefaultCompression), resp2.Body.Bytes())
|
||||
|
||||
// content-type header is correctly set based on uncompressed body
|
||||
|
||||
req3, _ := http.NewRequest("GET", "/whatever", nil)
|
||||
req3.Header.Set("Accept-Encoding", "gzip")
|
||||
res3 := httptest.NewRecorder()
|
||||
handler.ServeHTTP(res3, req3)
|
||||
|
||||
assert.Equal(t, http.DetectContentType([]byte(testBody)), res3.Header().Get("Content-Type"))
|
||||
}
|
||||
|
||||
func TestGzipHandlerAlreadyCompressed(t *testing.T) {
|
||||
handler := newTestHandler(testBody)
|
||||
|
||||
req, _ := http.NewRequest("GET", "/gzipped", nil)
|
||||
req.Header.Set("Accept-Encoding", "gzip")
|
||||
res := httptest.NewRecorder()
|
||||
handler.ServeHTTP(res, req)
|
||||
|
||||
assert.Equal(t, testBody, res.Body.String())
|
||||
}
|
||||
|
||||
func TestNewGzipLevelHandler(t *testing.T) {
|
||||
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
io.WriteString(w, testBody)
|
||||
})
|
||||
|
||||
for lvl := gzip.BestSpeed; lvl <= gzip.BestCompression; lvl++ {
|
||||
wrapper, err := NewGzipLevelHandler(lvl)
|
||||
if !assert.Nil(t, err, "NewGzipLevleHandler returned error for level:", lvl) {
|
||||
continue
|
||||
}
|
||||
|
||||
req, _ := http.NewRequest("GET", "/whatever", nil)
|
||||
req.Header.Set("Accept-Encoding", "gzip")
|
||||
resp := httptest.NewRecorder()
|
||||
wrapper(handler).ServeHTTP(resp, req)
|
||||
res := resp.Result()
|
||||
|
||||
assert.Equal(t, 200, res.StatusCode)
|
||||
assert.Equal(t, "gzip", res.Header.Get("Content-Encoding"))
|
||||
assert.Equal(t, "Accept-Encoding", res.Header.Get("Vary"))
|
||||
assert.Equal(t, gzipStrLevel(testBody, lvl), resp.Body.Bytes())
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewGzipLevelHandlerReturnsErrorForInvalidLevels(t *testing.T) {
|
||||
var err error
|
||||
_, err = NewGzipLevelHandler(-42)
|
||||
assert.NotNil(t, err)
|
||||
|
||||
_, err = NewGzipLevelHandler(42)
|
||||
assert.NotNil(t, err)
|
||||
}
|
||||
|
||||
func TestMustNewGzipLevelHandlerWillPanic(t *testing.T) {
|
||||
defer func() {
|
||||
if r := recover(); r == nil {
|
||||
t.Error("panic was not called")
|
||||
}
|
||||
}()
|
||||
|
||||
_ = MustNewGzipLevelHandler(-42)
|
||||
}
|
||||
|
||||
func TestGzipHandlerNoBody(t *testing.T) {
|
||||
tests := []struct {
|
||||
statusCode int
|
||||
contentEncoding string
|
||||
bodyLen int
|
||||
}{
|
||||
// Body must be empty.
|
||||
{http.StatusNoContent, "", 0},
|
||||
{http.StatusNotModified, "", 0},
|
||||
// Body is going to get gzip'd no matter what.
|
||||
{http.StatusOK, "", 0},
|
||||
}
|
||||
|
||||
for num, test := range tests {
|
||||
handler := GzipHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(test.statusCode)
|
||||
}))
|
||||
|
||||
rec := httptest.NewRecorder()
|
||||
// TODO: in Go1.7 httptest.NewRequest was introduced this should be used
|
||||
// once 1.6 is not longer supported.
|
||||
req := &http.Request{
|
||||
Method: "GET",
|
||||
URL: &url.URL{Path: "/"},
|
||||
Proto: "HTTP/1.1",
|
||||
ProtoMinor: 1,
|
||||
RemoteAddr: "192.0.2.1:1234",
|
||||
Header: make(http.Header),
|
||||
}
|
||||
req.Header.Set("Accept-Encoding", "gzip")
|
||||
handler.ServeHTTP(rec, req)
|
||||
|
||||
body, err := ioutil.ReadAll(rec.Body)
|
||||
if err != nil {
|
||||
t.Fatalf("Unexpected error reading response body: %v", err)
|
||||
}
|
||||
|
||||
header := rec.Header()
|
||||
assert.Equal(t, test.contentEncoding, header.Get("Content-Encoding"), fmt.Sprintf("for test iteration %d", num))
|
||||
assert.Equal(t, "Accept-Encoding", header.Get("Vary"), fmt.Sprintf("for test iteration %d", num))
|
||||
assert.Equal(t, test.bodyLen, len(body), fmt.Sprintf("for test iteration %d", num))
|
||||
}
|
||||
}
|
||||
|
||||
func TestGzipHandlerContentLength(t *testing.T) {
|
||||
b := []byte(testBody)
|
||||
handler := GzipHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Length", strconv.Itoa(len(b)))
|
||||
w.Write(b)
|
||||
}))
|
||||
// httptest.NewRecorder doesn't give you access to the Content-Length
|
||||
// header so instead, we create a server on a random port and make
|
||||
// a request to that instead
|
||||
ln, err := net.Listen("tcp", "127.0.0.1:")
|
||||
if err != nil {
|
||||
t.Fatalf("failed creating listen socket: %v", err)
|
||||
}
|
||||
defer ln.Close()
|
||||
srv := &http.Server{
|
||||
Handler: handler,
|
||||
}
|
||||
go srv.Serve(ln)
|
||||
|
||||
req := &http.Request{
|
||||
Method: "GET",
|
||||
URL: &url.URL{Path: "/", Scheme: "http", Host: ln.Addr().String()},
|
||||
Header: make(http.Header),
|
||||
Close: true,
|
||||
}
|
||||
req.Header.Set("Accept-Encoding", "gzip")
|
||||
res, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
t.Fatalf("Unexpected error making http request: %v", err)
|
||||
}
|
||||
defer res.Body.Close()
|
||||
|
||||
body, err := ioutil.ReadAll(res.Body)
|
||||
if err != nil {
|
||||
t.Fatalf("Unexpected error reading response body: %v", err)
|
||||
}
|
||||
|
||||
l, err := strconv.Atoi(res.Header.Get("Content-Length"))
|
||||
if err != nil {
|
||||
t.Fatalf("Unexpected error parsing Content-Length: %v", err)
|
||||
}
|
||||
assert.Len(t, body, l)
|
||||
assert.Equal(t, "gzip", res.Header.Get("Content-Encoding"))
|
||||
assert.NotEqual(t, b, body)
|
||||
}
|
||||
|
||||
func TestGzipHandlerMinSizeMustBePositive(t *testing.T) {
|
||||
_, err := NewGzipLevelAndMinSize(gzip.DefaultCompression, -1)
|
||||
assert.Error(t, err)
|
||||
}
|
||||
|
||||
func TestGzipHandlerMinSize(t *testing.T) {
|
||||
responseLength := 0
|
||||
b := []byte{'x'}
|
||||
|
||||
wrapper, _ := NewGzipLevelAndMinSize(gzip.DefaultCompression, 128)
|
||||
handler := wrapper(http.HandlerFunc(
|
||||
func(w http.ResponseWriter, r *http.Request) {
|
||||
// Write responses one byte at a time to ensure that the flush
|
||||
// mechanism, if used, is working properly.
|
||||
for i := 0; i < responseLength; i++ {
|
||||
n, err := w.Write(b)
|
||||
assert.Equal(t, 1, n)
|
||||
assert.Nil(t, err)
|
||||
}
|
||||
},
|
||||
))
|
||||
|
||||
r, _ := http.NewRequest("GET", "/whatever", &bytes.Buffer{})
|
||||
r.Header.Add("Accept-Encoding", "gzip")
|
||||
|
||||
// Short response is not compressed
|
||||
responseLength = 127
|
||||
w := httptest.NewRecorder()
|
||||
handler.ServeHTTP(w, r)
|
||||
if w.Result().Header.Get(contentEncoding) == "gzip" {
|
||||
t.Error("Expected uncompressed response, got compressed")
|
||||
}
|
||||
|
||||
// Long response is not compressed
|
||||
responseLength = 128
|
||||
w = httptest.NewRecorder()
|
||||
handler.ServeHTTP(w, r)
|
||||
if w.Result().Header.Get(contentEncoding) != "gzip" {
|
||||
t.Error("Expected compressed response, got uncompressed")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGzipDoubleClose(t *testing.T) {
|
||||
// reset the pool for the default compression so we can make sure duplicates
|
||||
// aren't added back by double close
|
||||
addLevelPool(gzip.DefaultCompression)
|
||||
|
||||
handler := GzipHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
// call close here and it'll get called again interally by
|
||||
// NewGzipLevelHandler's handler defer
|
||||
w.Write([]byte("test"))
|
||||
w.(io.Closer).Close()
|
||||
}))
|
||||
|
||||
r := httptest.NewRequest("GET", "/", nil)
|
||||
r.Header.Set("Accept-Encoding", "gzip")
|
||||
w := httptest.NewRecorder()
|
||||
handler.ServeHTTP(w, r)
|
||||
|
||||
// the second close shouldn't have added the same writer
|
||||
// so we pull out 2 writers from the pool and make sure they're different
|
||||
w1 := gzipWriterPools[poolIndex(gzip.DefaultCompression)].Get()
|
||||
w2 := gzipWriterPools[poolIndex(gzip.DefaultCompression)].Get()
|
||||
// assert.NotEqual looks at the value and not the address, so we use regular ==
|
||||
assert.False(t, w1 == w2)
|
||||
}
|
||||
|
||||
func TestStatusCodes(t *testing.T) {
|
||||
handler := GzipHandler(http.NotFoundHandler())
|
||||
r := httptest.NewRequest("GET", "/", nil)
|
||||
r.Header.Set("Accept-Encoding", "gzip")
|
||||
w := httptest.NewRecorder()
|
||||
handler.ServeHTTP(w, r)
|
||||
|
||||
result := w.Result()
|
||||
if result.StatusCode != 404 {
|
||||
t.Errorf("StatusCode should have been 404 but was %d", result.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFlushBeforeWrite(t *testing.T) {
|
||||
b := []byte(testBody)
|
||||
handler := GzipHandler(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
|
||||
rw.WriteHeader(http.StatusNotFound)
|
||||
rw.(http.Flusher).Flush()
|
||||
rw.Write(b)
|
||||
}))
|
||||
r := httptest.NewRequest(http.MethodGet, "/", nil)
|
||||
r.Header.Set("Accept-Encoding", "gzip")
|
||||
w := httptest.NewRecorder()
|
||||
handler.ServeHTTP(w, r)
|
||||
|
||||
res := w.Result()
|
||||
assert.Equal(t, http.StatusNotFound, res.StatusCode)
|
||||
assert.Equal(t, "gzip", res.Header.Get("Content-Encoding"))
|
||||
assert.NotEqual(t, b, w.Body.Bytes())
|
||||
}
|
||||
|
||||
func TestImplementCloseNotifier(t *testing.T) {
|
||||
request := httptest.NewRequest(http.MethodGet, "/", nil)
|
||||
request.Header.Set(acceptEncoding, "gzip")
|
||||
GzipHandler(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request){
|
||||
_, ok := rw.(http.CloseNotifier)
|
||||
assert.True(t, ok, "response writer must implement http.CloseNotifier")
|
||||
})).ServeHTTP(&mockRWCloseNotify{}, request)
|
||||
}
|
||||
|
||||
func TestImplementFlusherAndCloseNotifier(t *testing.T) {
|
||||
request := httptest.NewRequest(http.MethodGet, "/", nil)
|
||||
request.Header.Set(acceptEncoding, "gzip")
|
||||
GzipHandler(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request){
|
||||
_, okCloseNotifier := rw.(http.CloseNotifier)
|
||||
assert.True(t, okCloseNotifier, "response writer must implement http.CloseNotifier")
|
||||
_, okFlusher := rw.(http.Flusher)
|
||||
assert.True(t, okFlusher, "response writer must implement http.Flusher")
|
||||
})).ServeHTTP(&mockRWCloseNotify{}, request)
|
||||
}
|
||||
|
||||
func TestNotImplementCloseNotifier(t *testing.T) {
|
||||
request := httptest.NewRequest(http.MethodGet, "/", nil)
|
||||
request.Header.Set(acceptEncoding, "gzip")
|
||||
GzipHandler(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request){
|
||||
_, ok := rw.(http.CloseNotifier)
|
||||
assert.False(t, ok, "response writer must not implement http.CloseNotifier")
|
||||
})).ServeHTTP(httptest.NewRecorder(), request)
|
||||
}
|
||||
|
||||
|
||||
type mockRWCloseNotify struct{}
|
||||
|
||||
func (m *mockRWCloseNotify) CloseNotify() <-chan bool {
|
||||
panic("implement me")
|
||||
}
|
||||
|
||||
func (m *mockRWCloseNotify) Header() http.Header {
|
||||
return http.Header{}
|
||||
}
|
||||
|
||||
func (m *mockRWCloseNotify) Write([]byte) (int, error) {
|
||||
panic("implement me")
|
||||
}
|
||||
|
||||
func (m *mockRWCloseNotify) WriteHeader(int) {
|
||||
panic("implement me")
|
||||
}
|
||||
|
||||
|
||||
func TestIgnoreSubsequentWriteHeader(t *testing.T) {
|
||||
handler := GzipHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(500)
|
||||
w.WriteHeader(404)
|
||||
}))
|
||||
r := httptest.NewRequest("GET", "/", nil)
|
||||
r.Header.Set("Accept-Encoding", "gzip")
|
||||
w := httptest.NewRecorder()
|
||||
handler.ServeHTTP(w, r)
|
||||
|
||||
result := w.Result()
|
||||
if result.StatusCode != 500 {
|
||||
t.Errorf("StatusCode should have been 500 but was %d", result.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDontWriteWhenNotWrittenTo(t *testing.T) {
|
||||
// When using gzip as middleware without ANY writes in the handler,
|
||||
// ensure the gzip middleware doesn't touch the actual ResponseWriter
|
||||
// either.
|
||||
|
||||
handler0 := GzipHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
}))
|
||||
|
||||
handler1 := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
handler0.ServeHTTP(w, r)
|
||||
w.WriteHeader(404) // this only works if gzip didn't do a WriteHeader(200)
|
||||
})
|
||||
|
||||
r := httptest.NewRequest("GET", "/", nil)
|
||||
r.Header.Set("Accept-Encoding", "gzip")
|
||||
w := httptest.NewRecorder()
|
||||
handler1.ServeHTTP(w, r)
|
||||
|
||||
result := w.Result()
|
||||
if result.StatusCode != 404 {
|
||||
t.Errorf("StatusCode should have been 404 but was %d", result.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
var contentTypeTests = []struct {
|
||||
name string
|
||||
contentType string
|
||||
acceptedContentTypes []string
|
||||
expectedGzip bool
|
||||
}{
|
||||
{
|
||||
name: "Always gzip when content types are empty",
|
||||
contentType: "",
|
||||
acceptedContentTypes: []string{},
|
||||
expectedGzip: true,
|
||||
},
|
||||
{
|
||||
name: "Exact content-type match",
|
||||
contentType: "application/json",
|
||||
acceptedContentTypes: []string{"application/json"},
|
||||
expectedGzip: true,
|
||||
},
|
||||
{
|
||||
name: "Case insensitive content-type matching",
|
||||
contentType: "Application/Json",
|
||||
acceptedContentTypes: []string{"application/json"},
|
||||
expectedGzip: true,
|
||||
},
|
||||
{
|
||||
name: "Non-matching content-type",
|
||||
contentType: "text/xml",
|
||||
acceptedContentTypes: []string{"application/json"},
|
||||
expectedGzip: false,
|
||||
},
|
||||
}
|
||||
|
||||
func TestContentTypes(t *testing.T) {
|
||||
for _, tt := range contentTypeTests {
|
||||
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.Header().Set("Content-Type", tt.contentType)
|
||||
io.WriteString(w, testBody)
|
||||
})
|
||||
|
||||
wrapper, err := GzipHandlerWithOpts(ContentTypes(tt.acceptedContentTypes))
|
||||
if !assert.Nil(t, err, "NewGzipHandlerWithOpts returned error", tt.name) {
|
||||
continue
|
||||
}
|
||||
|
||||
req, _ := http.NewRequest("GET", "/whatever", nil)
|
||||
req.Header.Set("Accept-Encoding", "gzip")
|
||||
resp := httptest.NewRecorder()
|
||||
wrapper(handler).ServeHTTP(resp, req)
|
||||
res := resp.Result()
|
||||
|
||||
assert.Equal(t, 200, res.StatusCode)
|
||||
if tt.expectedGzip {
|
||||
assert.Equal(t, "gzip", res.Header.Get("Content-Encoding"), tt.name)
|
||||
} else {
|
||||
assert.NotEqual(t, "gzip", res.Header.Get("Content-Encoding"), tt.name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --------------------------------------------------------------------
|
||||
|
||||
func BenchmarkGzipHandler_S2k(b *testing.B) { benchmark(b, false, 2048) }
|
||||
func BenchmarkGzipHandler_S20k(b *testing.B) { benchmark(b, false, 20480) }
|
||||
func BenchmarkGzipHandler_S100k(b *testing.B) { benchmark(b, false, 102400) }
|
||||
func BenchmarkGzipHandler_P2k(b *testing.B) { benchmark(b, true, 2048) }
|
||||
func BenchmarkGzipHandler_P20k(b *testing.B) { benchmark(b, true, 20480) }
|
||||
func BenchmarkGzipHandler_P100k(b *testing.B) { benchmark(b, true, 102400) }
|
||||
|
||||
// --------------------------------------------------------------------
|
||||
|
||||
func gzipStrLevel(s string, lvl int) []byte {
|
||||
var b bytes.Buffer
|
||||
w, _ := gzip.NewWriterLevel(&b, lvl)
|
||||
io.WriteString(w, s)
|
||||
w.Close()
|
||||
return b.Bytes()
|
||||
}
|
||||
|
||||
func benchmark(b *testing.B, parallel bool, size int) {
|
||||
bin, err := ioutil.ReadFile("testdata/benchmark.json")
|
||||
if err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
|
||||
req, _ := http.NewRequest("GET", "/whatever", nil)
|
||||
req.Header.Set("Accept-Encoding", "gzip")
|
||||
handler := newTestHandler(string(bin[:size]))
|
||||
|
||||
if parallel {
|
||||
b.ResetTimer()
|
||||
b.RunParallel(func(pb *testing.PB) {
|
||||
for pb.Next() {
|
||||
runBenchmark(b, req, handler)
|
||||
}
|
||||
})
|
||||
} else {
|
||||
b.ResetTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
runBenchmark(b, req, handler)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func runBenchmark(b *testing.B, req *http.Request, handler http.Handler) {
|
||||
res := httptest.NewRecorder()
|
||||
handler.ServeHTTP(res, req)
|
||||
if code := res.Code; code != 200 {
|
||||
b.Fatalf("Expected 200 but got %d", code)
|
||||
} else if blen := res.Body.Len(); blen < 500 {
|
||||
b.Fatalf("Expected complete response body, but got %d bytes", blen)
|
||||
}
|
||||
}
|
||||
|
||||
func newTestHandler(body string) http.Handler {
|
||||
return GzipHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.URL.Path {
|
||||
case "/gzipped":
|
||||
w.Header().Set("Content-Encoding", "gzip")
|
||||
io.WriteString(w, body)
|
||||
default:
|
||||
io.WriteString(w, body)
|
||||
}
|
||||
}))
|
||||
}
|
||||
5456
vendor/github.com/NYTimes/gziphandler/testdata/benchmark.json
сгенерированный
поставляемый
14
vendor/github.com/alecthomas/log4go/examples/ConsoleLogWriter_Manual.go
сгенерированный
поставляемый
@@ -1,14 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"time"
|
||||
)
|
||||
|
||||
import l4g "code.google.com/p/log4go"
|
||||
|
||||
func main() {
|
||||
log := l4g.NewLogger()
|
||||
defer log.Close()
|
||||
log.AddFilter("stdout", l4g.DEBUG, l4g.NewConsoleLogWriter())
|
||||
log.Info("The time is now: %s", time.Now().Format("15:04:05 MST 2006/01/02"))
|
||||
}
|
||||
57
vendor/github.com/alecthomas/log4go/examples/FileLogWriter_Manual.go
сгенерированный
поставляемый
@@ -1,57 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"time"
|
||||
)
|
||||
|
||||
import l4g "code.google.com/p/log4go"
|
||||
|
||||
const (
|
||||
filename = "flw.log"
|
||||
)
|
||||
|
||||
func main() {
|
||||
// Get a new logger instance
|
||||
log := l4g.NewLogger()
|
||||
|
||||
// Create a default logger that is logging messages of FINE or higher
|
||||
log.AddFilter("file", l4g.FINE, l4g.NewFileLogWriter(filename, false))
|
||||
log.Close()
|
||||
|
||||
/* Can also specify manually via the following: (these are the defaults) */
|
||||
flw := l4g.NewFileLogWriter(filename, false)
|
||||
flw.SetFormat("[%D %T] [%L] (%S) %M")
|
||||
flw.SetRotate(false)
|
||||
flw.SetRotateSize(0)
|
||||
flw.SetRotateLines(0)
|
||||
flw.SetRotateDaily(false)
|
||||
log.AddFilter("file", l4g.FINE, flw)
|
||||
|
||||
// Log some experimental messages
|
||||
log.Finest("Everything is created now (notice that I will not be printing to the file)")
|
||||
log.Info("The time is now: %s", time.Now().Format("15:04:05 MST 2006/01/02"))
|
||||
log.Critical("Time to close out!")
|
||||
|
||||
// Close the log
|
||||
log.Close()
|
||||
|
||||
// Print what was logged to the file (yes, I know I'm skipping error checking)
|
||||
fd, _ := os.Open(filename)
|
||||
in := bufio.NewReader(fd)
|
||||
fmt.Print("Messages logged to file were: (line numbers not included)\n")
|
||||
for lineno := 1; ; lineno++ {
|
||||
line, err := in.ReadString('\n')
|
||||
if err == io.EOF {
|
||||
break
|
||||
}
|
||||
fmt.Printf("%3d:\t%s", lineno, line)
|
||||
}
|
||||
fd.Close()
|
||||
|
||||
// Remove the file so it's not lying around
|
||||
os.Remove(filename)
|
||||
}
|
||||
42
vendor/github.com/alecthomas/log4go/examples/SimpleNetLogServer.go
сгенерированный
поставляемый
@@ -1,42 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"net"
|
||||
"os"
|
||||
)
|
||||
|
||||
var (
|
||||
port = flag.String("p", "12124", "Port number to listen on")
|
||||
)
|
||||
|
||||
func e(err error) {
|
||||
if err != nil {
|
||||
fmt.Printf("Erroring out: %s\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
flag.Parse()
|
||||
|
||||
// Bind to the port
|
||||
bind, err := net.ResolveUDPAddr("0.0.0.0:" + *port)
|
||||
e(err)
|
||||
|
||||
// Create listener
|
||||
listener, err := net.ListenUDP("udp", bind)
|
||||
e(err)
|
||||
|
||||
fmt.Printf("Listening to port %s...\n", *port)
|
||||
for {
|
||||
// read into a new buffer
|
||||
buffer := make([]byte, 1024)
|
||||
_, _, err := listener.ReadFrom(buffer)
|
||||
e(err)
|
||||
|
||||
// log to standard output
|
||||
fmt.Println(string(buffer))
|
||||
}
|
||||
}
|
||||
18
vendor/github.com/alecthomas/log4go/examples/SocketLogWriter_Manual.go
сгенерированный
поставляемый
@@ -1,18 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"time"
|
||||
)
|
||||
|
||||
import l4g "code.google.com/p/log4go"
|
||||
|
||||
func main() {
|
||||
log := l4g.NewLogger()
|
||||
log.AddFilter("network", l4g.FINEST, l4g.NewSocketLogWriter("udp", "192.168.1.255:12124"))
|
||||
|
||||
// Run `nc -u -l -p 12124` or similar before you run this to see the following message
|
||||
log.Info("The time is now: %s", time.Now().Format("15:04:05 MST 2006/01/02"))
|
||||
|
||||
// This makes sure the output stream buffer is written
|
||||
log.Close()
|
||||
}
|
||||
13
vendor/github.com/alecthomas/log4go/examples/XMLConfigurationExample.go
сгенерированный
поставляемый
@@ -1,13 +0,0 @@
|
||||
package main
|
||||
|
||||
import l4g "code.google.com/p/log4go"
|
||||
|
||||
func main() {
|
||||
// Load the configuration (isn't this easy?)
|
||||
l4g.LoadConfiguration("example.xml")
|
||||
|
||||
// And now we're ready!
|
||||
l4g.Finest("This will only go to those of you really cool UDP kids! If you change enabled=true.")
|
||||
l4g.Debug("Oh no! %d + %d = %d!", 2, 2, 2+2)
|
||||
l4g.Info("About that time, eh chaps?")
|
||||
}
|
||||
47
vendor/github.com/alecthomas/log4go/examples/example.xml
сгенерированный
поставляемый
@@ -1,47 +0,0 @@
|
||||
<logging>
|
||||
<filter enabled="true">
|
||||
<tag>stdout</tag>
|
||||
<type>console</type>
|
||||
<!-- level is (:?FINEST|FINE|DEBUG|TRACE|INFO|WARNING|ERROR) -->
|
||||
<level>DEBUG</level>
|
||||
</filter>
|
||||
<filter enabled="true">
|
||||
<tag>file</tag>
|
||||
<type>file</type>
|
||||
<level>FINEST</level>
|
||||
<property name="filename">test.log</property>
|
||||
<!--
|
||||
%T - Time (15:04:05 MST)
|
||||
%t - Time (15:04)
|
||||
%D - Date (2006/01/02)
|
||||
%d - Date (01/02/06)
|
||||
%L - Level (FNST, FINE, DEBG, TRAC, WARN, EROR, CRIT)
|
||||
%S - Source
|
||||
%M - Message
|
||||
It ignores unknown format strings (and removes them)
|
||||
Recommended: "[%D %T] [%L] (%S) %M"
|
||||
-->
|
||||
<property name="format">[%D %T] [%L] (%S) %M</property>
|
||||
<property name="rotate">false</property> <!-- true enables log rotation, otherwise append -->
|
||||
<property name="maxsize">0M</property> <!-- \d+[KMG]? Suffixes are in terms of 2**10 -->
|
||||
<property name="maxlines">0K</property> <!-- \d+[KMG]? Suffixes are in terms of thousands -->
|
||||
<property name="daily">true</property> <!-- Automatically rotates when a log message is written after midnight -->
|
||||
</filter>
|
||||
<filter enabled="true">
|
||||
<tag>xmllog</tag>
|
||||
<type>xml</type>
|
||||
<level>TRACE</level>
|
||||
<property name="filename">trace.xml</property>
|
||||
<property name="rotate">true</property> <!-- true enables log rotation, otherwise append -->
|
||||
<property name="maxsize">100M</property> <!-- \d+[KMG]? Suffixes are in terms of 2**10 -->
|
||||
<property name="maxrecords">6K</property> <!-- \d+[KMG]? Suffixes are in terms of thousands -->
|
||||
<property name="daily">false</property> <!-- Automatically rotates when a log message is written after midnight -->
|
||||
</filter>
|
||||
<filter enabled="false"><!-- enabled=false means this logger won't actually be created -->
|
||||
<tag>donotopen</tag>
|
||||
<type>socket</type>
|
||||
<level>FINEST</level>
|
||||
<property name="endpoint">192.168.1.255:12124</property> <!-- recommend UDP broadcast -->
|
||||
<property name="protocol">udp</property> <!-- tcp or udp -->
|
||||
</filter>
|
||||
</logging>
|
||||
51
vendor/github.com/alecthomas/log4go/filelog.go
сгенерированный
поставляемый
@@ -3,15 +3,18 @@
|
||||
package log4go
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"time"
|
||||
)
|
||||
|
||||
// This log writer sends output to a file
|
||||
type FileLogWriter struct {
|
||||
rec chan *LogRecord
|
||||
rot chan bool
|
||||
rec chan *LogRecord
|
||||
rot chan bool
|
||||
done chan bool
|
||||
|
||||
// The opened file
|
||||
filename string
|
||||
@@ -47,6 +50,7 @@ func (w *FileLogWriter) LogWrite(rec *LogRecord) {
|
||||
|
||||
func (w *FileLogWriter) Close() {
|
||||
close(w.rec)
|
||||
<-w.done
|
||||
}
|
||||
|
||||
// NewFileLogWriter creates a new LogWriter which writes to the given file and
|
||||
@@ -62,6 +66,7 @@ func NewFileLogWriter(fname string, rotate bool) *FileLogWriter {
|
||||
w := &FileLogWriter{
|
||||
rec: make(chan *LogRecord, LogBufferLength),
|
||||
rot: make(chan bool),
|
||||
done: make(chan bool),
|
||||
filename: fname,
|
||||
format: "[%D %T] [%L] (%S) %M",
|
||||
rotate: rotate,
|
||||
@@ -81,6 +86,7 @@ func NewFileLogWriter(fname string, rotate bool) *FileLogWriter {
|
||||
w.file.Sync()
|
||||
w.file.Close()
|
||||
}
|
||||
close(w.done)
|
||||
}()
|
||||
|
||||
for {
|
||||
@@ -173,7 +179,22 @@ func (w *FileLogWriter) intRotate() error {
|
||||
}
|
||||
}
|
||||
|
||||
// Open the log file
|
||||
lineCount := 0
|
||||
byteCount := 0
|
||||
|
||||
// If the file exists, open for reading and set our line/byte counts
|
||||
// On failure, just assume the file doesn't exist
|
||||
if fd, err := os.OpenFile(w.filename, os.O_RDONLY, 0440); err == nil {
|
||||
lineCount, _ = lineCounter(fd)
|
||||
|
||||
fi, err := fd.Stat()
|
||||
if err == nil {
|
||||
byteCount = int(fi.Size())
|
||||
}
|
||||
|
||||
fd.Close()
|
||||
}
|
||||
|
||||
fd, err := os.OpenFile(w.filename, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0660)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -187,12 +208,32 @@ func (w *FileLogWriter) intRotate() error {
|
||||
w.daily_opendate = now.Day()
|
||||
|
||||
// initialize rotation values
|
||||
w.maxlines_curlines = 0
|
||||
w.maxsize_cursize = 0
|
||||
w.maxlines_curlines = lineCount
|
||||
w.maxsize_cursize = byteCount
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Taken from https://stackoverflow.com/a/24563853
|
||||
func lineCounter(r io.Reader) (int, error) {
|
||||
buf := make([]byte, 32*1024)
|
||||
count := 0
|
||||
lineSep := []byte{'\n'}
|
||||
|
||||
for {
|
||||
c, err := r.Read(buf)
|
||||
count += bytes.Count(buf[:c], lineSep)
|
||||
|
||||
switch {
|
||||
case err == io.EOF:
|
||||
return count, nil
|
||||
|
||||
case err != nil:
|
||||
return count, err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Set the logging format (chainable). Must be called before the first log
|
||||
// message is written.
|
||||
func (w *FileLogWriter) SetFormat(format string) *FileLogWriter {
|
||||
|
||||
534
vendor/github.com/alecthomas/log4go/log4go_test.go
сгенерированный
поставляемый
@@ -1,534 +0,0 @@
|
||||
// Copyright (C) 2010, Kyle Lemons <kyle@kylelemons.net>. All rights reserved.
|
||||
|
||||
package log4go
|
||||
|
||||
import (
|
||||
"crypto/md5"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"runtime"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
const testLogFile = "_logtest.log"
|
||||
|
||||
var now time.Time = time.Unix(0, 1234567890123456789).In(time.UTC)
|
||||
|
||||
func newLogRecord(lvl Level, src string, msg string) *LogRecord {
|
||||
return &LogRecord{
|
||||
Level: lvl,
|
||||
Source: src,
|
||||
Created: now,
|
||||
Message: msg,
|
||||
}
|
||||
}
|
||||
|
||||
func TestELog(t *testing.T) {
|
||||
fmt.Printf("Testing %s\n", L4G_VERSION)
|
||||
lr := newLogRecord(CRITICAL, "source", "message")
|
||||
if lr.Level != CRITICAL {
|
||||
t.Errorf("Incorrect level: %d should be %d", lr.Level, CRITICAL)
|
||||
}
|
||||
if lr.Source != "source" {
|
||||
t.Errorf("Incorrect source: %s should be %s", lr.Source, "source")
|
||||
}
|
||||
if lr.Message != "message" {
|
||||
t.Errorf("Incorrect message: %s should be %s", lr.Source, "message")
|
||||
}
|
||||
}
|
||||
|
||||
var formatTests = []struct {
|
||||
Test string
|
||||
Record *LogRecord
|
||||
Formats map[string]string
|
||||
}{
|
||||
{
|
||||
Test: "Standard formats",
|
||||
Record: &LogRecord{
|
||||
Level: ERROR,
|
||||
Source: "source",
|
||||
Message: "message",
|
||||
Created: now,
|
||||
},
|
||||
Formats: map[string]string{
|
||||
// TODO(kevlar): How can I do this so it'll work outside of PST?
|
||||
FORMAT_DEFAULT: "[2009/02/13 23:31:30 UTC] [EROR] (source) message\n",
|
||||
FORMAT_SHORT: "[23:31 13/02/09] [EROR] message\n",
|
||||
FORMAT_ABBREV: "[EROR] message\n",
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
func TestFormatLogRecord(t *testing.T) {
|
||||
for _, test := range formatTests {
|
||||
name := test.Test
|
||||
for fmt, want := range test.Formats {
|
||||
if got := FormatLogRecord(fmt, test.Record); got != want {
|
||||
t.Errorf("%s - %s:", name, fmt)
|
||||
t.Errorf(" got %q", got)
|
||||
t.Errorf(" want %q", want)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var logRecordWriteTests = []struct {
|
||||
Test string
|
||||
Record *LogRecord
|
||||
Console string
|
||||
}{
|
||||
{
|
||||
Test: "Normal message",
|
||||
Record: &LogRecord{
|
||||
Level: CRITICAL,
|
||||
Source: "source",
|
||||
Message: "message",
|
||||
Created: now,
|
||||
},
|
||||
Console: "[23:31:30 UTC 2009/02/13] [CRIT] message\n",
|
||||
},
|
||||
}
|
||||
|
||||
func TestConsoleLogWriter(t *testing.T) {
|
||||
console := make(ConsoleLogWriter)
|
||||
|
||||
r, w := io.Pipe()
|
||||
go console.run(w)
|
||||
defer console.Close()
|
||||
|
||||
buf := make([]byte, 1024)
|
||||
|
||||
for _, test := range logRecordWriteTests {
|
||||
name := test.Test
|
||||
|
||||
console.LogWrite(test.Record)
|
||||
n, _ := r.Read(buf)
|
||||
|
||||
if got, want := string(buf[:n]), test.Console; got != want {
|
||||
t.Errorf("%s: got %q", name, got)
|
||||
t.Errorf("%s: want %q", name, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestFileLogWriter(t *testing.T) {
|
||||
defer func(buflen int) {
|
||||
LogBufferLength = buflen
|
||||
}(LogBufferLength)
|
||||
LogBufferLength = 0
|
||||
|
||||
w := NewFileLogWriter(testLogFile, false)
|
||||
if w == nil {
|
||||
t.Fatalf("Invalid return: w should not be nil")
|
||||
}
|
||||
defer os.Remove(testLogFile)
|
||||
|
||||
w.LogWrite(newLogRecord(CRITICAL, "source", "message"))
|
||||
w.Close()
|
||||
runtime.Gosched()
|
||||
|
||||
if contents, err := ioutil.ReadFile(testLogFile); err != nil {
|
||||
t.Errorf("read(%q): %s", testLogFile, err)
|
||||
} else if len(contents) != 50 {
|
||||
t.Errorf("malformed filelog: %q (%d bytes)", string(contents), len(contents))
|
||||
}
|
||||
}
|
||||
|
||||
func TestXMLLogWriter(t *testing.T) {
|
||||
defer func(buflen int) {
|
||||
LogBufferLength = buflen
|
||||
}(LogBufferLength)
|
||||
LogBufferLength = 0
|
||||
|
||||
w := NewXMLLogWriter(testLogFile, false)
|
||||
if w == nil {
|
||||
t.Fatalf("Invalid return: w should not be nil")
|
||||
}
|
||||
defer os.Remove(testLogFile)
|
||||
|
||||
w.LogWrite(newLogRecord(CRITICAL, "source", "message"))
|
||||
w.Close()
|
||||
runtime.Gosched()
|
||||
|
||||
if contents, err := ioutil.ReadFile(testLogFile); err != nil {
|
||||
t.Errorf("read(%q): %s", testLogFile, err)
|
||||
} else if len(contents) != 185 {
|
||||
t.Errorf("malformed xmllog: %q (%d bytes)", string(contents), len(contents))
|
||||
}
|
||||
}
|
||||
|
||||
func TestLogger(t *testing.T) {
|
||||
sl := NewDefaultLogger(WARNING)
|
||||
if sl == nil {
|
||||
t.Fatalf("NewDefaultLogger should never return nil")
|
||||
}
|
||||
if lw, exist := sl["stdout"]; lw == nil || exist != true {
|
||||
t.Fatalf("NewDefaultLogger produced invalid logger (DNE or nil)")
|
||||
}
|
||||
if sl["stdout"].Level != WARNING {
|
||||
t.Fatalf("NewDefaultLogger produced invalid logger (incorrect level)")
|
||||
}
|
||||
if len(sl) != 1 {
|
||||
t.Fatalf("NewDefaultLogger produced invalid logger (incorrect map count)")
|
||||
}
|
||||
|
||||
//func (l *Logger) AddFilter(name string, level int, writer LogWriter) {}
|
||||
l := make(Logger)
|
||||
l.AddFilter("stdout", DEBUG, NewConsoleLogWriter())
|
||||
if lw, exist := l["stdout"]; lw == nil || exist != true {
|
||||
t.Fatalf("AddFilter produced invalid logger (DNE or nil)")
|
||||
}
|
||||
if l["stdout"].Level != DEBUG {
|
||||
t.Fatalf("AddFilter produced invalid logger (incorrect level)")
|
||||
}
|
||||
if len(l) != 1 {
|
||||
t.Fatalf("AddFilter produced invalid logger (incorrect map count)")
|
||||
}
|
||||
|
||||
//func (l *Logger) Warn(format string, args ...interface{}) error {}
|
||||
if err := l.Warn("%s %d %#v", "Warning:", 1, []int{}); err.Error() != "Warning: 1 []int{}" {
|
||||
t.Errorf("Warn returned invalid error: %s", err)
|
||||
}
|
||||
|
||||
//func (l *Logger) Error(format string, args ...interface{}) error {}
|
||||
if err := l.Error("%s %d %#v", "Error:", 10, []string{}); err.Error() != "Error: 10 []string{}" {
|
||||
t.Errorf("Error returned invalid error: %s", err)
|
||||
}
|
||||
|
||||
//func (l *Logger) Critical(format string, args ...interface{}) error {}
|
||||
if err := l.Critical("%s %d %#v", "Critical:", 100, []int64{}); err.Error() != "Critical: 100 []int64{}" {
|
||||
t.Errorf("Critical returned invalid error: %s", err)
|
||||
}
|
||||
|
||||
// Already tested or basically untestable
|
||||
//func (l *Logger) Log(level int, source, message string) {}
|
||||
//func (l *Logger) Logf(level int, format string, args ...interface{}) {}
|
||||
//func (l *Logger) intLogf(level int, format string, args ...interface{}) string {}
|
||||
//func (l *Logger) Finest(format string, args ...interface{}) {}
|
||||
//func (l *Logger) Fine(format string, args ...interface{}) {}
|
||||
//func (l *Logger) Debug(format string, args ...interface{}) {}
|
||||
//func (l *Logger) Trace(format string, args ...interface{}) {}
|
||||
//func (l *Logger) Info(format string, args ...interface{}) {}
|
||||
}
|
||||
|
||||
func TestLogOutput(t *testing.T) {
|
||||
const (
|
||||
expected = "fdf3e51e444da56b4cb400f30bc47424"
|
||||
)
|
||||
|
||||
// Unbuffered output
|
||||
defer func(buflen int) {
|
||||
LogBufferLength = buflen
|
||||
}(LogBufferLength)
|
||||
LogBufferLength = 0
|
||||
|
||||
l := make(Logger)
|
||||
|
||||
// Delete and open the output log without a timestamp (for a constant md5sum)
|
||||
l.AddFilter("file", FINEST, NewFileLogWriter(testLogFile, false).SetFormat("[%L] %M"))
|
||||
defer os.Remove(testLogFile)
|
||||
|
||||
// Send some log messages
|
||||
l.Log(CRITICAL, "testsrc1", fmt.Sprintf("This message is level %d", int(CRITICAL)))
|
||||
l.Logf(ERROR, "This message is level %v", ERROR)
|
||||
l.Logf(WARNING, "This message is level %s", WARNING)
|
||||
l.Logc(INFO, func() string { return "This message is level INFO" })
|
||||
l.Trace("This message is level %d", int(TRACE))
|
||||
l.Debug("This message is level %s", DEBUG)
|
||||
l.Fine(func() string { return fmt.Sprintf("This message is level %v", FINE) })
|
||||
l.Finest("This message is level %v", FINEST)
|
||||
l.Finest(FINEST, "is also this message's level")
|
||||
|
||||
l.Close()
|
||||
|
||||
contents, err := ioutil.ReadFile(testLogFile)
|
||||
if err != nil {
|
||||
t.Fatalf("Could not read output log: %s", err)
|
||||
}
|
||||
|
||||
sum := md5.New()
|
||||
sum.Write(contents)
|
||||
if sumstr := hex.EncodeToString(sum.Sum(nil)); sumstr != expected {
|
||||
t.Errorf("--- Log Contents:\n%s---", string(contents))
|
||||
t.Fatalf("Checksum does not match: %s (expecting %s)", sumstr, expected)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCountMallocs(t *testing.T) {
|
||||
const N = 1
|
||||
var m runtime.MemStats
|
||||
getMallocs := func() uint64 {
|
||||
runtime.ReadMemStats(&m)
|
||||
return m.Mallocs
|
||||
}
|
||||
|
||||
// Console logger
|
||||
sl := NewDefaultLogger(INFO)
|
||||
mallocs := 0 - getMallocs()
|
||||
for i := 0; i < N; i++ {
|
||||
sl.Log(WARNING, "here", "This is a WARNING message")
|
||||
}
|
||||
mallocs += getMallocs()
|
||||
fmt.Printf("mallocs per sl.Log((WARNING, \"here\", \"This is a log message\"): %d\n", mallocs/N)
|
||||
|
||||
// Console logger formatted
|
||||
mallocs = 0 - getMallocs()
|
||||
for i := 0; i < N; i++ {
|
||||
sl.Logf(WARNING, "%s is a log message with level %d", "This", WARNING)
|
||||
}
|
||||
mallocs += getMallocs()
|
||||
fmt.Printf("mallocs per sl.Logf(WARNING, \"%%s is a log message with level %%d\", \"This\", WARNING): %d\n", mallocs/N)
|
||||
|
||||
// Console logger (not logged)
|
||||
sl = NewDefaultLogger(INFO)
|
||||
mallocs = 0 - getMallocs()
|
||||
for i := 0; i < N; i++ {
|
||||
sl.Log(DEBUG, "here", "This is a DEBUG log message")
|
||||
}
|
||||
mallocs += getMallocs()
|
||||
fmt.Printf("mallocs per unlogged sl.Log((WARNING, \"here\", \"This is a log message\"): %d\n", mallocs/N)
|
||||
|
||||
// Console logger formatted (not logged)
|
||||
mallocs = 0 - getMallocs()
|
||||
for i := 0; i < N; i++ {
|
||||
sl.Logf(DEBUG, "%s is a log message with level %d", "This", DEBUG)
|
||||
}
|
||||
mallocs += getMallocs()
|
||||
fmt.Printf("mallocs per unlogged sl.Logf(WARNING, \"%%s is a log message with level %%d\", \"This\", WARNING): %d\n", mallocs/N)
|
||||
}
|
||||
|
||||
func TestXMLConfig(t *testing.T) {
|
||||
const (
|
||||
configfile = "example.xml"
|
||||
)
|
||||
|
||||
fd, err := os.Create(configfile)
|
||||
if err != nil {
|
||||
t.Fatalf("Could not open %s for writing: %s", configfile, err)
|
||||
}
|
||||
|
||||
fmt.Fprintln(fd, "<logging>")
|
||||
fmt.Fprintln(fd, " <filter enabled=\"true\">")
|
||||
fmt.Fprintln(fd, " <tag>stdout</tag>")
|
||||
fmt.Fprintln(fd, " <type>console</type>")
|
||||
fmt.Fprintln(fd, " <!-- level is (:?FINEST|FINE|DEBUG|TRACE|INFO|WARNING|ERROR) -->")
|
||||
fmt.Fprintln(fd, " <level>DEBUG</level>")
|
||||
fmt.Fprintln(fd, " </filter>")
|
||||
fmt.Fprintln(fd, " <filter enabled=\"true\">")
|
||||
fmt.Fprintln(fd, " <tag>file</tag>")
|
||||
fmt.Fprintln(fd, " <type>file</type>")
|
||||
fmt.Fprintln(fd, " <level>FINEST</level>")
|
||||
fmt.Fprintln(fd, " <property name=\"filename\">test.log</property>")
|
||||
fmt.Fprintln(fd, " <!--")
|
||||
fmt.Fprintln(fd, " %T - Time (15:04:05 MST)")
|
||||
fmt.Fprintln(fd, " %t - Time (15:04)")
|
||||
fmt.Fprintln(fd, " %D - Date (2006/01/02)")
|
||||
fmt.Fprintln(fd, " %d - Date (01/02/06)")
|
||||
fmt.Fprintln(fd, " %L - Level (FNST, FINE, DEBG, TRAC, WARN, EROR, CRIT)")
|
||||
fmt.Fprintln(fd, " %S - Source")
|
||||
fmt.Fprintln(fd, " %M - Message")
|
||||
fmt.Fprintln(fd, " It ignores unknown format strings (and removes them)")
|
||||
fmt.Fprintln(fd, " Recommended: \"[%D %T] [%L] (%S) %M\"")
|
||||
fmt.Fprintln(fd, " -->")
|
||||
fmt.Fprintln(fd, " <property name=\"format\">[%D %T] [%L] (%S) %M</property>")
|
||||
fmt.Fprintln(fd, " <property name=\"rotate\">false</property> <!-- true enables log rotation, otherwise append -->")
|
||||
fmt.Fprintln(fd, " <property name=\"maxsize\">0M</property> <!-- \\d+[KMG]? Suffixes are in terms of 2**10 -->")
|
||||
fmt.Fprintln(fd, " <property name=\"maxlines\">0K</property> <!-- \\d+[KMG]? Suffixes are in terms of thousands -->")
|
||||
fmt.Fprintln(fd, " <property name=\"daily\">true</property> <!-- Automatically rotates when a log message is written after midnight -->")
|
||||
fmt.Fprintln(fd, " </filter>")
|
||||
fmt.Fprintln(fd, " <filter enabled=\"true\">")
|
||||
fmt.Fprintln(fd, " <tag>xmllog</tag>")
|
||||
fmt.Fprintln(fd, " <type>xml</type>")
|
||||
fmt.Fprintln(fd, " <level>TRACE</level>")
|
||||
fmt.Fprintln(fd, " <property name=\"filename\">trace.xml</property>")
|
||||
fmt.Fprintln(fd, " <property name=\"rotate\">true</property> <!-- true enables log rotation, otherwise append -->")
|
||||
fmt.Fprintln(fd, " <property name=\"maxsize\">100M</property> <!-- \\d+[KMG]? Suffixes are in terms of 2**10 -->")
|
||||
fmt.Fprintln(fd, " <property name=\"maxrecords\">6K</property> <!-- \\d+[KMG]? Suffixes are in terms of thousands -->")
|
||||
fmt.Fprintln(fd, " <property name=\"daily\">false</property> <!-- Automatically rotates when a log message is written after midnight -->")
|
||||
fmt.Fprintln(fd, " </filter>")
|
||||
fmt.Fprintln(fd, " <filter enabled=\"false\"><!-- enabled=false means this logger won't actually be created -->")
|
||||
fmt.Fprintln(fd, " <tag>donotopen</tag>")
|
||||
fmt.Fprintln(fd, " <type>socket</type>")
|
||||
fmt.Fprintln(fd, " <level>FINEST</level>")
|
||||
fmt.Fprintln(fd, " <property name=\"endpoint\">192.168.1.255:12124</property> <!-- recommend UDP broadcast -->")
|
||||
fmt.Fprintln(fd, " <property name=\"protocol\">udp</property> <!-- tcp or udp -->")
|
||||
fmt.Fprintln(fd, " </filter>")
|
||||
fmt.Fprintln(fd, "</logging>")
|
||||
fd.Close()
|
||||
|
||||
log := make(Logger)
|
||||
log.LoadConfiguration(configfile)
|
||||
defer os.Remove("trace.xml")
|
||||
defer os.Remove("test.log")
|
||||
defer log.Close()
|
||||
|
||||
// Make sure we got all loggers
|
||||
if len(log) != 3 {
|
||||
t.Fatalf("XMLConfig: Expected 3 filters, found %d", len(log))
|
||||
}
|
||||
|
||||
// Make sure they're the right keys
|
||||
if _, ok := log["stdout"]; !ok {
|
||||
t.Errorf("XMLConfig: Expected stdout logger")
|
||||
}
|
||||
if _, ok := log["file"]; !ok {
|
||||
t.Fatalf("XMLConfig: Expected file logger")
|
||||
}
|
||||
if _, ok := log["xmllog"]; !ok {
|
||||
t.Fatalf("XMLConfig: Expected xmllog logger")
|
||||
}
|
||||
|
||||
// Make sure they're the right type
|
||||
if _, ok := log["stdout"].LogWriter.(ConsoleLogWriter); !ok {
|
||||
t.Fatalf("XMLConfig: Expected stdout to be ConsoleLogWriter, found %T", log["stdout"].LogWriter)
|
||||
}
|
||||
if _, ok := log["file"].LogWriter.(*FileLogWriter); !ok {
|
||||
t.Fatalf("XMLConfig: Expected file to be *FileLogWriter, found %T", log["file"].LogWriter)
|
||||
}
|
||||
if _, ok := log["xmllog"].LogWriter.(*FileLogWriter); !ok {
|
||||
t.Fatalf("XMLConfig: Expected xmllog to be *FileLogWriter, found %T", log["xmllog"].LogWriter)
|
||||
}
|
||||
|
||||
// Make sure levels are set
|
||||
if lvl := log["stdout"].Level; lvl != DEBUG {
|
||||
t.Errorf("XMLConfig: Expected stdout to be set to level %d, found %d", DEBUG, lvl)
|
||||
}
|
||||
if lvl := log["file"].Level; lvl != FINEST {
|
||||
t.Errorf("XMLConfig: Expected file to be set to level %d, found %d", FINEST, lvl)
|
||||
}
|
||||
if lvl := log["xmllog"].Level; lvl != TRACE {
|
||||
t.Errorf("XMLConfig: Expected xmllog to be set to level %d, found %d", TRACE, lvl)
|
||||
}
|
||||
|
||||
// Make sure the w is open and points to the right file
|
||||
if fname := log["file"].LogWriter.(*FileLogWriter).file.Name(); fname != "test.log" {
|
||||
t.Errorf("XMLConfig: Expected file to have opened %s, found %s", "test.log", fname)
|
||||
}
|
||||
|
||||
// Make sure the XLW is open and points to the right file
|
||||
if fname := log["xmllog"].LogWriter.(*FileLogWriter).file.Name(); fname != "trace.xml" {
|
||||
t.Errorf("XMLConfig: Expected xmllog to have opened %s, found %s", "trace.xml", fname)
|
||||
}
|
||||
|
||||
// Move XML log file
|
||||
os.Rename(configfile, "examples/"+configfile) // Keep this so that an example with the documentation is available
|
||||
}
|
||||
|
||||
func BenchmarkFormatLogRecord(b *testing.B) {
|
||||
const updateEvery = 1
|
||||
rec := &LogRecord{
|
||||
Level: CRITICAL,
|
||||
Created: now,
|
||||
Source: "source",
|
||||
Message: "message",
|
||||
}
|
||||
for i := 0; i < b.N; i++ {
|
||||
rec.Created = rec.Created.Add(1 * time.Second / updateEvery)
|
||||
if i%2 == 0 {
|
||||
FormatLogRecord(FORMAT_DEFAULT, rec)
|
||||
} else {
|
||||
FormatLogRecord(FORMAT_SHORT, rec)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkConsoleLog(b *testing.B) {
|
||||
/* This doesn't seem to work on OS X
|
||||
sink, err := os.Open(os.DevNull)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
if err := syscall.Dup2(int(sink.Fd()), syscall.Stdout); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
*/
|
||||
|
||||
stdout = ioutil.Discard
|
||||
sl := NewDefaultLogger(INFO)
|
||||
for i := 0; i < b.N; i++ {
|
||||
sl.Log(WARNING, "here", "This is a log message")
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkConsoleNotLogged(b *testing.B) {
|
||||
sl := NewDefaultLogger(INFO)
|
||||
for i := 0; i < b.N; i++ {
|
||||
sl.Log(DEBUG, "here", "This is a log message")
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkConsoleUtilLog(b *testing.B) {
|
||||
sl := NewDefaultLogger(INFO)
|
||||
for i := 0; i < b.N; i++ {
|
||||
sl.Info("%s is a log message", "This")
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkConsoleUtilNotLog(b *testing.B) {
|
||||
sl := NewDefaultLogger(INFO)
|
||||
for i := 0; i < b.N; i++ {
|
||||
sl.Debug("%s is a log message", "This")
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkFileLog(b *testing.B) {
|
||||
sl := make(Logger)
|
||||
b.StopTimer()
|
||||
sl.AddFilter("file", INFO, NewFileLogWriter("benchlog.log", false))
|
||||
b.StartTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
sl.Log(WARNING, "here", "This is a log message")
|
||||
}
|
||||
b.StopTimer()
|
||||
os.Remove("benchlog.log")
|
||||
}
|
||||
|
||||
func BenchmarkFileNotLogged(b *testing.B) {
|
||||
sl := make(Logger)
|
||||
b.StopTimer()
|
||||
sl.AddFilter("file", INFO, NewFileLogWriter("benchlog.log", false))
|
||||
b.StartTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
sl.Log(DEBUG, "here", "This is a log message")
|
||||
}
|
||||
b.StopTimer()
|
||||
os.Remove("benchlog.log")
|
||||
}
|
||||
|
||||
func BenchmarkFileUtilLog(b *testing.B) {
|
||||
sl := make(Logger)
|
||||
b.StopTimer()
|
||||
sl.AddFilter("file", INFO, NewFileLogWriter("benchlog.log", false))
|
||||
b.StartTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
sl.Info("%s is a log message", "This")
|
||||
}
|
||||
b.StopTimer()
|
||||
os.Remove("benchlog.log")
|
||||
}
|
||||
|
||||
func BenchmarkFileUtilNotLog(b *testing.B) {
|
||||
sl := make(Logger)
|
||||
b.StopTimer()
|
||||
sl.AddFilter("file", INFO, NewFileLogWriter("benchlog.log", false))
|
||||
b.StartTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
sl.Debug("%s is a log message", "This")
|
||||
}
|
||||
b.StopTimer()
|
||||
os.Remove("benchlog.log")
|
||||
}
|
||||
|
||||
// Benchmark results (darwin amd64 6g)
|
||||
//elog.BenchmarkConsoleLog 100000 22819 ns/op
|
||||
//elog.BenchmarkConsoleNotLogged 2000000 879 ns/op
|
||||
//elog.BenchmarkConsoleUtilLog 50000 34380 ns/op
|
||||
//elog.BenchmarkConsoleUtilNotLog 1000000 1339 ns/op
|
||||
//elog.BenchmarkFileLog 100000 26497 ns/op
|
||||
//elog.BenchmarkFileNotLogged 2000000 821 ns/op
|
||||
//elog.BenchmarkFileUtilLog 50000 33945 ns/op
|
||||
//elog.BenchmarkFileUtilNotLog 1000000 1258 ns/op
|
||||
119
vendor/github.com/armon/go-metrics/circonus/circonus.go
сгенерированный
поставляемый
@@ -1,119 +0,0 @@
|
||||
// Circonus Metrics Sink
|
||||
|
||||
package circonus
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"github.com/armon/go-metrics"
|
||||
cgm "github.com/circonus-labs/circonus-gometrics"
|
||||
)
|
||||
|
||||
// CirconusSink provides an interface to forward metrics to Circonus with
|
||||
// automatic check creation and metric management
|
||||
type CirconusSink struct {
|
||||
metrics *cgm.CirconusMetrics
|
||||
}
|
||||
|
||||
// Config options for CirconusSink
|
||||
// See https://github.com/circonus-labs/circonus-gometrics for configuration options
|
||||
type Config cgm.Config
|
||||
|
||||
// NewCirconusSink - create new metric sink for circonus
|
||||
//
|
||||
// one of the following must be supplied:
|
||||
// - API Token - search for an existing check or create a new check
|
||||
// - API Token + Check Id - the check identified by check id will be used
|
||||
// - API Token + Check Submission URL - the check identified by the submission url will be used
|
||||
// - Check Submission URL - the check identified by the submission url will be used
|
||||
// metric management will be *disabled*
|
||||
//
|
||||
// Note: If submission url is supplied w/o an api token, the public circonus ca cert will be used
|
||||
// to verify the broker for metrics submission.
|
||||
func NewCirconusSink(cc *Config) (*CirconusSink, error) {
|
||||
cfg := cgm.Config{}
|
||||
if cc != nil {
|
||||
cfg = cgm.Config(*cc)
|
||||
}
|
||||
|
||||
metrics, err := cgm.NewCirconusMetrics(&cfg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &CirconusSink{
|
||||
metrics: metrics,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Start submitting metrics to Circonus (flush every SubmitInterval)
|
||||
func (s *CirconusSink) Start() {
|
||||
s.metrics.Start()
|
||||
}
|
||||
|
||||
// Flush manually triggers metric submission to Circonus
|
||||
func (s *CirconusSink) Flush() {
|
||||
s.metrics.Flush()
|
||||
}
|
||||
|
||||
// SetGauge sets value for a gauge metric
|
||||
func (s *CirconusSink) SetGauge(key []string, val float32) {
|
||||
flatKey := s.flattenKey(key)
|
||||
s.metrics.SetGauge(flatKey, int64(val))
|
||||
}
|
||||
|
||||
// SetGaugeWithLabels sets value for a gauge metric with the given labels
|
||||
func (s *CirconusSink) SetGaugeWithLabels(key []string, val float32, labels []metrics.Label) {
|
||||
flatKey := s.flattenKeyLabels(key, labels)
|
||||
s.metrics.SetGauge(flatKey, int64(val))
|
||||
}
|
||||
|
||||
// EmitKey is not implemented in circonus
|
||||
func (s *CirconusSink) EmitKey(key []string, val float32) {
|
||||
// NOP
|
||||
}
|
||||
|
||||
// IncrCounter increments a counter metric
|
||||
func (s *CirconusSink) IncrCounter(key []string, val float32) {
|
||||
flatKey := s.flattenKey(key)
|
||||
s.metrics.IncrementByValue(flatKey, uint64(val))
|
||||
}
|
||||
|
||||
// IncrCounterWithLabels increments a counter metric with the given labels
|
||||
func (s *CirconusSink) IncrCounterWithLabels(key []string, val float32, labels []metrics.Label) {
|
||||
flatKey := s.flattenKeyLabels(key, labels)
|
||||
s.metrics.IncrementByValue(flatKey, uint64(val))
|
||||
}
|
||||
|
||||
// AddSample adds a sample to a histogram metric
|
||||
func (s *CirconusSink) AddSample(key []string, val float32) {
|
||||
flatKey := s.flattenKey(key)
|
||||
s.metrics.RecordValue(flatKey, float64(val))
|
||||
}
|
||||
|
||||
// AddSampleWithLabels adds a sample to a histogram metric with the given labels
|
||||
func (s *CirconusSink) AddSampleWithLabels(key []string, val float32, labels []metrics.Label) {
|
||||
flatKey := s.flattenKeyLabels(key, labels)
|
||||
s.metrics.RecordValue(flatKey, float64(val))
|
||||
}
|
||||
|
||||
// Flattens key to Circonus metric name
|
||||
func (s *CirconusSink) flattenKey(parts []string) string {
|
||||
joined := strings.Join(parts, "`")
|
||||
return strings.Map(func(r rune) rune {
|
||||
switch r {
|
||||
case ' ':
|
||||
return '_'
|
||||
default:
|
||||
return r
|
||||
}
|
||||
}, joined)
|
||||
}
|
||||
|
||||
// Flattens the key along with labels for formatting, removes spaces
|
||||
func (s *CirconusSink) flattenKeyLabels(parts []string, labels []metrics.Label) string {
|
||||
for _, label := range labels {
|
||||
parts = append(parts, label.Value)
|
||||
}
|
||||
return s.flattenKey(parts)
|
||||
}
|
||||
153
vendor/github.com/armon/go-metrics/circonus/circonus_test.go
сгенерированный
поставляемый
@@ -1,153 +0,0 @@
|
||||
package circonus
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestNewCirconusSink(t *testing.T) {
|
||||
|
||||
// test with invalid config (nil)
|
||||
expectedError := errors.New("invalid check manager configuration (no API token AND no submission url)")
|
||||
_, err := NewCirconusSink(nil)
|
||||
if err == nil || err.Error() != expectedError.Error() {
|
||||
t.Errorf("Expected an '%#v' error, got '%#v'", expectedError, err)
|
||||
}
|
||||
|
||||
// test w/submission url and w/o token
|
||||
cfg := &Config{}
|
||||
cfg.CheckManager.Check.SubmissionURL = "http://127.0.0.1:43191/"
|
||||
_, err = NewCirconusSink(cfg)
|
||||
if err != nil {
|
||||
t.Errorf("Expected no error, got '%v'", err)
|
||||
}
|
||||
|
||||
// note: a test with a valid token is *not* done as it *will* create a
|
||||
// check resulting in testing the api more than the circonus sink
|
||||
// see circonus-gometrics/checkmgr/checkmgr_test.go for testing of api token
|
||||
}
|
||||
|
||||
func TestFlattenKey(t *testing.T) {
|
||||
var testKeys = []struct {
|
||||
input []string
|
||||
expected string
|
||||
}{
|
||||
{[]string{"a", "b", "c"}, "a`b`c"},
|
||||
{[]string{"a-a", "b_b", "c/c"}, "a-a`b_b`c/c"},
|
||||
{[]string{"spaces must", "flatten", "to", "underscores"}, "spaces_must`flatten`to`underscores"},
|
||||
}
|
||||
|
||||
c := &CirconusSink{}
|
||||
|
||||
for _, test := range testKeys {
|
||||
if actual := c.flattenKey(test.input); actual != test.expected {
|
||||
t.Fatalf("Flattening %v failed, expected '%s' got '%s'", test.input, test.expected, actual)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func fakeBroker(q chan string) *httptest.Server {
|
||||
handler := func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(200)
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
defer r.Body.Close()
|
||||
body, err := ioutil.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
q <- err.Error()
|
||||
fmt.Fprintln(w, err.Error())
|
||||
} else {
|
||||
q <- string(body)
|
||||
fmt.Fprintln(w, `{"stats":1}`)
|
||||
}
|
||||
}
|
||||
|
||||
return httptest.NewServer(http.HandlerFunc(handler))
|
||||
}
|
||||
|
||||
func TestSetGauge(t *testing.T) {
|
||||
q := make(chan string)
|
||||
|
||||
server := fakeBroker(q)
|
||||
defer server.Close()
|
||||
|
||||
cfg := &Config{}
|
||||
cfg.CheckManager.Check.SubmissionURL = server.URL
|
||||
|
||||
cs, err := NewCirconusSink(cfg)
|
||||
if err != nil {
|
||||
t.Errorf("Expected no error, got '%v'", err)
|
||||
}
|
||||
|
||||
go func() {
|
||||
cs.SetGauge([]string{"foo", "bar"}, 1)
|
||||
cs.Flush()
|
||||
}()
|
||||
|
||||
expect := "{\"foo`bar\":{\"_type\":\"n\",\"_value\":\"1\"}}"
|
||||
actual := <-q
|
||||
|
||||
if actual != expect {
|
||||
t.Errorf("Expected '%s', got '%s'", expect, actual)
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
func TestIncrCounter(t *testing.T) {
|
||||
q := make(chan string)
|
||||
|
||||
server := fakeBroker(q)
|
||||
defer server.Close()
|
||||
|
||||
cfg := &Config{}
|
||||
cfg.CheckManager.Check.SubmissionURL = server.URL
|
||||
|
||||
cs, err := NewCirconusSink(cfg)
|
||||
if err != nil {
|
||||
t.Errorf("Expected no error, got '%v'", err)
|
||||
}
|
||||
|
||||
go func() {
|
||||
cs.IncrCounter([]string{"foo", "bar"}, 1)
|
||||
cs.Flush()
|
||||
}()
|
||||
|
||||
expect := "{\"foo`bar\":{\"_type\":\"n\",\"_value\":1}}"
|
||||
actual := <-q
|
||||
|
||||
if actual != expect {
|
||||
t.Errorf("Expected '%s', got '%s'", expect, actual)
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
func TestAddSample(t *testing.T) {
|
||||
q := make(chan string)
|
||||
|
||||
server := fakeBroker(q)
|
||||
defer server.Close()
|
||||
|
||||
cfg := &Config{}
|
||||
cfg.CheckManager.Check.SubmissionURL = server.URL
|
||||
|
||||
cs, err := NewCirconusSink(cfg)
|
||||
if err != nil {
|
||||
t.Errorf("Expected no error, got '%v'", err)
|
||||
}
|
||||
|
||||
go func() {
|
||||
cs.AddSample([]string{"foo", "bar"}, 1)
|
||||
cs.Flush()
|
||||
}()
|
||||
|
||||
expect := "{\"foo`bar\":{\"_type\":\"n\",\"_value\":[\"H[1.0e+00]=1\"]}}"
|
||||
actual := <-q
|
||||
|
||||
if actual != expect {
|
||||
t.Errorf("Expected '%s', got '%s'", expect, actual)
|
||||
|
||||
}
|
||||
}
|
||||
140
vendor/github.com/armon/go-metrics/datadog/dogstatsd.go
сгенерированный
поставляемый
@@ -1,140 +0,0 @@
|
||||
package datadog
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/DataDog/datadog-go/statsd"
|
||||
"github.com/armon/go-metrics"
|
||||
)
|
||||
|
||||
// DogStatsdSink provides a MetricSink that can be used
|
||||
// with a dogstatsd server. It utilizes the Dogstatsd client at github.com/DataDog/datadog-go/statsd
|
||||
type DogStatsdSink struct {
|
||||
client *statsd.Client
|
||||
hostName string
|
||||
propagateHostname bool
|
||||
}
|
||||
|
||||
// NewDogStatsdSink is used to create a new DogStatsdSink with sane defaults
|
||||
func NewDogStatsdSink(addr string, hostName string) (*DogStatsdSink, error) {
|
||||
client, err := statsd.New(addr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sink := &DogStatsdSink{
|
||||
client: client,
|
||||
hostName: hostName,
|
||||
propagateHostname: false,
|
||||
}
|
||||
return sink, nil
|
||||
}
|
||||
|
||||
// SetTags sets common tags on the Dogstatsd Client that will be sent
|
||||
// along with all dogstatsd packets.
|
||||
// Ref: http://docs.datadoghq.com/guides/dogstatsd/#tags
|
||||
func (s *DogStatsdSink) SetTags(tags []string) {
|
||||
s.client.Tags = tags
|
||||
}
|
||||
|
||||
// EnableHostnamePropagation forces a Dogstatsd `host` tag with the value specified by `s.HostName`
|
||||
// Since the go-metrics package has its own mechanism for attaching a hostname to metrics,
|
||||
// setting the `propagateHostname` flag ensures that `s.HostName` overrides the host tag naively set by the DogStatsd server
|
||||
func (s *DogStatsdSink) EnableHostNamePropagation() {
|
||||
s.propagateHostname = true
|
||||
}
|
||||
|
||||
func (s *DogStatsdSink) flattenKey(parts []string) string {
|
||||
joined := strings.Join(parts, ".")
|
||||
return strings.Map(sanitize, joined)
|
||||
}
|
||||
|
||||
func sanitize(r rune) rune {
|
||||
switch r {
|
||||
case ':':
|
||||
fallthrough
|
||||
case ' ':
|
||||
return '_'
|
||||
default:
|
||||
return r
|
||||
}
|
||||
}
|
||||
|
||||
func (s *DogStatsdSink) parseKey(key []string) ([]string, []metrics.Label) {
|
||||
// Since DogStatsd supports dimensionality via tags on metric keys, this sink's approach is to splice the hostname out of the key in favor of a `host` tag
|
||||
// The `host` tag is either forced here, or set downstream by the DogStatsd server
|
||||
|
||||
var labels []metrics.Label
|
||||
hostName := s.hostName
|
||||
|
||||
// Splice the hostname out of the key
|
||||
for i, el := range key {
|
||||
if el == hostName {
|
||||
key = append(key[:i], key[i+1:]...)
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if s.propagateHostname {
|
||||
labels = append(labels, metrics.Label{"host", hostName})
|
||||
}
|
||||
return key, labels
|
||||
}
|
||||
|
||||
// Implementation of methods in the MetricSink interface
|
||||
|
||||
func (s *DogStatsdSink) SetGauge(key []string, val float32) {
|
||||
s.SetGaugeWithLabels(key, val, nil)
|
||||
}
|
||||
|
||||
func (s *DogStatsdSink) IncrCounter(key []string, val float32) {
|
||||
s.IncrCounterWithLabels(key, val, nil)
|
||||
}
|
||||
|
||||
// EmitKey is not implemented since DogStatsd does not provide a metric type that holds an
|
||||
// arbitrary number of values
|
||||
func (s *DogStatsdSink) EmitKey(key []string, val float32) {
|
||||
}
|
||||
|
||||
func (s *DogStatsdSink) AddSample(key []string, val float32) {
|
||||
s.AddSampleWithLabels(key, val, nil)
|
||||
}
|
||||
|
||||
// The following ...WithLabels methods correspond to Datadog's Tag extension to Statsd.
|
||||
// http://docs.datadoghq.com/guides/dogstatsd/#tags
|
||||
func (s *DogStatsdSink) SetGaugeWithLabels(key []string, val float32, labels []metrics.Label) {
|
||||
flatKey, tags := s.getFlatkeyAndCombinedLabels(key, labels)
|
||||
rate := 1.0
|
||||
s.client.Gauge(flatKey, float64(val), tags, rate)
|
||||
}
|
||||
|
||||
func (s *DogStatsdSink) IncrCounterWithLabels(key []string, val float32, labels []metrics.Label) {
|
||||
flatKey, tags := s.getFlatkeyAndCombinedLabels(key, labels)
|
||||
rate := 1.0
|
||||
s.client.Count(flatKey, int64(val), tags, rate)
|
||||
}
|
||||
|
||||
func (s *DogStatsdSink) AddSampleWithLabels(key []string, val float32, labels []metrics.Label) {
|
||||
flatKey, tags := s.getFlatkeyAndCombinedLabels(key, labels)
|
||||
rate := 1.0
|
||||
s.client.TimeInMilliseconds(flatKey, float64(val), tags, rate)
|
||||
}
|
||||
|
||||
func (s *DogStatsdSink) getFlatkeyAndCombinedLabels(key []string, labels []metrics.Label) (string, []string) {
|
||||
key, parsedLabels := s.parseKey(key)
|
||||
flatKey := s.flattenKey(key)
|
||||
labels = append(labels, parsedLabels...)
|
||||
|
||||
var tags []string
|
||||
for _, label := range labels {
|
||||
label.Name = strings.Map(sanitize, label.Name)
|
||||
label.Value = strings.Map(sanitize, label.Value)
|
||||
if label.Value != "" {
|
||||
tags = append(tags, fmt.Sprintf("%s:%s", label.Name, label.Value))
|
||||
} else {
|
||||
tags = append(tags, label.Name)
|
||||
}
|
||||
}
|
||||
|
||||
return flatKey, tags
|
||||
}
|
||||
150
vendor/github.com/armon/go-metrics/datadog/dogstatsd_test.go
сгенерированный
поставляемый
@@ -1,150 +0,0 @@
|
||||
package datadog
|
||||
|
||||
import (
|
||||
"net"
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"github.com/armon/go-metrics"
|
||||
)
|
||||
|
||||
var EmptyTags []metrics.Label
|
||||
|
||||
const (
|
||||
DogStatsdAddr = "127.0.0.1:7254"
|
||||
HostnameEnabled = true
|
||||
HostnameDisabled = false
|
||||
TestHostname = "test_hostname"
|
||||
)
|
||||
|
||||
func MockGetHostname() string {
|
||||
return TestHostname
|
||||
}
|
||||
|
||||
var ParseKeyTests = []struct {
|
||||
KeyToParse []string
|
||||
Tags []metrics.Label
|
||||
PropagateHostname bool
|
||||
ExpectedKey []string
|
||||
ExpectedTags []metrics.Label
|
||||
}{
|
||||
{[]string{"a", MockGetHostname(), "b", "c"}, EmptyTags, HostnameDisabled, []string{"a", "b", "c"}, EmptyTags},
|
||||
{[]string{"a", "b", "c"}, EmptyTags, HostnameDisabled, []string{"a", "b", "c"}, EmptyTags},
|
||||
{[]string{"a", "b", "c"}, EmptyTags, HostnameEnabled, []string{"a", "b", "c"}, []metrics.Label{{"host", MockGetHostname()}}},
|
||||
}
|
||||
|
||||
var FlattenKeyTests = []struct {
|
||||
KeyToFlatten []string
|
||||
Expected string
|
||||
}{
|
||||
{[]string{"a", "b", "c"}, "a.b.c"},
|
||||
{[]string{"spaces must", "flatten", "to", "underscores"}, "spaces_must.flatten.to.underscores"},
|
||||
}
|
||||
|
||||
var MetricSinkTests = []struct {
|
||||
Method string
|
||||
Metric []string
|
||||
Value interface{}
|
||||
Tags []metrics.Label
|
||||
PropagateHostname bool
|
||||
Expected string
|
||||
}{
|
||||
{"SetGauge", []string{"foo", "bar"}, float32(42), EmptyTags, HostnameDisabled, "foo.bar:42.000000|g"},
|
||||
{"SetGauge", []string{"foo", "bar", "baz"}, float32(42), EmptyTags, HostnameDisabled, "foo.bar.baz:42.000000|g"},
|
||||
{"AddSample", []string{"sample", "thing"}, float32(4), EmptyTags, HostnameDisabled, "sample.thing:4.000000|ms"},
|
||||
{"IncrCounter", []string{"count", "me"}, float32(3), EmptyTags, HostnameDisabled, "count.me:3|c"},
|
||||
|
||||
{"SetGauge", []string{"foo", "baz"}, float32(42), []metrics.Label{{"my_tag", ""}}, HostnameDisabled, "foo.baz:42.000000|g|#my_tag"},
|
||||
{"SetGauge", []string{"foo", "baz"}, float32(42), []metrics.Label{{"my tag", "my_value"}}, HostnameDisabled, "foo.baz:42.000000|g|#my_tag:my_value"},
|
||||
{"SetGauge", []string{"foo", "bar"}, float32(42), []metrics.Label{{"my_tag", "my_value"}, {"other_tag", "other_value"}}, HostnameDisabled, "foo.bar:42.000000|g|#my_tag:my_value,other_tag:other_value"},
|
||||
{"SetGauge", []string{"foo", "bar"}, float32(42), []metrics.Label{{"my_tag", "my_value"}, {"other_tag", "other_value"}}, HostnameEnabled, "foo.bar:42.000000|g|#my_tag:my_value,other_tag:other_value,host:test_hostname"},
|
||||
}
|
||||
|
||||
func mockNewDogStatsdSink(addr string, labels []metrics.Label, tagWithHostname bool) *DogStatsdSink {
|
||||
dog, _ := NewDogStatsdSink(addr, MockGetHostname())
|
||||
_, tags := dog.getFlatkeyAndCombinedLabels(nil, labels)
|
||||
dog.SetTags(tags)
|
||||
if tagWithHostname {
|
||||
dog.EnableHostNamePropagation()
|
||||
}
|
||||
|
||||
return dog
|
||||
}
|
||||
|
||||
func setupTestServerAndBuffer(t *testing.T) (*net.UDPConn, []byte) {
|
||||
udpAddr, err := net.ResolveUDPAddr("udp", DogStatsdAddr)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
server, err := net.ListenUDP("udp", udpAddr)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return server, make([]byte, 1024)
|
||||
}
|
||||
|
||||
func TestParseKey(t *testing.T) {
|
||||
for _, tt := range ParseKeyTests {
|
||||
dog := mockNewDogStatsdSink(DogStatsdAddr, tt.Tags, tt.PropagateHostname)
|
||||
key, tags := dog.parseKey(tt.KeyToParse)
|
||||
|
||||
if !reflect.DeepEqual(key, tt.ExpectedKey) {
|
||||
t.Fatalf("Key Parsing failed for %v", tt.KeyToParse)
|
||||
}
|
||||
|
||||
if !reflect.DeepEqual(tags, tt.ExpectedTags) {
|
||||
t.Fatalf("Tag Parsing Failed for %v, %v != %v", tt.KeyToParse, tags, tt.ExpectedTags)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestFlattenKey(t *testing.T) {
|
||||
dog := mockNewDogStatsdSink(DogStatsdAddr, EmptyTags, HostnameDisabled)
|
||||
for _, tt := range FlattenKeyTests {
|
||||
if !reflect.DeepEqual(dog.flattenKey(tt.KeyToFlatten), tt.Expected) {
|
||||
t.Fatalf("Flattening %v failed", tt.KeyToFlatten)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestMetricSink(t *testing.T) {
|
||||
server, buf := setupTestServerAndBuffer(t)
|
||||
defer server.Close()
|
||||
|
||||
for _, tt := range MetricSinkTests {
|
||||
dog := mockNewDogStatsdSink(DogStatsdAddr, tt.Tags, tt.PropagateHostname)
|
||||
method := reflect.ValueOf(dog).MethodByName(tt.Method)
|
||||
method.Call([]reflect.Value{
|
||||
reflect.ValueOf(tt.Metric),
|
||||
reflect.ValueOf(tt.Value)})
|
||||
assertServerMatchesExpected(t, server, buf, tt.Expected)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTaggableMetrics(t *testing.T) {
|
||||
server, buf := setupTestServerAndBuffer(t)
|
||||
defer server.Close()
|
||||
|
||||
dog := mockNewDogStatsdSink(DogStatsdAddr, EmptyTags, HostnameDisabled)
|
||||
|
||||
dog.AddSampleWithLabels([]string{"sample", "thing"}, float32(4), []metrics.Label{{"tagkey", "tagvalue"}})
|
||||
assertServerMatchesExpected(t, server, buf, "sample.thing:4.000000|ms|#tagkey:tagvalue")
|
||||
|
||||
dog.SetGaugeWithLabels([]string{"sample", "thing"}, float32(4), []metrics.Label{{"tagkey", "tagvalue"}})
|
||||
assertServerMatchesExpected(t, server, buf, "sample.thing:4.000000|g|#tagkey:tagvalue")
|
||||
|
||||
dog.IncrCounterWithLabels([]string{"sample", "thing"}, float32(4), []metrics.Label{{"tagkey", "tagvalue"}})
|
||||
assertServerMatchesExpected(t, server, buf, "sample.thing:4|c|#tagkey:tagvalue")
|
||||
|
||||
dog = mockNewDogStatsdSink(DogStatsdAddr, []metrics.Label{{Name: "global"}}, HostnameEnabled) // with hostname, global tags
|
||||
dog.IncrCounterWithLabels([]string{"sample", "thing"}, float32(4), []metrics.Label{{"tagkey", "tagvalue"}})
|
||||
assertServerMatchesExpected(t, server, buf, "sample.thing:4|c|#global,tagkey:tagvalue,host:test_hostname")
|
||||
}
|
||||
|
||||
func assertServerMatchesExpected(t *testing.T, server *net.UDPConn, buf []byte, expected string) {
|
||||
n, _ := server.Read(buf)
|
||||
msg := buf[:n]
|
||||
if string(msg) != expected {
|
||||
t.Fatalf("Line %s does not match expected: %s", string(msg), expected)
|
||||
}
|
||||
}
|
||||
33
vendor/github.com/armon/go-metrics/inmem.go
сгенерированный
поставляемый
@@ -232,8 +232,37 @@ func (i *InmemSink) Data() []*IntervalMetrics {
|
||||
i.intervalLock.RLock()
|
||||
defer i.intervalLock.RUnlock()
|
||||
|
||||
intervals := make([]*IntervalMetrics, len(i.intervals))
|
||||
copy(intervals, i.intervals)
|
||||
n := len(i.intervals)
|
||||
intervals := make([]*IntervalMetrics, n)
|
||||
|
||||
copy(intervals[:n-1], i.intervals[:n-1])
|
||||
current := i.intervals[n-1]
|
||||
|
||||
// make its own copy for current interval
|
||||
intervals[n-1] = &IntervalMetrics{}
|
||||
copyCurrent := intervals[n-1]
|
||||
current.RLock()
|
||||
*copyCurrent = *current
|
||||
|
||||
copyCurrent.Gauges = make(map[string]GaugeValue, len(current.Gauges))
|
||||
for k, v := range current.Gauges {
|
||||
copyCurrent.Gauges[k] = v
|
||||
}
|
||||
// saved values will be not change, just copy its link
|
||||
copyCurrent.Points = make(map[string][]float32, len(current.Points))
|
||||
for k, v := range current.Points {
|
||||
copyCurrent.Points[k] = v
|
||||
}
|
||||
copyCurrent.Counters = make(map[string]SampledValue, len(current.Counters))
|
||||
for k, v := range current.Counters {
|
||||
copyCurrent.Counters[k] = v
|
||||
}
|
||||
copyCurrent.Samples = make(map[string]SampledValue, len(current.Samples))
|
||||
for k, v := range current.Samples {
|
||||
copyCurrent.Samples[k] = v
|
||||
}
|
||||
current.RUnlock()
|
||||
|
||||
return intervals
|
||||
}
|
||||
|
||||
|
||||
133
vendor/github.com/armon/go-metrics/inmem_endpoint_test.go
сгенерированный
поставляемый
@@ -1,133 +0,0 @@
|
||||
package metrics
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/pascaldekloe/goe/verify"
|
||||
)
|
||||
|
||||
func TestDisplayMetrics(t *testing.T) {
|
||||
interval := 10 * time.Millisecond
|
||||
inm := NewInmemSink(interval, 50*time.Millisecond)
|
||||
|
||||
// Add data points
|
||||
inm.SetGauge([]string{"foo", "bar"}, 42)
|
||||
inm.SetGaugeWithLabels([]string{"foo", "bar"}, 23, []Label{{"a", "b"}})
|
||||
inm.EmitKey([]string{"foo", "bar"}, 42)
|
||||
inm.IncrCounter([]string{"foo", "bar"}, 20)
|
||||
inm.IncrCounter([]string{"foo", "bar"}, 22)
|
||||
inm.IncrCounterWithLabels([]string{"foo", "bar"}, 20, []Label{{"a", "b"}})
|
||||
inm.IncrCounterWithLabels([]string{"foo", "bar"}, 40, []Label{{"a", "b"}})
|
||||
inm.AddSample([]string{"foo", "bar"}, 20)
|
||||
inm.AddSample([]string{"foo", "bar"}, 24)
|
||||
inm.AddSampleWithLabels([]string{"foo", "bar"}, 23, []Label{{"a", "b"}})
|
||||
inm.AddSampleWithLabels([]string{"foo", "bar"}, 33, []Label{{"a", "b"}})
|
||||
|
||||
data := inm.Data()
|
||||
if len(data) != 1 {
|
||||
t.Fatalf("bad: %v", data)
|
||||
}
|
||||
|
||||
expected := MetricsSummary{
|
||||
Timestamp: data[0].Interval.Round(time.Second).UTC().String(),
|
||||
Gauges: []GaugeValue{
|
||||
{
|
||||
Name: "foo.bar",
|
||||
Hash: "foo.bar",
|
||||
Value: float32(42),
|
||||
DisplayLabels: map[string]string{},
|
||||
},
|
||||
{
|
||||
Name: "foo.bar",
|
||||
Hash: "foo.bar;a=b",
|
||||
Value: float32(23),
|
||||
DisplayLabels: map[string]string{"a": "b"},
|
||||
},
|
||||
},
|
||||
Points: []PointValue{
|
||||
{
|
||||
Name: "foo.bar",
|
||||
Points: []float32{42},
|
||||
},
|
||||
},
|
||||
Counters: []SampledValue{
|
||||
{
|
||||
Name: "foo.bar",
|
||||
Hash: "foo.bar",
|
||||
AggregateSample: &AggregateSample{
|
||||
Count: 2,
|
||||
Min: 20,
|
||||
Max: 22,
|
||||
Sum: 42,
|
||||
SumSq: 884,
|
||||
Rate: 4200,
|
||||
},
|
||||
Mean: 21,
|
||||
Stddev: 1.4142135623730951,
|
||||
},
|
||||
{
|
||||
Name: "foo.bar",
|
||||
Hash: "foo.bar;a=b",
|
||||
AggregateSample: &AggregateSample{
|
||||
Count: 2,
|
||||
Min: 20,
|
||||
Max: 40,
|
||||
Sum: 60,
|
||||
SumSq: 2000,
|
||||
Rate: 6000,
|
||||
},
|
||||
Mean: 30,
|
||||
Stddev: 14.142135623730951,
|
||||
DisplayLabels: map[string]string{"a": "b"},
|
||||
},
|
||||
},
|
||||
Samples: []SampledValue{
|
||||
{
|
||||
Name: "foo.bar",
|
||||
Hash: "foo.bar",
|
||||
AggregateSample: &AggregateSample{
|
||||
Count: 2,
|
||||
Min: 20,
|
||||
Max: 24,
|
||||
Sum: 44,
|
||||
SumSq: 976,
|
||||
Rate: 4400,
|
||||
},
|
||||
Mean: 22,
|
||||
Stddev: 2.8284271247461903,
|
||||
},
|
||||
{
|
||||
Name: "foo.bar",
|
||||
Hash: "foo.bar;a=b",
|
||||
AggregateSample: &AggregateSample{
|
||||
Count: 2,
|
||||
Min: 23,
|
||||
Max: 33,
|
||||
Sum: 56,
|
||||
SumSq: 1618,
|
||||
Rate: 5600,
|
||||
},
|
||||
Mean: 28,
|
||||
Stddev: 7.0710678118654755,
|
||||
DisplayLabels: map[string]string{"a": "b"},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
raw, err := inm.DisplayMetrics(nil, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("err: %v", err)
|
||||
}
|
||||
result := raw.(MetricsSummary)
|
||||
|
||||
// Ignore the LastUpdated field, we don't export that anyway
|
||||
for i, got := range result.Counters {
|
||||
expected.Counters[i].LastUpdated = got.LastUpdated
|
||||
}
|
||||
for i, got := range result.Samples {
|
||||
expected.Samples[i].LastUpdated = got.LastUpdated
|
||||
}
|
||||
|
||||
verify.Values(t, "all", result, expected)
|
||||
}
|
||||
58
vendor/github.com/armon/go-metrics/inmem_signal_test.go
сгенерированный
поставляемый
@@ -1,58 +0,0 @@
|
||||
package metrics
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"os"
|
||||
"strings"
|
||||
"syscall"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestInmemSignal(t *testing.T) {
|
||||
buf := bytes.NewBuffer(nil)
|
||||
inm := NewInmemSink(10*time.Millisecond, 50*time.Millisecond)
|
||||
sig := NewInmemSignal(inm, syscall.SIGUSR1, buf)
|
||||
defer sig.Stop()
|
||||
|
||||
inm.SetGauge([]string{"foo"}, 42)
|
||||
inm.EmitKey([]string{"bar"}, 42)
|
||||
inm.IncrCounter([]string{"baz"}, 42)
|
||||
inm.AddSample([]string{"wow"}, 42)
|
||||
inm.SetGaugeWithLabels([]string{"asdf"}, 42, []Label{{"a", "b"}})
|
||||
inm.IncrCounterWithLabels([]string{"qwer"}, 42, []Label{{"a", "b"}})
|
||||
inm.AddSampleWithLabels([]string{"zxcv"}, 42, []Label{{"a", "b"}})
|
||||
|
||||
// Wait for period to end
|
||||
time.Sleep(15 * time.Millisecond)
|
||||
|
||||
// Send signal!
|
||||
syscall.Kill(os.Getpid(), syscall.SIGUSR1)
|
||||
|
||||
// Wait for flush
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
|
||||
// Check the output
|
||||
out := string(buf.Bytes())
|
||||
if !strings.Contains(out, "[G] 'foo': 42") {
|
||||
t.Fatalf("bad: %v", out)
|
||||
}
|
||||
if !strings.Contains(out, "[P] 'bar': 42") {
|
||||
t.Fatalf("bad: %v", out)
|
||||
}
|
||||
if !strings.Contains(out, "[C] 'baz': Count: 1 Sum: 42") {
|
||||
t.Fatalf("bad: %v", out)
|
||||
}
|
||||
if !strings.Contains(out, "[S] 'wow': Count: 1 Sum: 42") {
|
||||
t.Fatalf("bad: %v", out)
|
||||
}
|
||||
if !strings.Contains(out, "[G] 'asdf.b': 42") {
|
||||
t.Fatalf("bad: %v", out)
|
||||
}
|
||||
if !strings.Contains(out, "[C] 'qwer.b': Count: 1 Sum: 42") {
|
||||
t.Fatalf("bad: %v", out)
|
||||
}
|
||||
if !strings.Contains(out, "[S] 'zxcv.b': Count: 1 Sum: 42") {
|
||||
t.Fatalf("bad: %v", out)
|
||||
}
|
||||
}
|
||||
190
vendor/github.com/armon/go-metrics/inmem_test.go
сгенерированный
поставляемый
@@ -1,190 +0,0 @@
|
||||
package metrics
|
||||
|
||||
import (
|
||||
"math"
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestInmemSink(t *testing.T) {
|
||||
inm := NewInmemSink(10*time.Millisecond, 50*time.Millisecond)
|
||||
|
||||
data := inm.Data()
|
||||
if len(data) != 1 {
|
||||
t.Fatalf("bad: %v", data)
|
||||
}
|
||||
|
||||
// Add data points
|
||||
inm.SetGauge([]string{"foo", "bar"}, 42)
|
||||
inm.SetGaugeWithLabels([]string{"foo", "bar"}, 23, []Label{{"a", "b"}})
|
||||
inm.EmitKey([]string{"foo", "bar"}, 42)
|
||||
inm.IncrCounter([]string{"foo", "bar"}, 20)
|
||||
inm.IncrCounter([]string{"foo", "bar"}, 22)
|
||||
inm.IncrCounterWithLabels([]string{"foo", "bar"}, 20, []Label{{"a", "b"}})
|
||||
inm.IncrCounterWithLabels([]string{"foo", "bar"}, 22, []Label{{"a", "b"}})
|
||||
inm.AddSample([]string{"foo", "bar"}, 20)
|
||||
inm.AddSample([]string{"foo", "bar"}, 22)
|
||||
inm.AddSampleWithLabels([]string{"foo", "bar"}, 23, []Label{{"a", "b"}})
|
||||
|
||||
data = inm.Data()
|
||||
if len(data) != 1 {
|
||||
t.Fatalf("bad: %v", data)
|
||||
}
|
||||
|
||||
intvM := data[0]
|
||||
intvM.RLock()
|
||||
|
||||
if time.Now().Sub(intvM.Interval) > 10*time.Millisecond {
|
||||
t.Fatalf("interval too old")
|
||||
}
|
||||
if intvM.Gauges["foo.bar"].Value != 42 {
|
||||
t.Fatalf("bad val: %v", intvM.Gauges)
|
||||
}
|
||||
if intvM.Gauges["foo.bar;a=b"].Value != 23 {
|
||||
t.Fatalf("bad val: %v", intvM.Gauges)
|
||||
}
|
||||
if intvM.Points["foo.bar"][0] != 42 {
|
||||
t.Fatalf("bad val: %v", intvM.Points)
|
||||
}
|
||||
|
||||
for _, agg := range []SampledValue{intvM.Counters["foo.bar"], intvM.Counters["foo.bar;a=b"]} {
|
||||
if agg.Count != 2 {
|
||||
t.Fatalf("bad val: %v", agg)
|
||||
}
|
||||
if agg.Rate != 4200 {
|
||||
t.Fatalf("bad val: %v", agg.Rate)
|
||||
}
|
||||
if agg.Sum != 42 {
|
||||
t.Fatalf("bad val: %v", agg)
|
||||
}
|
||||
if agg.SumSq != 884 {
|
||||
t.Fatalf("bad val: %v", agg)
|
||||
}
|
||||
if agg.Min != 20 {
|
||||
t.Fatalf("bad val: %v", agg)
|
||||
}
|
||||
if agg.Max != 22 {
|
||||
t.Fatalf("bad val: %v", agg)
|
||||
}
|
||||
if agg.AggregateSample.Mean() != 21 {
|
||||
t.Fatalf("bad val: %v", agg)
|
||||
}
|
||||
if agg.AggregateSample.Stddev() != math.Sqrt(2) {
|
||||
t.Fatalf("bad val: %v", agg)
|
||||
}
|
||||
|
||||
if agg.LastUpdated.IsZero() {
|
||||
t.Fatalf("agg.LastUpdated is not set: %v", agg)
|
||||
}
|
||||
|
||||
diff := time.Now().Sub(agg.LastUpdated).Seconds()
|
||||
if diff > 1 {
|
||||
t.Fatalf("time diff too great: %f", diff)
|
||||
}
|
||||
}
|
||||
|
||||
if _, ok := intvM.Samples["foo.bar"]; !ok {
|
||||
t.Fatalf("missing sample")
|
||||
}
|
||||
|
||||
if _, ok := intvM.Samples["foo.bar;a=b"]; !ok {
|
||||
t.Fatalf("missing sample")
|
||||
}
|
||||
|
||||
intvM.RUnlock()
|
||||
|
||||
for i := 1; i < 10; i++ {
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
inm.SetGauge([]string{"foo", "bar"}, 42)
|
||||
data = inm.Data()
|
||||
if len(data) != min(i+1, 5) {
|
||||
t.Fatalf("bad: %v", data)
|
||||
}
|
||||
}
|
||||
|
||||
// Should not exceed 5 intervals!
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
inm.SetGauge([]string{"foo", "bar"}, 42)
|
||||
data = inm.Data()
|
||||
if len(data) != 5 {
|
||||
t.Fatalf("bad: %v", data)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewInmemSinkFromURL(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
desc string
|
||||
input string
|
||||
expectErr string
|
||||
expectInterval time.Duration
|
||||
expectRetain time.Duration
|
||||
}{
|
||||
{
|
||||
desc: "interval and duration are set via query params",
|
||||
input: "inmem://?interval=11s&retain=22s",
|
||||
expectInterval: duration(t, "11s"),
|
||||
expectRetain: duration(t, "22s"),
|
||||
},
|
||||
{
|
||||
desc: "interval is required",
|
||||
input: "inmem://?retain=22s",
|
||||
expectErr: "Bad 'interval' param",
|
||||
},
|
||||
{
|
||||
desc: "interval must be a duration",
|
||||
input: "inmem://?retain=30s&interval=HIYA",
|
||||
expectErr: "Bad 'interval' param",
|
||||
},
|
||||
{
|
||||
desc: "retain is required",
|
||||
input: "inmem://?interval=30s",
|
||||
expectErr: "Bad 'retain' param",
|
||||
},
|
||||
{
|
||||
desc: "retain must be a valid duration",
|
||||
input: "inmem://?interval=30s&retain=HELLO",
|
||||
expectErr: "Bad 'retain' param",
|
||||
},
|
||||
} {
|
||||
t.Run(tc.desc, func(t *testing.T) {
|
||||
u, err := url.Parse(tc.input)
|
||||
if err != nil {
|
||||
t.Fatalf("error parsing URL: %s", err)
|
||||
}
|
||||
ms, err := NewInmemSinkFromURL(u)
|
||||
if tc.expectErr != "" {
|
||||
if !strings.Contains(err.Error(), tc.expectErr) {
|
||||
t.Fatalf("expected err: %q, to contain: %q", err, tc.expectErr)
|
||||
}
|
||||
} else {
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected err: %s", err)
|
||||
}
|
||||
is := ms.(*InmemSink)
|
||||
if is.interval != tc.expectInterval {
|
||||
t.Fatalf("expected interval %s, got: %s", tc.expectInterval, is.interval)
|
||||
}
|
||||
if is.retain != tc.expectRetain {
|
||||
t.Fatalf("expected retain %s, got: %s", tc.expectRetain, is.retain)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func min(a, b int) int {
|
||||
if a < b {
|
||||
return a
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
func duration(t *testing.T, s string) time.Duration {
|
||||
dur, err := time.ParseDuration(s)
|
||||
if err != nil {
|
||||
t.Fatalf("error parsing duration: %s", err)
|
||||
}
|
||||
return dur
|
||||
}
|
||||
411
vendor/github.com/armon/go-metrics/metrics_test.go
сгенерированный
поставляемый
@@ -1,411 +0,0 @@
|
||||
package metrics
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"runtime"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func mockMetric() (*MockSink, *Metrics) {
|
||||
m := &MockSink{}
|
||||
met := &Metrics{Config: Config{FilterDefault: true}, sink: m}
|
||||
return m, met
|
||||
}
|
||||
|
||||
func TestMetrics_SetGauge(t *testing.T) {
|
||||
m, met := mockMetric()
|
||||
met.SetGauge([]string{"key"}, float32(1))
|
||||
if m.keys[0][0] != "key" {
|
||||
t.Fatalf("")
|
||||
}
|
||||
if m.vals[0] != 1 {
|
||||
t.Fatalf("")
|
||||
}
|
||||
|
||||
m, met = mockMetric()
|
||||
labels := []Label{{"a", "b"}}
|
||||
met.SetGaugeWithLabels([]string{"key"}, float32(1), labels)
|
||||
if m.keys[0][0] != "key" {
|
||||
t.Fatalf("")
|
||||
}
|
||||
if m.vals[0] != 1 {
|
||||
t.Fatalf("")
|
||||
}
|
||||
if !reflect.DeepEqual(m.labels[0], labels) {
|
||||
t.Fatalf("")
|
||||
}
|
||||
|
||||
m, met = mockMetric()
|
||||
met.HostName = "test"
|
||||
met.EnableHostname = true
|
||||
met.SetGauge([]string{"key"}, float32(1))
|
||||
if m.keys[0][0] != "test" || m.keys[0][1] != "key" {
|
||||
t.Fatalf("")
|
||||
}
|
||||
if m.vals[0] != 1 {
|
||||
t.Fatalf("")
|
||||
}
|
||||
|
||||
m, met = mockMetric()
|
||||
met.EnableTypePrefix = true
|
||||
met.SetGauge([]string{"key"}, float32(1))
|
||||
if m.keys[0][0] != "gauge" || m.keys[0][1] != "key" {
|
||||
t.Fatalf("")
|
||||
}
|
||||
if m.vals[0] != 1 {
|
||||
t.Fatalf("")
|
||||
}
|
||||
|
||||
m, met = mockMetric()
|
||||
met.ServiceName = "service"
|
||||
met.SetGauge([]string{"key"}, float32(1))
|
||||
if m.keys[0][0] != "service" || m.keys[0][1] != "key" {
|
||||
t.Fatalf("")
|
||||
}
|
||||
if m.vals[0] != 1 {
|
||||
t.Fatalf("")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMetrics_EmitKey(t *testing.T) {
|
||||
m, met := mockMetric()
|
||||
met.EmitKey([]string{"key"}, float32(1))
|
||||
if m.keys[0][0] != "key" {
|
||||
t.Fatalf("")
|
||||
}
|
||||
if m.vals[0] != 1 {
|
||||
t.Fatalf("")
|
||||
}
|
||||
|
||||
m, met = mockMetric()
|
||||
met.EnableTypePrefix = true
|
||||
met.EmitKey([]string{"key"}, float32(1))
|
||||
if m.keys[0][0] != "kv" || m.keys[0][1] != "key" {
|
||||
t.Fatalf("")
|
||||
}
|
||||
if m.vals[0] != 1 {
|
||||
t.Fatalf("")
|
||||
}
|
||||
|
||||
m, met = mockMetric()
|
||||
met.ServiceName = "service"
|
||||
met.EmitKey([]string{"key"}, float32(1))
|
||||
if m.keys[0][0] != "service" || m.keys[0][1] != "key" {
|
||||
t.Fatalf("")
|
||||
}
|
||||
if m.vals[0] != 1 {
|
||||
t.Fatalf("")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMetrics_IncrCounter(t *testing.T) {
|
||||
m, met := mockMetric()
|
||||
met.IncrCounter([]string{"key"}, float32(1))
|
||||
if m.keys[0][0] != "key" {
|
||||
t.Fatalf("")
|
||||
}
|
||||
if m.vals[0] != 1 {
|
||||
t.Fatalf("")
|
||||
}
|
||||
|
||||
m, met = mockMetric()
|
||||
labels := []Label{{"a", "b"}}
|
||||
met.IncrCounterWithLabels([]string{"key"}, float32(1), labels)
|
||||
if m.keys[0][0] != "key" {
|
||||
t.Fatalf("")
|
||||
}
|
||||
if m.vals[0] != 1 {
|
||||
t.Fatalf("")
|
||||
}
|
||||
if !reflect.DeepEqual(m.labels[0], labels) {
|
||||
t.Fatalf("")
|
||||
}
|
||||
|
||||
m, met = mockMetric()
|
||||
met.EnableTypePrefix = true
|
||||
met.IncrCounter([]string{"key"}, float32(1))
|
||||
if m.keys[0][0] != "counter" || m.keys[0][1] != "key" {
|
||||
t.Fatalf("")
|
||||
}
|
||||
if m.vals[0] != 1 {
|
||||
t.Fatalf("")
|
||||
}
|
||||
|
||||
m, met = mockMetric()
|
||||
met.ServiceName = "service"
|
||||
met.IncrCounter([]string{"key"}, float32(1))
|
||||
if m.keys[0][0] != "service" || m.keys[0][1] != "key" {
|
||||
t.Fatalf("")
|
||||
}
|
||||
if m.vals[0] != 1 {
|
||||
t.Fatalf("")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMetrics_AddSample(t *testing.T) {
|
||||
m, met := mockMetric()
|
||||
met.AddSample([]string{"key"}, float32(1))
|
||||
if m.keys[0][0] != "key" {
|
||||
t.Fatalf("")
|
||||
}
|
||||
if m.vals[0] != 1 {
|
||||
t.Fatalf("")
|
||||
}
|
||||
|
||||
m, met = mockMetric()
|
||||
labels := []Label{{"a", "b"}}
|
||||
met.AddSampleWithLabels([]string{"key"}, float32(1), labels)
|
||||
if m.keys[0][0] != "key" {
|
||||
t.Fatalf("")
|
||||
}
|
||||
if m.vals[0] != 1 {
|
||||
t.Fatalf("")
|
||||
}
|
||||
if !reflect.DeepEqual(m.labels[0], labels) {
|
||||
t.Fatalf("")
|
||||
}
|
||||
|
||||
m, met = mockMetric()
|
||||
met.EnableTypePrefix = true
|
||||
met.AddSample([]string{"key"}, float32(1))
|
||||
if m.keys[0][0] != "sample" || m.keys[0][1] != "key" {
|
||||
t.Fatalf("")
|
||||
}
|
||||
if m.vals[0] != 1 {
|
||||
t.Fatalf("")
|
||||
}
|
||||
|
||||
m, met = mockMetric()
|
||||
met.ServiceName = "service"
|
||||
met.AddSample([]string{"key"}, float32(1))
|
||||
if m.keys[0][0] != "service" || m.keys[0][1] != "key" {
|
||||
t.Fatalf("")
|
||||
}
|
||||
if m.vals[0] != 1 {
|
||||
t.Fatalf("")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMetrics_MeasureSince(t *testing.T) {
|
||||
m, met := mockMetric()
|
||||
met.TimerGranularity = time.Millisecond
|
||||
n := time.Now()
|
||||
met.MeasureSince([]string{"key"}, n)
|
||||
if m.keys[0][0] != "key" {
|
||||
t.Fatalf("")
|
||||
}
|
||||
if m.vals[0] > 0.1 {
|
||||
t.Fatalf("")
|
||||
}
|
||||
|
||||
m, met = mockMetric()
|
||||
met.TimerGranularity = time.Millisecond
|
||||
labels := []Label{{"a", "b"}}
|
||||
met.MeasureSinceWithLabels([]string{"key"}, n, labels)
|
||||
if m.keys[0][0] != "key" {
|
||||
t.Fatalf("")
|
||||
}
|
||||
if m.vals[0] > 0.1 {
|
||||
t.Fatalf("")
|
||||
}
|
||||
if !reflect.DeepEqual(m.labels[0], labels) {
|
||||
t.Fatalf("")
|
||||
}
|
||||
|
||||
m, met = mockMetric()
|
||||
met.TimerGranularity = time.Millisecond
|
||||
met.EnableTypePrefix = true
|
||||
met.MeasureSince([]string{"key"}, n)
|
||||
if m.keys[0][0] != "timer" || m.keys[0][1] != "key" {
|
||||
t.Fatalf("")
|
||||
}
|
||||
if m.vals[0] > 0.1 {
|
||||
t.Fatalf("")
|
||||
}
|
||||
|
||||
m, met = mockMetric()
|
||||
met.TimerGranularity = time.Millisecond
|
||||
met.ServiceName = "service"
|
||||
met.MeasureSince([]string{"key"}, n)
|
||||
if m.keys[0][0] != "service" || m.keys[0][1] != "key" {
|
||||
t.Fatalf("")
|
||||
}
|
||||
if m.vals[0] > 0.1 {
|
||||
t.Fatalf("")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMetrics_EmitRuntimeStats(t *testing.T) {
|
||||
runtime.GC()
|
||||
m, met := mockMetric()
|
||||
met.emitRuntimeStats()
|
||||
|
||||
if m.keys[0][0] != "runtime" || m.keys[0][1] != "num_goroutines" {
|
||||
t.Fatalf("bad key %v", m.keys)
|
||||
}
|
||||
if m.vals[0] <= 1 {
|
||||
t.Fatalf("bad val: %v", m.vals)
|
||||
}
|
||||
|
||||
if m.keys[1][0] != "runtime" || m.keys[1][1] != "alloc_bytes" {
|
||||
t.Fatalf("bad key %v", m.keys)
|
||||
}
|
||||
if m.vals[1] <= 40000 {
|
||||
t.Fatalf("bad val: %v", m.vals)
|
||||
}
|
||||
|
||||
if m.keys[2][0] != "runtime" || m.keys[2][1] != "sys_bytes" {
|
||||
t.Fatalf("bad key %v", m.keys)
|
||||
}
|
||||
if m.vals[2] <= 100000 {
|
||||
t.Fatalf("bad val: %v", m.vals)
|
||||
}
|
||||
|
||||
if m.keys[3][0] != "runtime" || m.keys[3][1] != "malloc_count" {
|
||||
t.Fatalf("bad key %v", m.keys)
|
||||
}
|
||||
if m.vals[3] <= 100 {
|
||||
t.Fatalf("bad val: %v", m.vals)
|
||||
}
|
||||
|
||||
if m.keys[4][0] != "runtime" || m.keys[4][1] != "free_count" {
|
||||
t.Fatalf("bad key %v", m.keys)
|
||||
}
|
||||
if m.vals[4] <= 100 {
|
||||
t.Fatalf("bad val: %v", m.vals)
|
||||
}
|
||||
|
||||
if m.keys[5][0] != "runtime" || m.keys[5][1] != "heap_objects" {
|
||||
t.Fatalf("bad key %v", m.keys)
|
||||
}
|
||||
if m.vals[5] <= 100 {
|
||||
t.Fatalf("bad val: %v", m.vals)
|
||||
}
|
||||
|
||||
if m.keys[6][0] != "runtime" || m.keys[6][1] != "total_gc_pause_ns" {
|
||||
t.Fatalf("bad key %v", m.keys)
|
||||
}
|
||||
if m.vals[6] <= 100000 {
|
||||
t.Fatalf("bad val: %v", m.vals)
|
||||
}
|
||||
|
||||
if m.keys[7][0] != "runtime" || m.keys[7][1] != "total_gc_runs" {
|
||||
t.Fatalf("bad key %v", m.keys)
|
||||
}
|
||||
if m.vals[7] < 1 {
|
||||
t.Fatalf("bad val: %v", m.vals)
|
||||
}
|
||||
|
||||
if m.keys[8][0] != "runtime" || m.keys[8][1] != "gc_pause_ns" {
|
||||
t.Fatalf("bad key %v", m.keys)
|
||||
}
|
||||
if m.vals[8] <= 1000 {
|
||||
t.Fatalf("bad val: %v", m.vals)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInsert(t *testing.T) {
|
||||
k := []string{"hi", "bob"}
|
||||
exp := []string{"hi", "there", "bob"}
|
||||
out := insert(1, "there", k)
|
||||
if !reflect.DeepEqual(exp, out) {
|
||||
t.Fatalf("bad insert %v %v", exp, out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMetrics_Filter_Blacklist(t *testing.T) {
|
||||
m := &MockSink{}
|
||||
conf := DefaultConfig("")
|
||||
conf.AllowedPrefixes = []string{"service", "debug.thing"}
|
||||
conf.BlockedPrefixes = []string{"debug"}
|
||||
conf.EnableHostname = false
|
||||
met, err := New(conf, m)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Allowed by default
|
||||
key := []string{"thing"}
|
||||
met.SetGauge(key, 1)
|
||||
if !reflect.DeepEqual(m.keys[0], key) {
|
||||
t.Fatalf("key doesn't exist %v, %v", m.keys[0], key)
|
||||
}
|
||||
if m.vals[0] != 1 {
|
||||
t.Fatalf("bad val: %v", m.vals[0])
|
||||
}
|
||||
|
||||
// Allowed by filter
|
||||
key = []string{"service", "thing"}
|
||||
met.SetGauge(key, 2)
|
||||
if !reflect.DeepEqual(m.keys[1], key) {
|
||||
t.Fatalf("key doesn't exist")
|
||||
}
|
||||
if m.vals[1] != 2 {
|
||||
t.Fatalf("bad val: %v", m.vals[1])
|
||||
}
|
||||
|
||||
// Allowed by filter, subtree of a blocked entry
|
||||
key = []string{"debug", "thing"}
|
||||
met.SetGauge(key, 3)
|
||||
if !reflect.DeepEqual(m.keys[2], key) {
|
||||
t.Fatalf("key doesn't exist")
|
||||
}
|
||||
if m.vals[2] != 3 {
|
||||
t.Fatalf("bad val: %v", m.vals[2])
|
||||
}
|
||||
|
||||
// Blocked by filter
|
||||
key = []string{"debug", "other-thing"}
|
||||
met.SetGauge(key, 4)
|
||||
if len(m.keys) != 3 {
|
||||
t.Fatalf("key shouldn't exist")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMetrics_Filter_Whitelist(t *testing.T) {
|
||||
m := &MockSink{}
|
||||
conf := DefaultConfig("")
|
||||
conf.AllowedPrefixes = []string{"service", "debug.thing"}
|
||||
conf.BlockedPrefixes = []string{"debug"}
|
||||
conf.FilterDefault = false
|
||||
conf.EnableHostname = false
|
||||
met, err := New(conf, m)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Blocked by default
|
||||
key := []string{"thing"}
|
||||
met.SetGauge(key, 1)
|
||||
if len(m.keys) != 0 {
|
||||
t.Fatalf("key should not exist")
|
||||
}
|
||||
|
||||
// Allowed by filter
|
||||
key = []string{"service", "thing"}
|
||||
met.SetGauge(key, 2)
|
||||
if !reflect.DeepEqual(m.keys[0], key) {
|
||||
t.Fatalf("key doesn't exist")
|
||||
}
|
||||
if m.vals[0] != 2 {
|
||||
t.Fatalf("bad val: %v", m.vals[0])
|
||||
}
|
||||
|
||||
// Allowed by filter, subtree of a blocked entry
|
||||
key = []string{"debug", "thing"}
|
||||
met.SetGauge(key, 3)
|
||||
if !reflect.DeepEqual(m.keys[1], key) {
|
||||
t.Fatalf("key doesn't exist")
|
||||
}
|
||||
if m.vals[1] != 3 {
|
||||
t.Fatalf("bad val: %v", m.vals[1])
|
||||
}
|
||||
|
||||
// Blocked by filter
|
||||
key = []string{"debug", "other-thing"}
|
||||
met.SetGauge(key, 4)
|
||||
if len(m.keys) != 2 {
|
||||
t.Fatalf("key shouldn't exist")
|
||||
}
|
||||
}
|
||||
193
vendor/github.com/armon/go-metrics/prometheus/prometheus.go
сгенерированный
поставляемый
@@ -1,193 +0,0 @@
|
||||
// +build go1.3
|
||||
package prometheus
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"regexp"
|
||||
|
||||
"github.com/armon/go-metrics"
|
||||
"github.com/prometheus/client_golang/prometheus"
|
||||
)
|
||||
|
||||
var (
|
||||
// DefaultPrometheusOpts is the default set of options used when creating a
|
||||
// PrometheusSink.
|
||||
DefaultPrometheusOpts = PrometheusOpts{
|
||||
Expiration: 60 * time.Second,
|
||||
}
|
||||
)
|
||||
|
||||
// PrometheusOpts is used to configure the Prometheus Sink
|
||||
type PrometheusOpts struct {
|
||||
// Expiration is the duration a metric is valid for, after which it will be
|
||||
// untracked. If the value is zero, a metric is never expired.
|
||||
Expiration time.Duration
|
||||
}
|
||||
|
||||
type PrometheusSink struct {
|
||||
mu sync.Mutex
|
||||
gauges map[string]prometheus.Gauge
|
||||
summaries map[string]prometheus.Summary
|
||||
counters map[string]prometheus.Counter
|
||||
updates map[string]time.Time
|
||||
expiration time.Duration
|
||||
}
|
||||
|
||||
// NewPrometheusSink creates a new PrometheusSink using the default options.
|
||||
func NewPrometheusSink() (*PrometheusSink, error) {
|
||||
return NewPrometheusSinkFrom(DefaultPrometheusOpts)
|
||||
}
|
||||
|
||||
// NewPrometheusSinkFrom creates a new PrometheusSink using the passed options.
|
||||
func NewPrometheusSinkFrom(opts PrometheusOpts) (*PrometheusSink, error) {
|
||||
sink := &PrometheusSink{
|
||||
gauges: make(map[string]prometheus.Gauge),
|
||||
summaries: make(map[string]prometheus.Summary),
|
||||
counters: make(map[string]prometheus.Counter),
|
||||
updates: make(map[string]time.Time),
|
||||
expiration: opts.Expiration,
|
||||
}
|
||||
|
||||
return sink, prometheus.Register(sink)
|
||||
}
|
||||
|
||||
// Describe is needed to meet the Collector interface.
|
||||
func (p *PrometheusSink) Describe(c chan<- *prometheus.Desc) {
|
||||
// We must emit some description otherwise an error is returned. This
|
||||
// description isn't shown to the user!
|
||||
prometheus.NewGauge(prometheus.GaugeOpts{Name: "Dummy", Help: "Dummy"}).Describe(c)
|
||||
}
|
||||
|
||||
// Collect meets the collection interface and allows us to enforce our expiration
|
||||
// logic to clean up ephemeral metrics if their value haven't been set for a
|
||||
// duration exceeding our allowed expiration time.
|
||||
func (p *PrometheusSink) Collect(c chan<- prometheus.Metric) {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
|
||||
expire := p.expiration != 0
|
||||
now := time.Now()
|
||||
for k, v := range p.gauges {
|
||||
last := p.updates[k]
|
||||
if expire && last.Add(p.expiration).Before(now) {
|
||||
delete(p.updates, k)
|
||||
delete(p.gauges, k)
|
||||
} else {
|
||||
v.Collect(c)
|
||||
}
|
||||
}
|
||||
for k, v := range p.summaries {
|
||||
last := p.updates[k]
|
||||
if expire && last.Add(p.expiration).Before(now) {
|
||||
delete(p.updates, k)
|
||||
delete(p.summaries, k)
|
||||
} else {
|
||||
v.Collect(c)
|
||||
}
|
||||
}
|
||||
for k, v := range p.counters {
|
||||
last := p.updates[k]
|
||||
if expire && last.Add(p.expiration).Before(now) {
|
||||
delete(p.updates, k)
|
||||
delete(p.counters, k)
|
||||
} else {
|
||||
v.Collect(c)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var forbiddenChars = regexp.MustCompile("[ .=\\-]")
|
||||
|
||||
func (p *PrometheusSink) flattenKey(parts []string, labels []metrics.Label) (string, string) {
|
||||
key := strings.Join(parts, "_")
|
||||
key = forbiddenChars.ReplaceAllString(key, "_")
|
||||
|
||||
hash := key
|
||||
for _, label := range labels {
|
||||
hash += fmt.Sprintf(";%s=%s", label.Name, label.Value)
|
||||
}
|
||||
|
||||
return key, hash
|
||||
}
|
||||
|
||||
func prometheusLabels(labels []metrics.Label) prometheus.Labels {
|
||||
l := make(prometheus.Labels)
|
||||
for _, label := range labels {
|
||||
l[label.Name] = label.Value
|
||||
}
|
||||
return l
|
||||
}
|
||||
|
||||
func (p *PrometheusSink) SetGauge(parts []string, val float32) {
|
||||
p.SetGaugeWithLabels(parts, val, nil)
|
||||
}
|
||||
|
||||
func (p *PrometheusSink) SetGaugeWithLabels(parts []string, val float32, labels []metrics.Label) {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
key, hash := p.flattenKey(parts, labels)
|
||||
g, ok := p.gauges[hash]
|
||||
if !ok {
|
||||
g = prometheus.NewGauge(prometheus.GaugeOpts{
|
||||
Name: key,
|
||||
Help: key,
|
||||
ConstLabels: prometheusLabels(labels),
|
||||
})
|
||||
p.gauges[hash] = g
|
||||
}
|
||||
g.Set(float64(val))
|
||||
p.updates[hash] = time.Now()
|
||||
}
|
||||
|
||||
func (p *PrometheusSink) AddSample(parts []string, val float32) {
|
||||
p.AddSampleWithLabels(parts, val, nil)
|
||||
}
|
||||
|
||||
func (p *PrometheusSink) AddSampleWithLabels(parts []string, val float32, labels []metrics.Label) {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
key, hash := p.flattenKey(parts, labels)
|
||||
g, ok := p.summaries[hash]
|
||||
if !ok {
|
||||
g = prometheus.NewSummary(prometheus.SummaryOpts{
|
||||
Name: key,
|
||||
Help: key,
|
||||
MaxAge: 10 * time.Second,
|
||||
ConstLabels: prometheusLabels(labels),
|
||||
})
|
||||
p.summaries[hash] = g
|
||||
}
|
||||
g.Observe(float64(val))
|
||||
p.updates[hash] = time.Now()
|
||||
}
|
||||
|
||||
// EmitKey is not implemented. Prometheus doesn’t offer a type for which an
|
||||
// arbitrary number of values is retained, as Prometheus works with a pull
|
||||
// model, rather than a push model.
|
||||
func (p *PrometheusSink) EmitKey(key []string, val float32) {
|
||||
}
|
||||
|
||||
func (p *PrometheusSink) IncrCounter(parts []string, val float32) {
|
||||
p.IncrCounterWithLabels(parts, val, nil)
|
||||
}
|
||||
|
||||
func (p *PrometheusSink) IncrCounterWithLabels(parts []string, val float32, labels []metrics.Label) {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
key, hash := p.flattenKey(parts, labels)
|
||||
g, ok := p.counters[hash]
|
||||
if !ok {
|
||||
g = prometheus.NewCounter(prometheus.CounterOpts{
|
||||
Name: key,
|
||||
Help: key,
|
||||
ConstLabels: prometheusLabels(labels),
|
||||
})
|
||||
p.counters[hash] = g
|
||||
}
|
||||
g.Add(float64(val))
|
||||
p.updates[hash] = time.Now()
|
||||
}
|
||||
272
vendor/github.com/armon/go-metrics/sink_test.go
сгенерированный
поставляемый
@@ -1,272 +0,0 @@
|
||||
package metrics
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type MockSink struct {
|
||||
keys [][]string
|
||||
vals []float32
|
||||
labels [][]Label
|
||||
}
|
||||
|
||||
func (m *MockSink) SetGauge(key []string, val float32) {
|
||||
m.SetGaugeWithLabels(key, val, nil)
|
||||
}
|
||||
func (m *MockSink) SetGaugeWithLabels(key []string, val float32, labels []Label) {
|
||||
m.keys = append(m.keys, key)
|
||||
m.vals = append(m.vals, val)
|
||||
m.labels = append(m.labels, labels)
|
||||
}
|
||||
func (m *MockSink) EmitKey(key []string, val float32) {
|
||||
m.keys = append(m.keys, key)
|
||||
m.vals = append(m.vals, val)
|
||||
m.labels = append(m.labels, nil)
|
||||
}
|
||||
func (m *MockSink) IncrCounter(key []string, val float32) {
|
||||
m.IncrCounterWithLabels(key, val, nil)
|
||||
}
|
||||
func (m *MockSink) IncrCounterWithLabels(key []string, val float32, labels []Label) {
|
||||
m.keys = append(m.keys, key)
|
||||
m.vals = append(m.vals, val)
|
||||
m.labels = append(m.labels, labels)
|
||||
}
|
||||
func (m *MockSink) AddSample(key []string, val float32) {
|
||||
m.AddSampleWithLabels(key, val, nil)
|
||||
}
|
||||
func (m *MockSink) AddSampleWithLabels(key []string, val float32, labels []Label) {
|
||||
m.keys = append(m.keys, key)
|
||||
m.vals = append(m.vals, val)
|
||||
m.labels = append(m.labels, labels)
|
||||
}
|
||||
|
||||
func TestFanoutSink_Gauge(t *testing.T) {
|
||||
m1 := &MockSink{}
|
||||
m2 := &MockSink{}
|
||||
fh := &FanoutSink{m1, m2}
|
||||
|
||||
k := []string{"test"}
|
||||
v := float32(42.0)
|
||||
fh.SetGauge(k, v)
|
||||
|
||||
if !reflect.DeepEqual(m1.keys[0], k) {
|
||||
t.Fatalf("key not equal")
|
||||
}
|
||||
if !reflect.DeepEqual(m2.keys[0], k) {
|
||||
t.Fatalf("key not equal")
|
||||
}
|
||||
if !reflect.DeepEqual(m1.vals[0], v) {
|
||||
t.Fatalf("val not equal")
|
||||
}
|
||||
if !reflect.DeepEqual(m2.vals[0], v) {
|
||||
t.Fatalf("val not equal")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFanoutSink_Gauge_Labels(t *testing.T) {
|
||||
m1 := &MockSink{}
|
||||
m2 := &MockSink{}
|
||||
fh := &FanoutSink{m1, m2}
|
||||
|
||||
k := []string{"test"}
|
||||
v := float32(42.0)
|
||||
l := []Label{{"a", "b"}}
|
||||
fh.SetGaugeWithLabels(k, v, l)
|
||||
|
||||
if !reflect.DeepEqual(m1.keys[0], k) {
|
||||
t.Fatalf("key not equal")
|
||||
}
|
||||
if !reflect.DeepEqual(m2.keys[0], k) {
|
||||
t.Fatalf("key not equal")
|
||||
}
|
||||
if !reflect.DeepEqual(m1.vals[0], v) {
|
||||
t.Fatalf("val not equal")
|
||||
}
|
||||
if !reflect.DeepEqual(m2.vals[0], v) {
|
||||
t.Fatalf("val not equal")
|
||||
}
|
||||
if !reflect.DeepEqual(m1.labels[0], l) {
|
||||
t.Fatalf("labels not equal")
|
||||
}
|
||||
if !reflect.DeepEqual(m2.labels[0], l) {
|
||||
t.Fatalf("labels not equal")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFanoutSink_Key(t *testing.T) {
|
||||
m1 := &MockSink{}
|
||||
m2 := &MockSink{}
|
||||
fh := &FanoutSink{m1, m2}
|
||||
|
||||
k := []string{"test"}
|
||||
v := float32(42.0)
|
||||
fh.EmitKey(k, v)
|
||||
|
||||
if !reflect.DeepEqual(m1.keys[0], k) {
|
||||
t.Fatalf("key not equal")
|
||||
}
|
||||
if !reflect.DeepEqual(m2.keys[0], k) {
|
||||
t.Fatalf("key not equal")
|
||||
}
|
||||
if !reflect.DeepEqual(m1.vals[0], v) {
|
||||
t.Fatalf("val not equal")
|
||||
}
|
||||
if !reflect.DeepEqual(m2.vals[0], v) {
|
||||
t.Fatalf("val not equal")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFanoutSink_Counter(t *testing.T) {
|
||||
m1 := &MockSink{}
|
||||
m2 := &MockSink{}
|
||||
fh := &FanoutSink{m1, m2}
|
||||
|
||||
k := []string{"test"}
|
||||
v := float32(42.0)
|
||||
fh.IncrCounter(k, v)
|
||||
|
||||
if !reflect.DeepEqual(m1.keys[0], k) {
|
||||
t.Fatalf("key not equal")
|
||||
}
|
||||
if !reflect.DeepEqual(m2.keys[0], k) {
|
||||
t.Fatalf("key not equal")
|
||||
}
|
||||
if !reflect.DeepEqual(m1.vals[0], v) {
|
||||
t.Fatalf("val not equal")
|
||||
}
|
||||
if !reflect.DeepEqual(m2.vals[0], v) {
|
||||
t.Fatalf("val not equal")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFanoutSink_Counter_Labels(t *testing.T) {
|
||||
m1 := &MockSink{}
|
||||
m2 := &MockSink{}
|
||||
fh := &FanoutSink{m1, m2}
|
||||
|
||||
k := []string{"test"}
|
||||
v := float32(42.0)
|
||||
l := []Label{{"a", "b"}}
|
||||
fh.IncrCounterWithLabels(k, v, l)
|
||||
|
||||
if !reflect.DeepEqual(m1.keys[0], k) {
|
||||
t.Fatalf("key not equal")
|
||||
}
|
||||
if !reflect.DeepEqual(m2.keys[0], k) {
|
||||
t.Fatalf("key not equal")
|
||||
}
|
||||
if !reflect.DeepEqual(m1.vals[0], v) {
|
||||
t.Fatalf("val not equal")
|
||||
}
|
||||
if !reflect.DeepEqual(m2.vals[0], v) {
|
||||
t.Fatalf("val not equal")
|
||||
}
|
||||
if !reflect.DeepEqual(m1.labels[0], l) {
|
||||
t.Fatalf("labels not equal")
|
||||
}
|
||||
if !reflect.DeepEqual(m2.labels[0], l) {
|
||||
t.Fatalf("labels not equal")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFanoutSink_Sample(t *testing.T) {
|
||||
m1 := &MockSink{}
|
||||
m2 := &MockSink{}
|
||||
fh := &FanoutSink{m1, m2}
|
||||
|
||||
k := []string{"test"}
|
||||
v := float32(42.0)
|
||||
fh.AddSample(k, v)
|
||||
|
||||
if !reflect.DeepEqual(m1.keys[0], k) {
|
||||
t.Fatalf("key not equal")
|
||||
}
|
||||
if !reflect.DeepEqual(m2.keys[0], k) {
|
||||
t.Fatalf("key not equal")
|
||||
}
|
||||
if !reflect.DeepEqual(m1.vals[0], v) {
|
||||
t.Fatalf("val not equal")
|
||||
}
|
||||
if !reflect.DeepEqual(m2.vals[0], v) {
|
||||
t.Fatalf("val not equal")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFanoutSink_Sample_Labels(t *testing.T) {
|
||||
m1 := &MockSink{}
|
||||
m2 := &MockSink{}
|
||||
fh := &FanoutSink{m1, m2}
|
||||
|
||||
k := []string{"test"}
|
||||
v := float32(42.0)
|
||||
l := []Label{{"a", "b"}}
|
||||
fh.AddSampleWithLabels(k, v, l)
|
||||
|
||||
if !reflect.DeepEqual(m1.keys[0], k) {
|
||||
t.Fatalf("key not equal")
|
||||
}
|
||||
if !reflect.DeepEqual(m2.keys[0], k) {
|
||||
t.Fatalf("key not equal")
|
||||
}
|
||||
if !reflect.DeepEqual(m1.vals[0], v) {
|
||||
t.Fatalf("val not equal")
|
||||
}
|
||||
if !reflect.DeepEqual(m2.vals[0], v) {
|
||||
t.Fatalf("val not equal")
|
||||
}
|
||||
if !reflect.DeepEqual(m1.labels[0], l) {
|
||||
t.Fatalf("labels not equal")
|
||||
}
|
||||
if !reflect.DeepEqual(m2.labels[0], l) {
|
||||
t.Fatalf("labels not equal")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewMetricSinkFromURL(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
desc string
|
||||
input string
|
||||
expect reflect.Type
|
||||
expectErr string
|
||||
}{
|
||||
{
|
||||
desc: "statsd scheme yields a StatsdSink",
|
||||
input: "statsd://someserver:123",
|
||||
expect: reflect.TypeOf(&StatsdSink{}),
|
||||
},
|
||||
{
|
||||
desc: "statsite scheme yields a StatsiteSink",
|
||||
input: "statsite://someserver:123",
|
||||
expect: reflect.TypeOf(&StatsiteSink{}),
|
||||
},
|
||||
{
|
||||
desc: "inmem scheme yields an InmemSink",
|
||||
input: "inmem://?interval=30s&retain=30s",
|
||||
expect: reflect.TypeOf(&InmemSink{}),
|
||||
},
|
||||
{
|
||||
desc: "unknown scheme yields an error",
|
||||
input: "notasink://whatever",
|
||||
expectErr: "unrecognized sink name: \"notasink\"",
|
||||
},
|
||||
} {
|
||||
t.Run(tc.desc, func(t *testing.T) {
|
||||
ms, err := NewMetricSinkFromURL(tc.input)
|
||||
if tc.expectErr != "" {
|
||||
if !strings.Contains(err.Error(), tc.expectErr) {
|
||||
t.Fatalf("expected err: %q to contain: %q", err, tc.expectErr)
|
||||
}
|
||||
} else {
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected err: %s", err)
|
||||
}
|
||||
got := reflect.TypeOf(ms)
|
||||
if got != tc.expect {
|
||||
t.Fatalf("expected return type to be %v, got: %v", tc.expect, got)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
202
vendor/github.com/armon/go-metrics/start_test.go
сгенерированный
поставляемый
@@ -1,202 +0,0 @@
|
||||
package metrics
|
||||
|
||||
import (
|
||||
"io/ioutil"
|
||||
"log"
|
||||
"reflect"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestDefaultConfig(t *testing.T) {
|
||||
conf := DefaultConfig("service")
|
||||
if conf.ServiceName != "service" {
|
||||
t.Fatalf("Bad name")
|
||||
}
|
||||
if conf.HostName == "" {
|
||||
t.Fatalf("missing hostname")
|
||||
}
|
||||
if !conf.EnableHostname || !conf.EnableRuntimeMetrics {
|
||||
t.Fatalf("expect true")
|
||||
}
|
||||
if conf.EnableTypePrefix {
|
||||
t.Fatalf("expect false")
|
||||
}
|
||||
if conf.TimerGranularity != time.Millisecond {
|
||||
t.Fatalf("bad granularity")
|
||||
}
|
||||
if conf.ProfileInterval != time.Second {
|
||||
t.Fatalf("bad interval")
|
||||
}
|
||||
}
|
||||
|
||||
func Test_GlobalMetrics(t *testing.T) {
|
||||
var tests = []struct {
|
||||
desc string
|
||||
key []string
|
||||
val float32
|
||||
fn func([]string, float32)
|
||||
}{
|
||||
{"SetGauge", []string{"test"}, 42, SetGauge},
|
||||
{"EmitKey", []string{"test"}, 42, EmitKey},
|
||||
{"IncrCounter", []string{"test"}, 42, IncrCounter},
|
||||
{"AddSample", []string{"test"}, 42, AddSample},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.desc, func(t *testing.T) {
|
||||
s := &MockSink{}
|
||||
globalMetrics.Store(&Metrics{Config: Config{FilterDefault: true}, sink: s})
|
||||
tt.fn(tt.key, tt.val)
|
||||
if got, want := s.keys[0], tt.key; !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("got key %s want %s", got, want)
|
||||
}
|
||||
if got, want := s.vals[0], tt.val; !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("got val %s want %s", got, want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func Test_GlobalMetrics_Labels(t *testing.T) {
|
||||
labels := []Label{{"a", "b"}}
|
||||
var tests = []struct {
|
||||
desc string
|
||||
key []string
|
||||
val float32
|
||||
fn func([]string, float32, []Label)
|
||||
labels []Label
|
||||
}{
|
||||
{"SetGaugeWithLabels", []string{"test"}, 42, SetGaugeWithLabels, labels},
|
||||
{"IncrCounterWithLabels", []string{"test"}, 42, IncrCounterWithLabels, labels},
|
||||
{"AddSampleWithLabels", []string{"test"}, 42, AddSampleWithLabels, labels},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.desc, func(t *testing.T) {
|
||||
s := &MockSink{}
|
||||
globalMetrics.Store(&Metrics{Config: Config{FilterDefault: true}, sink: s})
|
||||
tt.fn(tt.key, tt.val, tt.labels)
|
||||
if got, want := s.keys[0], tt.key; !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("got key %s want %s", got, want)
|
||||
}
|
||||
if got, want := s.vals[0], tt.val; !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("got val %s want %s", got, want)
|
||||
}
|
||||
if got, want := s.labels[0], tt.labels; !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("got val %s want %s", got, want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func Test_GlobalMetrics_DefaultLabels(t *testing.T) {
|
||||
config := Config{
|
||||
HostName: "host1",
|
||||
ServiceName: "redis",
|
||||
EnableHostnameLabel: true,
|
||||
EnableServiceLabel: true,
|
||||
FilterDefault: true,
|
||||
}
|
||||
labels := []Label{
|
||||
{"host", config.HostName},
|
||||
{"service", config.ServiceName},
|
||||
}
|
||||
var tests = []struct {
|
||||
desc string
|
||||
key []string
|
||||
val float32
|
||||
fn func([]string, float32, []Label)
|
||||
labels []Label
|
||||
}{
|
||||
{"SetGaugeWithLabels", []string{"test"}, 42, SetGaugeWithLabels, labels},
|
||||
{"IncrCounterWithLabels", []string{"test"}, 42, IncrCounterWithLabels, labels},
|
||||
{"AddSampleWithLabels", []string{"test"}, 42, AddSampleWithLabels, labels},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.desc, func(t *testing.T) {
|
||||
s := &MockSink{}
|
||||
globalMetrics.Store(&Metrics{Config: config, sink: s})
|
||||
tt.fn(tt.key, tt.val, nil)
|
||||
if got, want := s.keys[0], tt.key; !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("got key %s want %s", got, want)
|
||||
}
|
||||
if got, want := s.vals[0], tt.val; !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("got val %s want %s", got, want)
|
||||
}
|
||||
if got, want := s.labels[0], tt.labels; !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("got val %s want %s", got, want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func Test_GlobalMetrics_MeasureSince(t *testing.T) {
|
||||
s := &MockSink{}
|
||||
m := &Metrics{sink: s, Config: Config{TimerGranularity: time.Millisecond, FilterDefault: true}}
|
||||
globalMetrics.Store(m)
|
||||
|
||||
k := []string{"test"}
|
||||
now := time.Now()
|
||||
MeasureSince(k, now)
|
||||
|
||||
if !reflect.DeepEqual(s.keys[0], k) {
|
||||
t.Fatalf("key not equal")
|
||||
}
|
||||
if s.vals[0] > 0.1 {
|
||||
t.Fatalf("val too large %v", s.vals[0])
|
||||
}
|
||||
|
||||
labels := []Label{{"a", "b"}}
|
||||
MeasureSinceWithLabels(k, now, labels)
|
||||
if got, want := s.keys[1], k; !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("got key %s want %s", got, want)
|
||||
}
|
||||
if s.vals[1] > 0.1 {
|
||||
t.Fatalf("val too large %v", s.vals[0])
|
||||
}
|
||||
if got, want := s.labels[1], labels; !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("got val %s want %s", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func Test_GlobalMetrics_UpdateFilter(t *testing.T) {
|
||||
globalMetrics.Store(&Metrics{Config: Config{
|
||||
AllowedPrefixes: []string{"a"},
|
||||
BlockedPrefixes: []string{"b"},
|
||||
}})
|
||||
UpdateFilter([]string{"c"}, []string{"d"})
|
||||
|
||||
m := globalMetrics.Load().(*Metrics)
|
||||
if m.AllowedPrefixes[0] != "c" {
|
||||
t.Fatalf("bad: %v", m.AllowedPrefixes)
|
||||
}
|
||||
if m.BlockedPrefixes[0] != "d" {
|
||||
t.Fatalf("bad: %v", m.BlockedPrefixes)
|
||||
}
|
||||
}
|
||||
|
||||
// Benchmark_GlobalMetrics_Direct/direct-8 5000000 278 ns/op
|
||||
// Benchmark_GlobalMetrics_Direct/atomic.Value-8 5000000 235 ns/op
|
||||
func Benchmark_GlobalMetrics_Direct(b *testing.B) {
|
||||
log.SetOutput(ioutil.Discard)
|
||||
s := &MockSink{}
|
||||
m := &Metrics{sink: s}
|
||||
var v atomic.Value
|
||||
v.Store(m)
|
||||
k := []string{"test"}
|
||||
b.Run("direct", func(b *testing.B) {
|
||||
for i := 0; i < b.N; i++ {
|
||||
m.IncrCounter(k, 1)
|
||||
}
|
||||
})
|
||||
b.Run("atomic.Value", func(b *testing.B) {
|
||||
for i := 0; i < b.N; i++ {
|
||||
v.Load().(*Metrics).IncrCounter(k, 1)
|
||||
}
|
||||
})
|
||||
// do something with m so that the compiler does not optimize this away
|
||||
b.Logf("%d", m.lastNumGC)
|
||||
}
|
||||
175
vendor/github.com/armon/go-metrics/statsd_test.go
сгенерированный
поставляемый
@@ -1,175 +0,0 @@
|
||||
package metrics
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"net"
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestStatsd_Flatten(t *testing.T) {
|
||||
s := &StatsdSink{}
|
||||
flat := s.flattenKey([]string{"a", "b", "c", "d"})
|
||||
if flat != "a.b.c.d" {
|
||||
t.Fatalf("Bad flat")
|
||||
}
|
||||
}
|
||||
|
||||
func TestStatsd_PushFullQueue(t *testing.T) {
|
||||
q := make(chan string, 1)
|
||||
q <- "full"
|
||||
|
||||
s := &StatsdSink{metricQueue: q}
|
||||
s.pushMetric("omit")
|
||||
|
||||
out := <-q
|
||||
if out != "full" {
|
||||
t.Fatalf("bad val %v", out)
|
||||
}
|
||||
|
||||
select {
|
||||
case v := <-q:
|
||||
t.Fatalf("bad val %v", v)
|
||||
default:
|
||||
}
|
||||
}
|
||||
|
||||
func TestStatsd_Conn(t *testing.T) {
|
||||
addr := "127.0.0.1:7524"
|
||||
done := make(chan bool)
|
||||
go func() {
|
||||
list, err := net.ListenUDP("udp", &net.UDPAddr{IP: net.ParseIP("127.0.0.1"), Port: 7524})
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
defer list.Close()
|
||||
buf := make([]byte, 1500)
|
||||
n, err := list.Read(buf)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
buf = buf[:n]
|
||||
reader := bufio.NewReader(bytes.NewReader(buf))
|
||||
|
||||
line, err := reader.ReadString('\n')
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected err %s", err)
|
||||
}
|
||||
if line != "gauge.val:1.000000|g\n" {
|
||||
t.Fatalf("bad line %s", line)
|
||||
}
|
||||
|
||||
line, err = reader.ReadString('\n')
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected err %s", err)
|
||||
}
|
||||
if line != "gauge_labels.val.label:2.000000|g\n" {
|
||||
t.Fatalf("bad line %s", line)
|
||||
}
|
||||
|
||||
line, err = reader.ReadString('\n')
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected err %s", err)
|
||||
}
|
||||
if line != "key.other:3.000000|kv\n" {
|
||||
t.Fatalf("bad line %s", line)
|
||||
}
|
||||
|
||||
line, err = reader.ReadString('\n')
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected err %s", err)
|
||||
}
|
||||
if line != "counter.me:4.000000|c\n" {
|
||||
t.Fatalf("bad line %s", line)
|
||||
}
|
||||
|
||||
line, err = reader.ReadString('\n')
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected err %s", err)
|
||||
}
|
||||
if line != "counter_labels.me.label:5.000000|c\n" {
|
||||
t.Fatalf("bad line %s", line)
|
||||
}
|
||||
|
||||
line, err = reader.ReadString('\n')
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected err %s", err)
|
||||
}
|
||||
if line != "sample.slow_thingy:6.000000|ms\n" {
|
||||
t.Fatalf("bad line %s", line)
|
||||
}
|
||||
|
||||
line, err = reader.ReadString('\n')
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected err %s", err)
|
||||
}
|
||||
if line != "sample_labels.slow_thingy.label:7.000000|ms\n" {
|
||||
t.Fatalf("bad line %s", line)
|
||||
}
|
||||
|
||||
done <- true
|
||||
}()
|
||||
s, err := NewStatsdSink(addr)
|
||||
if err != nil {
|
||||
t.Fatalf("bad error")
|
||||
}
|
||||
|
||||
s.SetGauge([]string{"gauge", "val"}, float32(1))
|
||||
s.SetGaugeWithLabels([]string{"gauge_labels", "val"}, float32(2), []Label{{"a", "label"}})
|
||||
s.EmitKey([]string{"key", "other"}, float32(3))
|
||||
s.IncrCounter([]string{"counter", "me"}, float32(4))
|
||||
s.IncrCounterWithLabels([]string{"counter_labels", "me"}, float32(5), []Label{{"a", "label"}})
|
||||
s.AddSample([]string{"sample", "slow thingy"}, float32(6))
|
||||
s.AddSampleWithLabels([]string{"sample_labels", "slow thingy"}, float32(7), []Label{{"a", "label"}})
|
||||
|
||||
select {
|
||||
case <-done:
|
||||
s.Shutdown()
|
||||
case <-time.After(3 * time.Second):
|
||||
t.Fatalf("timeout")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewStatsdSinkFromURL(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
desc string
|
||||
input string
|
||||
expectErr string
|
||||
expectAddr string
|
||||
}{
|
||||
{
|
||||
desc: "address is populated",
|
||||
input: "statsd://statsd.service.consul",
|
||||
expectAddr: "statsd.service.consul",
|
||||
},
|
||||
{
|
||||
desc: "address includes port",
|
||||
input: "statsd://statsd.service.consul:1234",
|
||||
expectAddr: "statsd.service.consul:1234",
|
||||
},
|
||||
} {
|
||||
t.Run(tc.desc, func(t *testing.T) {
|
||||
u, err := url.Parse(tc.input)
|
||||
if err != nil {
|
||||
t.Fatalf("error parsing URL: %s", err)
|
||||
}
|
||||
ms, err := NewStatsdSinkFromURL(u)
|
||||
if tc.expectErr != "" {
|
||||
if !strings.Contains(err.Error(), tc.expectErr) {
|
||||
t.Fatalf("expected err: %q, to contain: %q", err, tc.expectErr)
|
||||
}
|
||||
} else {
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected err: %s", err)
|
||||
}
|
||||
is := ms.(*StatsdSink)
|
||||
if is.addr != tc.expectAddr {
|
||||
t.Fatalf("expected addr %s, got: %s", tc.expectAddr, is.addr)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
171
vendor/github.com/armon/go-metrics/statsite_test.go
сгенерированный
поставляемый
@@ -1,171 +0,0 @@
|
||||
package metrics
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"net"
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func acceptConn(addr string) net.Conn {
|
||||
ln, _ := net.Listen("tcp", addr)
|
||||
conn, _ := ln.Accept()
|
||||
return conn
|
||||
}
|
||||
|
||||
func TestStatsite_Flatten(t *testing.T) {
|
||||
s := &StatsiteSink{}
|
||||
flat := s.flattenKey([]string{"a", "b", "c", "d"})
|
||||
if flat != "a.b.c.d" {
|
||||
t.Fatalf("Bad flat")
|
||||
}
|
||||
}
|
||||
|
||||
func TestStatsite_PushFullQueue(t *testing.T) {
|
||||
q := make(chan string, 1)
|
||||
q <- "full"
|
||||
|
||||
s := &StatsiteSink{metricQueue: q}
|
||||
s.pushMetric("omit")
|
||||
|
||||
out := <-q
|
||||
if out != "full" {
|
||||
t.Fatalf("bad val %v", out)
|
||||
}
|
||||
|
||||
select {
|
||||
case v := <-q:
|
||||
t.Fatalf("bad val %v", v)
|
||||
default:
|
||||
}
|
||||
}
|
||||
|
||||
func TestStatsite_Conn(t *testing.T) {
|
||||
addr := "localhost:7523"
|
||||
done := make(chan bool)
|
||||
go func() {
|
||||
conn := acceptConn(addr)
|
||||
reader := bufio.NewReader(conn)
|
||||
|
||||
line, err := reader.ReadString('\n')
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected err %s", err)
|
||||
}
|
||||
if line != "gauge.val:1.000000|g\n" {
|
||||
t.Fatalf("bad line %s", line)
|
||||
}
|
||||
|
||||
line, err = reader.ReadString('\n')
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected err %s", err)
|
||||
}
|
||||
if line != "gauge_labels.val.label:2.000000|g\n" {
|
||||
t.Fatalf("bad line %s", line)
|
||||
}
|
||||
|
||||
line, err = reader.ReadString('\n')
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected err %s", err)
|
||||
}
|
||||
if line != "key.other:3.000000|kv\n" {
|
||||
t.Fatalf("bad line %s", line)
|
||||
}
|
||||
|
||||
line, err = reader.ReadString('\n')
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected err %s", err)
|
||||
}
|
||||
if line != "counter.me:4.000000|c\n" {
|
||||
t.Fatalf("bad line %s", line)
|
||||
}
|
||||
|
||||
line, err = reader.ReadString('\n')
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected err %s", err)
|
||||
}
|
||||
if line != "counter_labels.me.label:5.000000|c\n" {
|
||||
t.Fatalf("bad line %s", line)
|
||||
}
|
||||
|
||||
line, err = reader.ReadString('\n')
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected err %s", err)
|
||||
}
|
||||
if line != "sample.slow_thingy:6.000000|ms\n" {
|
||||
t.Fatalf("bad line %s", line)
|
||||
}
|
||||
|
||||
line, err = reader.ReadString('\n')
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected err %s", err)
|
||||
}
|
||||
if line != "sample_labels.slow_thingy.label:7.000000|ms\n" {
|
||||
t.Fatalf("bad line %s", line)
|
||||
}
|
||||
|
||||
conn.Close()
|
||||
done <- true
|
||||
}()
|
||||
s, err := NewStatsiteSink(addr)
|
||||
if err != nil {
|
||||
t.Fatalf("bad error")
|
||||
}
|
||||
|
||||
s.SetGauge([]string{"gauge", "val"}, float32(1))
|
||||
s.SetGaugeWithLabels([]string{"gauge_labels", "val"}, float32(2), []Label{{"a", "label"}})
|
||||
s.EmitKey([]string{"key", "other"}, float32(3))
|
||||
s.IncrCounter([]string{"counter", "me"}, float32(4))
|
||||
s.IncrCounterWithLabels([]string{"counter_labels", "me"}, float32(5), []Label{{"a", "label"}})
|
||||
s.AddSample([]string{"sample", "slow thingy"}, float32(6))
|
||||
s.AddSampleWithLabels([]string{"sample_labels", "slow thingy"}, float32(7), []Label{{"a", "label"}})
|
||||
|
||||
select {
|
||||
case <-done:
|
||||
s.Shutdown()
|
||||
case <-time.After(3 * time.Second):
|
||||
t.Fatalf("timeout")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewStatsiteSinkFromURL(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
desc string
|
||||
input string
|
||||
expectErr string
|
||||
expectAddr string
|
||||
}{
|
||||
{
|
||||
desc: "address is populated",
|
||||
input: "statsd://statsd.service.consul",
|
||||
expectAddr: "statsd.service.consul",
|
||||
},
|
||||
{
|
||||
desc: "address includes port",
|
||||
input: "statsd://statsd.service.consul:1234",
|
||||
expectAddr: "statsd.service.consul:1234",
|
||||
},
|
||||
} {
|
||||
t.Run(tc.desc, func(t *testing.T) {
|
||||
u, err := url.Parse(tc.input)
|
||||
if err != nil {
|
||||
t.Fatalf("error parsing URL: %s", err)
|
||||
}
|
||||
ms, err := NewStatsiteSinkFromURL(u)
|
||||
if tc.expectErr != "" {
|
||||
if !strings.Contains(err.Error(), tc.expectErr) {
|
||||
t.Fatalf("expected err: %q, to contain: %q", err, tc.expectErr)
|
||||
}
|
||||
} else {
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected err: %s", err)
|
||||
}
|
||||
is := ms.(*StatsiteSink)
|
||||
if is.addr != tc.expectAddr {
|
||||
t.Fatalf("expected addr %s, got: %s", tc.expectAddr, is.addr)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
1074
vendor/github.com/avct/uasurfer/uasurfer_test.go
сгенерированный
поставляемый
2
vendor/github.com/beorn7/perks/.gitignore
сгенерированный
поставляемый
@@ -1,2 +0,0 @@
|
||||
*.test
|
||||
*.prof
|
||||
31
vendor/github.com/beorn7/perks/README.md
сгенерированный
поставляемый
@@ -1,31 +0,0 @@
|
||||
# Perks for Go (golang.org)
|
||||
|
||||
Perks contains the Go package quantile that computes approximate quantiles over
|
||||
an unbounded data stream within low memory and CPU bounds.
|
||||
|
||||
For more information and examples, see:
|
||||
http://godoc.org/github.com/bmizerany/perks
|
||||
|
||||
A very special thank you and shout out to Graham Cormode (Rutgers University),
|
||||
Flip Korn (AT&T Labs–Research), S. Muthukrishnan (Rutgers University), and
|
||||
Divesh Srivastava (AT&T Labs–Research) for their research and publication of
|
||||
[Effective Computation of Biased Quantiles over Data Streams](http://www.cs.rutgers.edu/~muthu/bquant.pdf)
|
||||
|
||||
Thank you, also:
|
||||
* Armon Dadgar (@armon)
|
||||
* Andrew Gerrand (@nf)
|
||||
* Brad Fitzpatrick (@bradfitz)
|
||||
* Keith Rarick (@kr)
|
||||
|
||||
FAQ:
|
||||
|
||||
Q: Why not move the quantile package into the project root?
|
||||
A: I want to add more packages to perks later.
|
||||
|
||||
Copyright (C) 2013 Blake Mizerany
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
26
vendor/github.com/beorn7/perks/histogram/bench_test.go
сгенерированный
поставляемый
@@ -1,26 +0,0 @@
|
||||
package histogram
|
||||
|
||||
import (
|
||||
"math/rand"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func BenchmarkInsert10Bins(b *testing.B) {
|
||||
b.StopTimer()
|
||||
h := New(10)
|
||||
b.StartTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
f := rand.ExpFloat64()
|
||||
h.Insert(f)
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkInsert100Bins(b *testing.B) {
|
||||
b.StopTimer()
|
||||
h := New(100)
|
||||
b.StartTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
f := rand.ExpFloat64()
|
||||
h.Insert(f)
|
||||
}
|
||||
}
|
||||
108
vendor/github.com/beorn7/perks/histogram/histogram.go
сгенерированный
поставляемый
@@ -1,108 +0,0 @@
|
||||
// Package histogram provides a Go implementation of BigML's histogram package
|
||||
// for Clojure/Java. It is currently experimental.
|
||||
package histogram
|
||||
|
||||
import (
|
||||
"container/heap"
|
||||
"math"
|
||||
"sort"
|
||||
)
|
||||
|
||||
type Bin struct {
|
||||
Count int
|
||||
Sum float64
|
||||
}
|
||||
|
||||
func (b *Bin) Update(x *Bin) {
|
||||
b.Count += x.Count
|
||||
b.Sum += x.Sum
|
||||
}
|
||||
|
||||
func (b *Bin) Mean() float64 {
|
||||
return b.Sum / float64(b.Count)
|
||||
}
|
||||
|
||||
type Bins []*Bin
|
||||
|
||||
func (bs Bins) Len() int { return len(bs) }
|
||||
func (bs Bins) Less(i, j int) bool { return bs[i].Mean() < bs[j].Mean() }
|
||||
func (bs Bins) Swap(i, j int) { bs[i], bs[j] = bs[j], bs[i] }
|
||||
|
||||
func (bs *Bins) Push(x interface{}) {
|
||||
*bs = append(*bs, x.(*Bin))
|
||||
}
|
||||
|
||||
func (bs *Bins) Pop() interface{} {
|
||||
return bs.remove(len(*bs) - 1)
|
||||
}
|
||||
|
||||
func (bs *Bins) remove(n int) *Bin {
|
||||
if n < 0 || len(*bs) < n {
|
||||
return nil
|
||||
}
|
||||
x := (*bs)[n]
|
||||
*bs = append((*bs)[:n], (*bs)[n+1:]...)
|
||||
return x
|
||||
}
|
||||
|
||||
type Histogram struct {
|
||||
res *reservoir
|
||||
}
|
||||
|
||||
func New(maxBins int) *Histogram {
|
||||
return &Histogram{res: newReservoir(maxBins)}
|
||||
}
|
||||
|
||||
func (h *Histogram) Insert(f float64) {
|
||||
h.res.insert(&Bin{1, f})
|
||||
h.res.compress()
|
||||
}
|
||||
|
||||
func (h *Histogram) Bins() Bins {
|
||||
return h.res.bins
|
||||
}
|
||||
|
||||
type reservoir struct {
|
||||
n int
|
||||
maxBins int
|
||||
bins Bins
|
||||
}
|
||||
|
||||
func newReservoir(maxBins int) *reservoir {
|
||||
return &reservoir{maxBins: maxBins}
|
||||
}
|
||||
|
||||
func (r *reservoir) insert(bin *Bin) {
|
||||
r.n += bin.Count
|
||||
i := sort.Search(len(r.bins), func(i int) bool {
|
||||
return r.bins[i].Mean() >= bin.Mean()
|
||||
})
|
||||
if i < 0 || i == r.bins.Len() {
|
||||
// TODO(blake): Maybe use an .insert(i, bin) instead of
|
||||
// performing the extra work of a heap.Push.
|
||||
heap.Push(&r.bins, bin)
|
||||
return
|
||||
}
|
||||
r.bins[i].Update(bin)
|
||||
}
|
||||
|
||||
func (r *reservoir) compress() {
|
||||
for r.bins.Len() > r.maxBins {
|
||||
minGapIndex := -1
|
||||
minGap := math.MaxFloat64
|
||||
for i := 0; i < r.bins.Len()-1; i++ {
|
||||
gap := gapWeight(r.bins[i], r.bins[i+1])
|
||||
if minGap > gap {
|
||||
minGap = gap
|
||||
minGapIndex = i
|
||||
}
|
||||
}
|
||||
prev := r.bins[minGapIndex]
|
||||
next := r.bins.remove(minGapIndex + 1)
|
||||
prev.Update(next)
|
||||
}
|
||||
}
|
||||
|
||||
func gapWeight(prev, next *Bin) float64 {
|
||||
return next.Mean() - prev.Mean()
|
||||
}
|
||||
38
vendor/github.com/beorn7/perks/histogram/histogram_test.go
сгенерированный
поставляемый
@@ -1,38 +0,0 @@
|
||||
package histogram
|
||||
|
||||
import (
|
||||
"math/rand"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestHistogram(t *testing.T) {
|
||||
const numPoints = 1e6
|
||||
const maxBins = 3
|
||||
|
||||
h := New(maxBins)
|
||||
for i := 0; i < numPoints; i++ {
|
||||
f := rand.ExpFloat64()
|
||||
h.Insert(f)
|
||||
}
|
||||
|
||||
bins := h.Bins()
|
||||
if g := len(bins); g > maxBins {
|
||||
t.Fatalf("got %d bins, wanted <= %d", g, maxBins)
|
||||
}
|
||||
|
||||
for _, b := range bins {
|
||||
t.Logf("%+v", b)
|
||||
}
|
||||
|
||||
if g := count(h.Bins()); g != numPoints {
|
||||
t.Fatalf("binned %d points, wanted %d", g, numPoints)
|
||||
}
|
||||
}
|
||||
|
||||
func count(bins Bins) int {
|
||||
binCounts := 0
|
||||
for _, b := range bins {
|
||||
binCounts += b.Count
|
||||
}
|
||||
return binCounts
|
||||
}
|
||||
63
vendor/github.com/beorn7/perks/quantile/bench_test.go
сгенерированный
поставляемый
@@ -1,63 +0,0 @@
|
||||
package quantile
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func BenchmarkInsertTargeted(b *testing.B) {
|
||||
b.ReportAllocs()
|
||||
|
||||
s := NewTargeted(Targets)
|
||||
b.ResetTimer()
|
||||
for i := float64(0); i < float64(b.N); i++ {
|
||||
s.Insert(i)
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkInsertTargetedSmallEpsilon(b *testing.B) {
|
||||
s := NewTargeted(TargetsSmallEpsilon)
|
||||
b.ResetTimer()
|
||||
for i := float64(0); i < float64(b.N); i++ {
|
||||
s.Insert(i)
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkInsertBiased(b *testing.B) {
|
||||
s := NewLowBiased(0.01)
|
||||
b.ResetTimer()
|
||||
for i := float64(0); i < float64(b.N); i++ {
|
||||
s.Insert(i)
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkInsertBiasedSmallEpsilon(b *testing.B) {
|
||||
s := NewLowBiased(0.0001)
|
||||
b.ResetTimer()
|
||||
for i := float64(0); i < float64(b.N); i++ {
|
||||
s.Insert(i)
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkQuery(b *testing.B) {
|
||||
s := NewTargeted(Targets)
|
||||
for i := float64(0); i < 1e6; i++ {
|
||||
s.Insert(i)
|
||||
}
|
||||
b.ResetTimer()
|
||||
n := float64(b.N)
|
||||
for i := float64(0); i < n; i++ {
|
||||
s.Query(i / n)
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkQuerySmallEpsilon(b *testing.B) {
|
||||
s := NewTargeted(TargetsSmallEpsilon)
|
||||
for i := float64(0); i < 1e6; i++ {
|
||||
s.Insert(i)
|
||||
}
|
||||
b.ResetTimer()
|
||||
n := float64(b.N)
|
||||
for i := float64(0); i < n; i++ {
|
||||
s.Query(i / n)
|
||||
}
|
||||
}
|
||||
121
vendor/github.com/beorn7/perks/quantile/example_test.go
сгенерированный
поставляемый
@@ -1,121 +0,0 @@
|
||||
// +build go1.1
|
||||
|
||||
package quantile_test
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/beorn7/perks/quantile"
|
||||
)
|
||||
|
||||
func Example_simple() {
|
||||
ch := make(chan float64)
|
||||
go sendFloats(ch)
|
||||
|
||||
// Compute the 50th, 90th, and 99th percentile.
|
||||
q := quantile.NewTargeted(map[float64]float64{
|
||||
0.50: 0.005,
|
||||
0.90: 0.001,
|
||||
0.99: 0.0001,
|
||||
})
|
||||
for v := range ch {
|
||||
q.Insert(v)
|
||||
}
|
||||
|
||||
fmt.Println("perc50:", q.Query(0.50))
|
||||
fmt.Println("perc90:", q.Query(0.90))
|
||||
fmt.Println("perc99:", q.Query(0.99))
|
||||
fmt.Println("count:", q.Count())
|
||||
// Output:
|
||||
// perc50: 5
|
||||
// perc90: 16
|
||||
// perc99: 223
|
||||
// count: 2388
|
||||
}
|
||||
|
||||
func Example_mergeMultipleStreams() {
|
||||
// Scenario:
|
||||
// We have multiple database shards. On each shard, there is a process
|
||||
// collecting query response times from the database logs and inserting
|
||||
// them into a Stream (created via NewTargeted(0.90)), much like the
|
||||
// Simple example. These processes expose a network interface for us to
|
||||
// ask them to serialize and send us the results of their
|
||||
// Stream.Samples so we may Merge and Query them.
|
||||
//
|
||||
// NOTES:
|
||||
// * These sample sets are small, allowing us to get them
|
||||
// across the network much faster than sending the entire list of data
|
||||
// points.
|
||||
//
|
||||
// * For this to work correctly, we must supply the same quantiles
|
||||
// a priori the process collecting the samples supplied to NewTargeted,
|
||||
// even if we do not plan to query them all here.
|
||||
ch := make(chan quantile.Samples)
|
||||
getDBQuerySamples(ch)
|
||||
q := quantile.NewTargeted(map[float64]float64{0.90: 0.001})
|
||||
for samples := range ch {
|
||||
q.Merge(samples)
|
||||
}
|
||||
fmt.Println("perc90:", q.Query(0.90))
|
||||
}
|
||||
|
||||
func Example_window() {
|
||||
// Scenario: We want the 90th, 95th, and 99th percentiles for each
|
||||
// minute.
|
||||
|
||||
ch := make(chan float64)
|
||||
go sendStreamValues(ch)
|
||||
|
||||
tick := time.NewTicker(1 * time.Minute)
|
||||
q := quantile.NewTargeted(map[float64]float64{
|
||||
0.90: 0.001,
|
||||
0.95: 0.0005,
|
||||
0.99: 0.0001,
|
||||
})
|
||||
for {
|
||||
select {
|
||||
case t := <-tick.C:
|
||||
flushToDB(t, q.Samples())
|
||||
q.Reset()
|
||||
case v := <-ch:
|
||||
q.Insert(v)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func sendStreamValues(ch chan float64) {
|
||||
// Use your imagination
|
||||
}
|
||||
|
||||
func flushToDB(t time.Time, samples quantile.Samples) {
|
||||
// Use your imagination
|
||||
}
|
||||
|
||||
// This is a stub for the above example. In reality this would hit the remote
|
||||
// servers via http or something like it.
|
||||
func getDBQuerySamples(ch chan quantile.Samples) {}
|
||||
|
||||
func sendFloats(ch chan<- float64) {
|
||||
f, err := os.Open("exampledata.txt")
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
sc := bufio.NewScanner(f)
|
||||
for sc.Scan() {
|
||||
b := sc.Bytes()
|
||||
v, err := strconv.ParseFloat(string(b), 64)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
ch <- v
|
||||
}
|
||||
if sc.Err() != nil {
|
||||
log.Fatal(sc.Err())
|
||||
}
|
||||
close(ch)
|
||||
}
|
||||
34
vendor/github.com/beorn7/perks/quantile/stream.go
сгенерированный
поставляемый
@@ -77,15 +77,20 @@ func NewHighBiased(epsilon float64) *Stream {
|
||||
// is guaranteed to be within (Quantile±Epsilon).
|
||||
//
|
||||
// See http://www.cs.rutgers.edu/~muthu/bquant.pdf for time, space, and error properties.
|
||||
func NewTargeted(targets map[float64]float64) *Stream {
|
||||
func NewTargeted(targetMap map[float64]float64) *Stream {
|
||||
// Convert map to slice to avoid slow iterations on a map.
|
||||
// ƒ is called on the hot path, so converting the map to a slice
|
||||
// beforehand results in significant CPU savings.
|
||||
targets := targetMapToSlice(targetMap)
|
||||
|
||||
ƒ := func(s *stream, r float64) float64 {
|
||||
var m = math.MaxFloat64
|
||||
var f float64
|
||||
for quantile, epsilon := range targets {
|
||||
if quantile*s.n <= r {
|
||||
f = (2 * epsilon * r) / quantile
|
||||
for _, t := range targets {
|
||||
if t.quantile*s.n <= r {
|
||||
f = (2 * t.epsilon * r) / t.quantile
|
||||
} else {
|
||||
f = (2 * epsilon * (s.n - r)) / (1 - quantile)
|
||||
f = (2 * t.epsilon * (s.n - r)) / (1 - t.quantile)
|
||||
}
|
||||
if f < m {
|
||||
m = f
|
||||
@@ -96,6 +101,25 @@ func NewTargeted(targets map[float64]float64) *Stream {
|
||||
return newStream(ƒ)
|
||||
}
|
||||
|
||||
type target struct {
|
||||
quantile float64
|
||||
epsilon float64
|
||||
}
|
||||
|
||||
func targetMapToSlice(targetMap map[float64]float64) []target {
|
||||
targets := make([]target, 0, len(targetMap))
|
||||
|
||||
for quantile, epsilon := range targetMap {
|
||||
t := target{
|
||||
quantile: quantile,
|
||||
epsilon: epsilon,
|
||||
}
|
||||
targets = append(targets, t)
|
||||
}
|
||||
|
||||
return targets
|
||||
}
|
||||
|
||||
// Stream computes quantiles for a stream of float64s. It is not thread-safe by
|
||||
// design. Take care when using across multiple goroutines.
|
||||
type Stream struct {
|
||||
|
||||
215
vendor/github.com/beorn7/perks/quantile/stream_test.go
сгенерированный
поставляемый
@@ -1,215 +0,0 @@
|
||||
package quantile
|
||||
|
||||
import (
|
||||
"math"
|
||||
"math/rand"
|
||||
"sort"
|
||||
"testing"
|
||||
)
|
||||
|
||||
var (
|
||||
Targets = map[float64]float64{
|
||||
0.01: 0.001,
|
||||
0.10: 0.01,
|
||||
0.50: 0.05,
|
||||
0.90: 0.01,
|
||||
0.99: 0.001,
|
||||
}
|
||||
TargetsSmallEpsilon = map[float64]float64{
|
||||
0.01: 0.0001,
|
||||
0.10: 0.001,
|
||||
0.50: 0.005,
|
||||
0.90: 0.001,
|
||||
0.99: 0.0001,
|
||||
}
|
||||
LowQuantiles = []float64{0.01, 0.1, 0.5}
|
||||
HighQuantiles = []float64{0.99, 0.9, 0.5}
|
||||
)
|
||||
|
||||
const RelativeEpsilon = 0.01
|
||||
|
||||
func verifyPercsWithAbsoluteEpsilon(t *testing.T, a []float64, s *Stream) {
|
||||
sort.Float64s(a)
|
||||
for quantile, epsilon := range Targets {
|
||||
n := float64(len(a))
|
||||
k := int(quantile * n)
|
||||
if k < 1 {
|
||||
k = 1
|
||||
}
|
||||
lower := int((quantile - epsilon) * n)
|
||||
if lower < 1 {
|
||||
lower = 1
|
||||
}
|
||||
upper := int(math.Ceil((quantile + epsilon) * n))
|
||||
if upper > len(a) {
|
||||
upper = len(a)
|
||||
}
|
||||
w, min, max := a[k-1], a[lower-1], a[upper-1]
|
||||
if g := s.Query(quantile); g < min || g > max {
|
||||
t.Errorf("q=%f: want %v [%f,%f], got %v", quantile, w, min, max, g)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func verifyLowPercsWithRelativeEpsilon(t *testing.T, a []float64, s *Stream) {
|
||||
sort.Float64s(a)
|
||||
for _, qu := range LowQuantiles {
|
||||
n := float64(len(a))
|
||||
k := int(qu * n)
|
||||
|
||||
lowerRank := int((1 - RelativeEpsilon) * qu * n)
|
||||
upperRank := int(math.Ceil((1 + RelativeEpsilon) * qu * n))
|
||||
w, min, max := a[k-1], a[lowerRank-1], a[upperRank-1]
|
||||
if g := s.Query(qu); g < min || g > max {
|
||||
t.Errorf("q=%f: want %v [%f,%f], got %v", qu, w, min, max, g)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func verifyHighPercsWithRelativeEpsilon(t *testing.T, a []float64, s *Stream) {
|
||||
sort.Float64s(a)
|
||||
for _, qu := range HighQuantiles {
|
||||
n := float64(len(a))
|
||||
k := int(qu * n)
|
||||
|
||||
lowerRank := int((1 - (1+RelativeEpsilon)*(1-qu)) * n)
|
||||
upperRank := int(math.Ceil((1 - (1-RelativeEpsilon)*(1-qu)) * n))
|
||||
w, min, max := a[k-1], a[lowerRank-1], a[upperRank-1]
|
||||
if g := s.Query(qu); g < min || g > max {
|
||||
t.Errorf("q=%f: want %v [%f,%f], got %v", qu, w, min, max, g)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func populateStream(s *Stream) []float64 {
|
||||
a := make([]float64, 0, 1e5+100)
|
||||
for i := 0; i < cap(a); i++ {
|
||||
v := rand.NormFloat64()
|
||||
// Add 5% asymmetric outliers.
|
||||
if i%20 == 0 {
|
||||
v = v*v + 1
|
||||
}
|
||||
s.Insert(v)
|
||||
a = append(a, v)
|
||||
}
|
||||
return a
|
||||
}
|
||||
|
||||
func TestTargetedQuery(t *testing.T) {
|
||||
rand.Seed(42)
|
||||
s := NewTargeted(Targets)
|
||||
a := populateStream(s)
|
||||
verifyPercsWithAbsoluteEpsilon(t, a, s)
|
||||
}
|
||||
|
||||
func TestTargetedQuerySmallSampleSize(t *testing.T) {
|
||||
rand.Seed(42)
|
||||
s := NewTargeted(TargetsSmallEpsilon)
|
||||
a := []float64{1, 2, 3, 4, 5}
|
||||
for _, v := range a {
|
||||
s.Insert(v)
|
||||
}
|
||||
verifyPercsWithAbsoluteEpsilon(t, a, s)
|
||||
// If not yet flushed, results should be precise:
|
||||
if !s.flushed() {
|
||||
for φ, want := range map[float64]float64{
|
||||
0.01: 1,
|
||||
0.10: 1,
|
||||
0.50: 3,
|
||||
0.90: 5,
|
||||
0.99: 5,
|
||||
} {
|
||||
if got := s.Query(φ); got != want {
|
||||
t.Errorf("want %f for φ=%f, got %f", want, φ, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestLowBiasedQuery(t *testing.T) {
|
||||
rand.Seed(42)
|
||||
s := NewLowBiased(RelativeEpsilon)
|
||||
a := populateStream(s)
|
||||
verifyLowPercsWithRelativeEpsilon(t, a, s)
|
||||
}
|
||||
|
||||
func TestHighBiasedQuery(t *testing.T) {
|
||||
rand.Seed(42)
|
||||
s := NewHighBiased(RelativeEpsilon)
|
||||
a := populateStream(s)
|
||||
verifyHighPercsWithRelativeEpsilon(t, a, s)
|
||||
}
|
||||
|
||||
// BrokenTestTargetedMerge is broken, see Merge doc comment.
|
||||
func BrokenTestTargetedMerge(t *testing.T) {
|
||||
rand.Seed(42)
|
||||
s1 := NewTargeted(Targets)
|
||||
s2 := NewTargeted(Targets)
|
||||
a := populateStream(s1)
|
||||
a = append(a, populateStream(s2)...)
|
||||
s1.Merge(s2.Samples())
|
||||
verifyPercsWithAbsoluteEpsilon(t, a, s1)
|
||||
}
|
||||
|
||||
// BrokenTestLowBiasedMerge is broken, see Merge doc comment.
|
||||
func BrokenTestLowBiasedMerge(t *testing.T) {
|
||||
rand.Seed(42)
|
||||
s1 := NewLowBiased(RelativeEpsilon)
|
||||
s2 := NewLowBiased(RelativeEpsilon)
|
||||
a := populateStream(s1)
|
||||
a = append(a, populateStream(s2)...)
|
||||
s1.Merge(s2.Samples())
|
||||
verifyLowPercsWithRelativeEpsilon(t, a, s2)
|
||||
}
|
||||
|
||||
// BrokenTestHighBiasedMerge is broken, see Merge doc comment.
|
||||
func BrokenTestHighBiasedMerge(t *testing.T) {
|
||||
rand.Seed(42)
|
||||
s1 := NewHighBiased(RelativeEpsilon)
|
||||
s2 := NewHighBiased(RelativeEpsilon)
|
||||
a := populateStream(s1)
|
||||
a = append(a, populateStream(s2)...)
|
||||
s1.Merge(s2.Samples())
|
||||
verifyHighPercsWithRelativeEpsilon(t, a, s2)
|
||||
}
|
||||
|
||||
func TestUncompressed(t *testing.T) {
|
||||
q := NewTargeted(Targets)
|
||||
for i := 100; i > 0; i-- {
|
||||
q.Insert(float64(i))
|
||||
}
|
||||
if g := q.Count(); g != 100 {
|
||||
t.Errorf("want count 100, got %d", g)
|
||||
}
|
||||
// Before compression, Query should have 100% accuracy.
|
||||
for quantile := range Targets {
|
||||
w := quantile * 100
|
||||
if g := q.Query(quantile); g != w {
|
||||
t.Errorf("want %f, got %f", w, g)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestUncompressedSamples(t *testing.T) {
|
||||
q := NewTargeted(map[float64]float64{0.99: 0.001})
|
||||
for i := 1; i <= 100; i++ {
|
||||
q.Insert(float64(i))
|
||||
}
|
||||
if g := q.Samples().Len(); g != 100 {
|
||||
t.Errorf("want count 100, got %d", g)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUncompressedOne(t *testing.T) {
|
||||
q := NewTargeted(map[float64]float64{0.99: 0.01})
|
||||
q.Insert(3.14)
|
||||
if g := q.Query(0.90); g != 3.14 {
|
||||
t.Error("want PI, got", g)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDefaults(t *testing.T) {
|
||||
if g := NewTargeted(map[float64]float64{0.99: 0.001}).Query(0.99); g != 0 {
|
||||
t.Errorf("want 0, got %f", g)
|
||||
}
|
||||
}
|
||||
90
vendor/github.com/beorn7/perks/topk/topk.go
сгенерированный
поставляемый
@@ -1,90 +0,0 @@
|
||||
package topk
|
||||
|
||||
import (
|
||||
"sort"
|
||||
)
|
||||
|
||||
// http://www.cs.ucsb.edu/research/tech_reports/reports/2005-23.pdf
|
||||
|
||||
type Element struct {
|
||||
Value string
|
||||
Count int
|
||||
}
|
||||
|
||||
type Samples []*Element
|
||||
|
||||
func (sm Samples) Len() int {
|
||||
return len(sm)
|
||||
}
|
||||
|
||||
func (sm Samples) Less(i, j int) bool {
|
||||
return sm[i].Count < sm[j].Count
|
||||
}
|
||||
|
||||
func (sm Samples) Swap(i, j int) {
|
||||
sm[i], sm[j] = sm[j], sm[i]
|
||||
}
|
||||
|
||||
type Stream struct {
|
||||
k int
|
||||
mon map[string]*Element
|
||||
|
||||
// the minimum Element
|
||||
min *Element
|
||||
}
|
||||
|
||||
func New(k int) *Stream {
|
||||
s := new(Stream)
|
||||
s.k = k
|
||||
s.mon = make(map[string]*Element)
|
||||
s.min = &Element{}
|
||||
|
||||
// Track k+1 so that less frequenet items contended for that spot,
|
||||
// resulting in k being more accurate.
|
||||
return s
|
||||
}
|
||||
|
||||
func (s *Stream) Insert(x string) {
|
||||
s.insert(&Element{x, 1})
|
||||
}
|
||||
|
||||
func (s *Stream) Merge(sm Samples) {
|
||||
for _, e := range sm {
|
||||
s.insert(e)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Stream) insert(in *Element) {
|
||||
e := s.mon[in.Value]
|
||||
if e != nil {
|
||||
e.Count++
|
||||
} else {
|
||||
if len(s.mon) < s.k+1 {
|
||||
e = &Element{in.Value, in.Count}
|
||||
s.mon[in.Value] = e
|
||||
} else {
|
||||
e = s.min
|
||||
delete(s.mon, e.Value)
|
||||
e.Value = in.Value
|
||||
e.Count += in.Count
|
||||
s.min = e
|
||||
}
|
||||
}
|
||||
if e.Count < s.min.Count {
|
||||
s.min = e
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Stream) Query() Samples {
|
||||
var sm Samples
|
||||
for _, e := range s.mon {
|
||||
sm = append(sm, e)
|
||||
}
|
||||
sort.Sort(sort.Reverse(sm))
|
||||
|
||||
if len(sm) < s.k {
|
||||
return sm
|
||||
}
|
||||
|
||||
return sm[:s.k]
|
||||
}
|
||||
57
vendor/github.com/beorn7/perks/topk/topk_test.go
сгенерированный
поставляемый
@@ -1,57 +0,0 @@
|
||||
package topk
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"sort"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestTopK(t *testing.T) {
|
||||
stream := New(10)
|
||||
ss := []*Stream{New(10), New(10), New(10)}
|
||||
m := make(map[string]int)
|
||||
for _, s := range ss {
|
||||
for i := 0; i < 1e6; i++ {
|
||||
v := fmt.Sprintf("%x", int8(rand.ExpFloat64()))
|
||||
s.Insert(v)
|
||||
m[v]++
|
||||
}
|
||||
stream.Merge(s.Query())
|
||||
}
|
||||
|
||||
var sm Samples
|
||||
for x, s := range m {
|
||||
sm = append(sm, &Element{x, s})
|
||||
}
|
||||
sort.Sort(sort.Reverse(sm))
|
||||
|
||||
g := stream.Query()
|
||||
if len(g) != 10 {
|
||||
t.Fatalf("got %d, want 10", len(g))
|
||||
}
|
||||
for i, e := range g {
|
||||
if sm[i].Value != e.Value {
|
||||
t.Errorf("at %d: want %q, got %q", i, sm[i].Value, e.Value)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestQuery(t *testing.T) {
|
||||
queryTests := []struct {
|
||||
value string
|
||||
expected int
|
||||
}{
|
||||
{"a", 1},
|
||||
{"b", 2},
|
||||
{"c", 2},
|
||||
}
|
||||
|
||||
stream := New(2)
|
||||
for _, tt := range queryTests {
|
||||
stream.Insert(tt.value)
|
||||
if n := len(stream.Query()); n != tt.expected {
|
||||
t.Errorf("want %d, got %d", tt.expected, n)
|
||||
}
|
||||
}
|
||||
}
|
||||
22
vendor/github.com/corpix/uarand/scripts/extract-user-agents
сгенерированный
поставляемый
@@ -1,22 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
import sys
|
||||
import xml.etree.ElementTree as XML
|
||||
from argparse import ArgumentParser
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
p = ArgumentParser(
|
||||
description=(
|
||||
"Expects XML from "
|
||||
"http://techpatterns.com/downloads/firefox/useragentswitcher.xml "
|
||||
"to be passed into STDIN and outputs user agents from this XML."
|
||||
)
|
||||
)
|
||||
p.parse_args()
|
||||
|
||||
sys.stderr.write("Reading stdin...\n")
|
||||
doc = XML.iterparse(sys.stdin)
|
||||
for _, node in doc:
|
||||
ua = node.get("useragent")
|
||||
if ua != "" and ua is not None:
|
||||
print(ua)
|
||||
50
vendor/github.com/corpix/uarand/scripts/generate-useragents-go
сгенерированный
поставляемый
@@ -1,50 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
import sys
|
||||
from os.path import exists, expanduser
|
||||
from argparse import ArgumentParser
|
||||
|
||||
|
||||
header = """package {package}
|
||||
|
||||
var (
|
||||
\t// UserAgents is a list of browser and bots user agents.
|
||||
\tUserAgents = []string{{
|
||||
"""
|
||||
|
||||
item = """\t\t"{content}",\n"""
|
||||
|
||||
footer = """\t}}
|
||||
)\n
|
||||
"""
|
||||
|
||||
if __name__ == "__main__":
|
||||
p = ArgumentParser(
|
||||
description=(
|
||||
"Expects a list of user agents delimited by new line character "
|
||||
"to be passed into STDIN and generates go code with this data."
|
||||
)
|
||||
)
|
||||
p.add_argument(
|
||||
"package",
|
||||
help="Go package name to use",
|
||||
default="uarand"
|
||||
)
|
||||
args = p.parse_args().__dict__
|
||||
|
||||
params = args.copy()
|
||||
sys.stderr.write("Reading stdin...\n")
|
||||
sys.stdout.write(
|
||||
header.format(**params)
|
||||
)
|
||||
|
||||
for line in sys.stdin:
|
||||
sys.stdout.write(
|
||||
item.format(
|
||||
content=line.strip(),
|
||||
**params
|
||||
)
|
||||
)
|
||||
|
||||
sys.stdout.write(
|
||||
footer.format(**params)
|
||||
)
|
||||
13
vendor/github.com/corpix/uarand/uarand_test.go
сгенерированный
поставляемый
@@ -1,13 +0,0 @@
|
||||
package uarand
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestGetRandom(t *testing.T) {
|
||||
for k := 0; k < len(UserAgents)*10; k++ {
|
||||
assert.NotEqual(t, "", GetRandom())
|
||||
}
|
||||
}
|
||||
11
vendor/github.com/corpix/uarand/useragents_test.go
сгенерированный
поставляемый
@@ -1,11 +0,0 @@
|
||||
package uarand
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestUserAgents(t *testing.T) {
|
||||
assert.Equal(t, true, len(UserAgents) > 0)
|
||||
}
|
||||
22
vendor/github.com/davecgh/go-spew/.gitignore
сгенерированный
поставляемый
@@ -1,22 +0,0 @@
|
||||
# Compiled Object files, Static and Dynamic libs (Shared Objects)
|
||||
*.o
|
||||
*.a
|
||||
*.so
|
||||
|
||||
# Folders
|
||||
_obj
|
||||
_test
|
||||
|
||||
# Architecture specific extensions/prefixes
|
||||
*.[568vq]
|
||||
[568vq].out
|
||||
|
||||
*.cgo1.go
|
||||
*.cgo2.c
|
||||
_cgo_defun.c
|
||||
_cgo_gotypes.go
|
||||
_cgo_export.*
|
||||
|
||||
_testmain.go
|
||||
|
||||
*.exe
|
||||
27
vendor/github.com/davecgh/go-spew/.travis.yml
сгенерированный
поставляемый
@@ -1,27 +0,0 @@
|
||||
language: go
|
||||
go_import_path: github.com/davecgh/go-spew
|
||||
go:
|
||||
- 1.6.x
|
||||
- 1.7.x
|
||||
- 1.8.x
|
||||
- 1.9.x
|
||||
- tip
|
||||
sudo: false
|
||||
install:
|
||||
- go get -v github.com/alecthomas/gometalinter
|
||||
- gometalinter --install
|
||||
script:
|
||||
- export PATH=$PATH:$HOME/gopath/bin
|
||||
- export GORACE="halt_on_error=1"
|
||||
- test -z "$(gometalinter --disable-all
|
||||
--enable=gofmt
|
||||
--enable=golint
|
||||
--enable=vet
|
||||
--enable=gosimple
|
||||
--enable=unconvert
|
||||
--deadline=4m ./spew | tee /dev/stderr)"
|
||||
- go test -v -race -tags safe ./spew
|
||||
- go test -v -race -tags testcgo ./spew -covermode=atomic -coverprofile=profile.cov
|
||||
after_success:
|
||||
- go get -v github.com/mattn/goveralls
|
||||
- goveralls -coverprofile=profile.cov -service=travis-ci
|
||||
2
vendor/github.com/davecgh/go-spew/LICENSE
сгенерированный
поставляемый
@@ -2,7 +2,7 @@ ISC License
|
||||
|
||||
Copyright (c) 2012-2016 Dave Collins <dave@davec.name>
|
||||
|
||||
Permission to use, copy, modify, and/or distribute this software for any
|
||||
Permission to use, copy, modify, and distribute this software for any
|
||||
purpose with or without fee is hereby granted, provided that the above
|
||||
copyright notice and this permission notice appear in all copies.
|
||||
|
||||
|
||||
201
vendor/github.com/davecgh/go-spew/README.md
сгенерированный
поставляемый
@@ -1,201 +0,0 @@
|
||||
go-spew
|
||||
=======
|
||||
|
||||
[](https://travis-ci.org/davecgh/go-spew)
|
||||
[](http://copyfree.org)
|
||||
[](https://coveralls.io/r/davecgh/go-spew?branch=master)
|
||||
|
||||
Go-spew implements a deep pretty printer for Go data structures to aid in
|
||||
debugging. A comprehensive suite of tests with 100% test coverage is provided
|
||||
to ensure proper functionality. See `test_coverage.txt` for the gocov coverage
|
||||
report. Go-spew is licensed under the liberal ISC license, so it may be used in
|
||||
open source or commercial projects.
|
||||
|
||||
If you're interested in reading about how this package came to life and some
|
||||
of the challenges involved in providing a deep pretty printer, there is a blog
|
||||
post about it
|
||||
[here](https://web.archive.org/web/20160304013555/https://blog.cyphertite.com/go-spew-a-journey-into-dumping-go-data-structures/).
|
||||
|
||||
## Documentation
|
||||
|
||||
[](http://godoc.org/github.com/davecgh/go-spew/spew)
|
||||
|
||||
Full `go doc` style documentation for the project can be viewed online without
|
||||
installing this package by using the excellent GoDoc site here:
|
||||
http://godoc.org/github.com/davecgh/go-spew/spew
|
||||
|
||||
You can also view the documentation locally once the package is installed with
|
||||
the `godoc` tool by running `godoc -http=":6060"` and pointing your browser to
|
||||
http://localhost:6060/pkg/github.com/davecgh/go-spew/spew
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
$ go get -u github.com/davecgh/go-spew/spew
|
||||
```
|
||||
|
||||
## Quick Start
|
||||
|
||||
Add this import line to the file you're working in:
|
||||
|
||||
```Go
|
||||
import "github.com/davecgh/go-spew/spew"
|
||||
```
|
||||
|
||||
To dump a variable with full newlines, indentation, type, and pointer
|
||||
information use Dump, Fdump, or Sdump:
|
||||
|
||||
```Go
|
||||
spew.Dump(myVar1, myVar2, ...)
|
||||
spew.Fdump(someWriter, myVar1, myVar2, ...)
|
||||
str := spew.Sdump(myVar1, myVar2, ...)
|
||||
```
|
||||
|
||||
Alternatively, if you would prefer to use format strings with a compacted inline
|
||||
printing style, use the convenience wrappers Printf, Fprintf, etc with %v (most
|
||||
compact), %+v (adds pointer addresses), %#v (adds types), or %#+v (adds types
|
||||
and pointer addresses):
|
||||
|
||||
```Go
|
||||
spew.Printf("myVar1: %v -- myVar2: %+v", myVar1, myVar2)
|
||||
spew.Printf("myVar3: %#v -- myVar4: %#+v", myVar3, myVar4)
|
||||
spew.Fprintf(someWriter, "myVar1: %v -- myVar2: %+v", myVar1, myVar2)
|
||||
spew.Fprintf(someWriter, "myVar3: %#v -- myVar4: %#+v", myVar3, myVar4)
|
||||
```
|
||||
|
||||
## Debugging a Web Application Example
|
||||
|
||||
Here is an example of how you can use `spew.Sdump()` to help debug a web application. Please be sure to wrap your output using the `html.EscapeString()` function for safety reasons. You should also only use this debugging technique in a development environment, never in production.
|
||||
|
||||
```Go
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"html"
|
||||
"net/http"
|
||||
|
||||
"github.com/davecgh/go-spew/spew"
|
||||
)
|
||||
|
||||
func handler(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/html")
|
||||
fmt.Fprintf(w, "Hi there, %s!", r.URL.Path[1:])
|
||||
fmt.Fprintf(w, "<!--\n" + html.EscapeString(spew.Sdump(w)) + "\n-->")
|
||||
}
|
||||
|
||||
func main() {
|
||||
http.HandleFunc("/", handler)
|
||||
http.ListenAndServe(":8080", nil)
|
||||
}
|
||||
```
|
||||
|
||||
## Sample Dump Output
|
||||
|
||||
```
|
||||
(main.Foo) {
|
||||
unexportedField: (*main.Bar)(0xf84002e210)({
|
||||
flag: (main.Flag) flagTwo,
|
||||
data: (uintptr) <nil>
|
||||
}),
|
||||
ExportedField: (map[interface {}]interface {}) {
|
||||
(string) "one": (bool) true
|
||||
}
|
||||
}
|
||||
([]uint8) {
|
||||
00000000 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 20 |............... |
|
||||
00000010 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f 30 |!"#$%&'()*+,-./0|
|
||||
00000020 31 32 |12|
|
||||
}
|
||||
```
|
||||
|
||||
## Sample Formatter Output
|
||||
|
||||
Double pointer to a uint8:
|
||||
```
|
||||
%v: <**>5
|
||||
%+v: <**>(0xf8400420d0->0xf8400420c8)5
|
||||
%#v: (**uint8)5
|
||||
%#+v: (**uint8)(0xf8400420d0->0xf8400420c8)5
|
||||
```
|
||||
|
||||
Pointer to circular struct with a uint8 field and a pointer to itself:
|
||||
```
|
||||
%v: <*>{1 <*><shown>}
|
||||
%+v: <*>(0xf84003e260){ui8:1 c:<*>(0xf84003e260)<shown>}
|
||||
%#v: (*main.circular){ui8:(uint8)1 c:(*main.circular)<shown>}
|
||||
%#+v: (*main.circular)(0xf84003e260){ui8:(uint8)1 c:(*main.circular)(0xf84003e260)<shown>}
|
||||
```
|
||||
|
||||
## Configuration Options
|
||||
|
||||
Configuration of spew is handled by fields in the ConfigState type. For
|
||||
convenience, all of the top-level functions use a global state available via the
|
||||
spew.Config global.
|
||||
|
||||
It is also possible to create a ConfigState instance that provides methods
|
||||
equivalent to the top-level functions. This allows concurrent configuration
|
||||
options. See the ConfigState documentation for more details.
|
||||
|
||||
```
|
||||
* Indent
|
||||
String to use for each indentation level for Dump functions.
|
||||
It is a single space by default. A popular alternative is "\t".
|
||||
|
||||
* MaxDepth
|
||||
Maximum number of levels to descend into nested data structures.
|
||||
There is no limit by default.
|
||||
|
||||
* DisableMethods
|
||||
Disables invocation of error and Stringer interface methods.
|
||||
Method invocation is enabled by default.
|
||||
|
||||
* DisablePointerMethods
|
||||
Disables invocation of error and Stringer interface methods on types
|
||||
which only accept pointer receivers from non-pointer variables. This option
|
||||
relies on access to the unsafe package, so it will not have any effect when
|
||||
running in environments without access to the unsafe package such as Google
|
||||
App Engine or with the "safe" build tag specified.
|
||||
Pointer method invocation is enabled by default.
|
||||
|
||||
* DisablePointerAddresses
|
||||
DisablePointerAddresses specifies whether to disable the printing of
|
||||
pointer addresses. This is useful when diffing data structures in tests.
|
||||
|
||||
* DisableCapacities
|
||||
DisableCapacities specifies whether to disable the printing of capacities
|
||||
for arrays, slices, maps and channels. This is useful when diffing data
|
||||
structures in tests.
|
||||
|
||||
* ContinueOnMethod
|
||||
Enables recursion into types after invoking error and Stringer interface
|
||||
methods. Recursion after method invocation is disabled by default.
|
||||
|
||||
* SortKeys
|
||||
Specifies map keys should be sorted before being printed. Use
|
||||
this to have a more deterministic, diffable output. Note that
|
||||
only native types (bool, int, uint, floats, uintptr and string)
|
||||
and types which implement error or Stringer interfaces are supported,
|
||||
with other types sorted according to the reflect.Value.String() output
|
||||
which guarantees display stability. Natural map order is used by
|
||||
default.
|
||||
|
||||
* SpewKeys
|
||||
SpewKeys specifies that, as a last resort attempt, map keys should be
|
||||
spewed to strings and sorted by those strings. This is only considered
|
||||
if SortKeys is true.
|
||||
|
||||
```
|
||||
|
||||
## Unsafe Package Dependency
|
||||
|
||||
This package relies on the unsafe package to perform some of the more advanced
|
||||
features, however it also supports a "limited" mode which allows it to work in
|
||||
environments where the unsafe package is not available. By default, it will
|
||||
operate in this mode on Google App Engine and when compiled with GopherJS. The
|
||||
"safe" build tag may also be specified to force the package to build without
|
||||
using the unsafe package.
|
||||
|
||||
## License
|
||||
|
||||
Go-spew is licensed under the [copyfree](http://copyfree.org) ISC License.
|
||||
22
vendor/github.com/davecgh/go-spew/cov_report.sh
сгенерированный
поставляемый
@@ -1,22 +0,0 @@
|
||||
#!/bin/sh
|
||||
|
||||
# This script uses gocov to generate a test coverage report.
|
||||
# The gocov tool my be obtained with the following command:
|
||||
# go get github.com/axw/gocov/gocov
|
||||
#
|
||||
# It will be installed to $GOPATH/bin, so ensure that location is in your $PATH.
|
||||
|
||||
# Check for gocov.
|
||||
if ! type gocov >/dev/null 2>&1; then
|
||||
echo >&2 "This script requires the gocov tool."
|
||||
echo >&2 "You may obtain it with the following command:"
|
||||
echo >&2 "go get github.com/axw/gocov/gocov"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Only run the cgo tests if gcc is installed.
|
||||
if type gcc >/dev/null 2>&1; then
|
||||
(cd spew && gocov test -tags testcgo | gocov report)
|
||||
else
|
||||
(cd spew && gocov test | gocov report)
|
||||
fi
|
||||
187
vendor/github.com/davecgh/go-spew/spew/bypass.go
сгенерированный
поставляемый
@@ -16,9 +16,7 @@
|
||||
// when the code is not running on Google App Engine, compiled by GopherJS, and
|
||||
// "-tags safe" is not added to the go build command line. The "disableunsafe"
|
||||
// tag is deprecated and thus should not be used.
|
||||
// Go versions prior to 1.4 are disabled because they use a different layout
|
||||
// for interfaces which make the implementation of unsafeReflectValue more complex.
|
||||
// +build !js,!appengine,!safe,!disableunsafe,go1.4
|
||||
// +build !js,!appengine,!safe,!disableunsafe
|
||||
|
||||
package spew
|
||||
|
||||
@@ -36,49 +34,80 @@ const (
|
||||
ptrSize = unsafe.Sizeof((*byte)(nil))
|
||||
)
|
||||
|
||||
type flag uintptr
|
||||
|
||||
var (
|
||||
// flagRO indicates whether the value field of a reflect.Value
|
||||
// is read-only.
|
||||
flagRO flag
|
||||
// offsetPtr, offsetScalar, and offsetFlag are the offsets for the
|
||||
// internal reflect.Value fields. These values are valid before golang
|
||||
// commit ecccf07e7f9d which changed the format. The are also valid
|
||||
// after commit 82f48826c6c7 which changed the format again to mirror
|
||||
// the original format. Code in the init function updates these offsets
|
||||
// as necessary.
|
||||
offsetPtr = uintptr(ptrSize)
|
||||
offsetScalar = uintptr(0)
|
||||
offsetFlag = uintptr(ptrSize * 2)
|
||||
|
||||
// flagAddr indicates whether the address of the reflect.Value's
|
||||
// value may be taken.
|
||||
flagAddr flag
|
||||
// flagKindWidth and flagKindShift indicate various bits that the
|
||||
// reflect package uses internally to track kind information.
|
||||
//
|
||||
// flagRO indicates whether or not the value field of a reflect.Value is
|
||||
// read-only.
|
||||
//
|
||||
// flagIndir indicates whether the value field of a reflect.Value is
|
||||
// the actual data or a pointer to the data.
|
||||
//
|
||||
// These values are valid before golang commit 90a7c3c86944 which
|
||||
// changed their positions. Code in the init function updates these
|
||||
// flags as necessary.
|
||||
flagKindWidth = uintptr(5)
|
||||
flagKindShift = uintptr(flagKindWidth - 1)
|
||||
flagRO = uintptr(1 << 0)
|
||||
flagIndir = uintptr(1 << 1)
|
||||
)
|
||||
|
||||
// flagKindMask holds the bits that make up the kind
|
||||
// part of the flags field. In all the supported versions,
|
||||
// it is in the lower 5 bits.
|
||||
const flagKindMask = flag(0x1f)
|
||||
|
||||
// Different versions of Go have used different
|
||||
// bit layouts for the flags type. This table
|
||||
// records the known combinations.
|
||||
var okFlags = []struct {
|
||||
ro, addr flag
|
||||
}{{
|
||||
// From Go 1.4 to 1.5
|
||||
ro: 1 << 5,
|
||||
addr: 1 << 7,
|
||||
}, {
|
||||
// Up to Go tip.
|
||||
ro: 1<<5 | 1<<6,
|
||||
addr: 1 << 8,
|
||||
}}
|
||||
|
||||
var flagValOffset = func() uintptr {
|
||||
field, ok := reflect.TypeOf(reflect.Value{}).FieldByName("flag")
|
||||
if !ok {
|
||||
panic("reflect.Value has no flag field")
|
||||
func init() {
|
||||
// Older versions of reflect.Value stored small integers directly in the
|
||||
// ptr field (which is named val in the older versions). Versions
|
||||
// between commits ecccf07e7f9d and 82f48826c6c7 added a new field named
|
||||
// scalar for this purpose which unfortunately came before the flag
|
||||
// field, so the offset of the flag field is different for those
|
||||
// versions.
|
||||
//
|
||||
// This code constructs a new reflect.Value from a known small integer
|
||||
// and checks if the size of the reflect.Value struct indicates it has
|
||||
// the scalar field. When it does, the offsets are updated accordingly.
|
||||
vv := reflect.ValueOf(0xf00)
|
||||
if unsafe.Sizeof(vv) == (ptrSize * 4) {
|
||||
offsetScalar = ptrSize * 2
|
||||
offsetFlag = ptrSize * 3
|
||||
}
|
||||
return field.Offset
|
||||
}()
|
||||
|
||||
// flagField returns a pointer to the flag field of a reflect.Value.
|
||||
func flagField(v *reflect.Value) *flag {
|
||||
return (*flag)(unsafe.Pointer(uintptr(unsafe.Pointer(v)) + flagValOffset))
|
||||
// Commit 90a7c3c86944 changed the flag positions such that the low
|
||||
// order bits are the kind. This code extracts the kind from the flags
|
||||
// field and ensures it's the correct type. When it's not, the flag
|
||||
// order has been changed to the newer format, so the flags are updated
|
||||
// accordingly.
|
||||
upf := unsafe.Pointer(uintptr(unsafe.Pointer(&vv)) + offsetFlag)
|
||||
upfv := *(*uintptr)(upf)
|
||||
flagKindMask := uintptr((1<<flagKindWidth - 1) << flagKindShift)
|
||||
if (upfv&flagKindMask)>>flagKindShift != uintptr(reflect.Int) {
|
||||
flagKindShift = 0
|
||||
flagRO = 1 << 5
|
||||
flagIndir = 1 << 6
|
||||
|
||||
// Commit adf9b30e5594 modified the flags to separate the
|
||||
// flagRO flag into two bits which specifies whether or not the
|
||||
// field is embedded. This causes flagIndir to move over a bit
|
||||
// and means that flagRO is the combination of either of the
|
||||
// original flagRO bit and the new bit.
|
||||
//
|
||||
// This code detects the change by extracting what used to be
|
||||
// the indirect bit to ensure it's set. When it's not, the flag
|
||||
// order has been changed to the newer format, so the flags are
|
||||
// updated accordingly.
|
||||
if upfv&flagIndir == 0 {
|
||||
flagRO = 3 << 5
|
||||
flagIndir = 1 << 7
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// unsafeReflectValue converts the passed reflect.Value into a one that bypasses
|
||||
@@ -90,56 +119,34 @@ func flagField(v *reflect.Value) *flag {
|
||||
// This allows us to check for implementations of the Stringer and error
|
||||
// interfaces to be used for pretty printing ordinarily unaddressable and
|
||||
// inaccessible values such as unexported struct fields.
|
||||
func unsafeReflectValue(v reflect.Value) reflect.Value {
|
||||
if !v.IsValid() || (v.CanInterface() && v.CanAddr()) {
|
||||
return v
|
||||
}
|
||||
flagFieldPtr := flagField(&v)
|
||||
*flagFieldPtr &^= flagRO
|
||||
*flagFieldPtr |= flagAddr
|
||||
return v
|
||||
}
|
||||
|
||||
// Sanity checks against future reflect package changes
|
||||
// to the type or semantics of the Value.flag field.
|
||||
func init() {
|
||||
field, ok := reflect.TypeOf(reflect.Value{}).FieldByName("flag")
|
||||
if !ok {
|
||||
panic("reflect.Value has no flag field")
|
||||
}
|
||||
if field.Type.Kind() != reflect.TypeOf(flag(0)).Kind() {
|
||||
panic("reflect.Value flag field has changed kind")
|
||||
}
|
||||
type t0 int
|
||||
var t struct {
|
||||
A t0
|
||||
// t0 will have flagEmbedRO set.
|
||||
t0
|
||||
// a will have flagStickyRO set
|
||||
a t0
|
||||
}
|
||||
vA := reflect.ValueOf(t).FieldByName("A")
|
||||
va := reflect.ValueOf(t).FieldByName("a")
|
||||
vt0 := reflect.ValueOf(t).FieldByName("t0")
|
||||
|
||||
// Infer flagRO from the difference between the flags
|
||||
// for the (otherwise identical) fields in t.
|
||||
flagPublic := *flagField(&vA)
|
||||
flagWithRO := *flagField(&va) | *flagField(&vt0)
|
||||
flagRO = flagPublic ^ flagWithRO
|
||||
|
||||
// Infer flagAddr from the difference between a value
|
||||
// taken from a pointer and not.
|
||||
vPtrA := reflect.ValueOf(&t).Elem().FieldByName("A")
|
||||
flagNoPtr := *flagField(&vA)
|
||||
flagPtr := *flagField(&vPtrA)
|
||||
flagAddr = flagNoPtr ^ flagPtr
|
||||
|
||||
// Check that the inferred flags tally with one of the known versions.
|
||||
for _, f := range okFlags {
|
||||
if flagRO == f.ro && flagAddr == f.addr {
|
||||
return
|
||||
func unsafeReflectValue(v reflect.Value) (rv reflect.Value) {
|
||||
indirects := 1
|
||||
vt := v.Type()
|
||||
upv := unsafe.Pointer(uintptr(unsafe.Pointer(&v)) + offsetPtr)
|
||||
rvf := *(*uintptr)(unsafe.Pointer(uintptr(unsafe.Pointer(&v)) + offsetFlag))
|
||||
if rvf&flagIndir != 0 {
|
||||
vt = reflect.PtrTo(v.Type())
|
||||
indirects++
|
||||
} else if offsetScalar != 0 {
|
||||
// The value is in the scalar field when it's not one of the
|
||||
// reference types.
|
||||
switch vt.Kind() {
|
||||
case reflect.Uintptr:
|
||||
case reflect.Chan:
|
||||
case reflect.Func:
|
||||
case reflect.Map:
|
||||
case reflect.Ptr:
|
||||
case reflect.UnsafePointer:
|
||||
default:
|
||||
upv = unsafe.Pointer(uintptr(unsafe.Pointer(&v)) +
|
||||
offsetScalar)
|
||||
}
|
||||
}
|
||||
panic("reflect.Value read-only flag has changed semantics")
|
||||
|
||||
pv := reflect.NewAt(vt, upv)
|
||||
rv = pv
|
||||
for i := 0; i < indirects; i++ {
|
||||
rv = rv.Elem()
|
||||
}
|
||||
return rv
|
||||
}
|
||||
|
||||
2
vendor/github.com/davecgh/go-spew/spew/bypasssafe.go
сгенерированный
поставляемый
@@ -16,7 +16,7 @@
|
||||
// when the code is running on Google App Engine, compiled by GopherJS, or
|
||||
// "-tags safe" is added to the go build command line. The "disableunsafe"
|
||||
// tag is deprecated and thus should not be used.
|
||||
// +build js appengine safe disableunsafe !go1.4
|
||||
// +build js appengine safe disableunsafe
|
||||
|
||||
package spew
|
||||
|
||||
|
||||
2
vendor/github.com/davecgh/go-spew/spew/common.go
сгенерированный
поставляемый
@@ -180,7 +180,7 @@ func printComplex(w io.Writer, c complex128, floatPrecision int) {
|
||||
w.Write(closeParenBytes)
|
||||
}
|
||||
|
||||
// printHexPtr outputs a uintptr formatted as hexadecimal with a leading '0x'
|
||||
// printHexPtr outputs a uintptr formatted as hexidecimal with a leading '0x'
|
||||
// prefix to Writer w.
|
||||
func printHexPtr(w io.Writer, p uintptr) {
|
||||
// Null pointer.
|
||||
|
||||
298
vendor/github.com/davecgh/go-spew/spew/common_test.go
сгенерированный
поставляемый
@@ -1,298 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2013-2016 Dave Collins <dave@davec.name>
|
||||
*
|
||||
* Permission to use, copy, modify, and distribute this software for any
|
||||
* purpose with or without fee is hereby granted, provided that the above
|
||||
* copyright notice and this permission notice appear in all copies.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
||||
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
||||
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
|
||||
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
||||
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
|
||||
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
|
||||
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
||||
*/
|
||||
|
||||
package spew_test
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"github.com/davecgh/go-spew/spew"
|
||||
)
|
||||
|
||||
// custom type to test Stinger interface on non-pointer receiver.
|
||||
type stringer string
|
||||
|
||||
// String implements the Stringer interface for testing invocation of custom
|
||||
// stringers on types with non-pointer receivers.
|
||||
func (s stringer) String() string {
|
||||
return "stringer " + string(s)
|
||||
}
|
||||
|
||||
// custom type to test Stinger interface on pointer receiver.
|
||||
type pstringer string
|
||||
|
||||
// String implements the Stringer interface for testing invocation of custom
|
||||
// stringers on types with only pointer receivers.
|
||||
func (s *pstringer) String() string {
|
||||
return "stringer " + string(*s)
|
||||
}
|
||||
|
||||
// xref1 and xref2 are cross referencing structs for testing circular reference
|
||||
// detection.
|
||||
type xref1 struct {
|
||||
ps2 *xref2
|
||||
}
|
||||
type xref2 struct {
|
||||
ps1 *xref1
|
||||
}
|
||||
|
||||
// indirCir1, indirCir2, and indirCir3 are used to generate an indirect circular
|
||||
// reference for testing detection.
|
||||
type indirCir1 struct {
|
||||
ps2 *indirCir2
|
||||
}
|
||||
type indirCir2 struct {
|
||||
ps3 *indirCir3
|
||||
}
|
||||
type indirCir3 struct {
|
||||
ps1 *indirCir1
|
||||
}
|
||||
|
||||
// embed is used to test embedded structures.
|
||||
type embed struct {
|
||||
a string
|
||||
}
|
||||
|
||||
// embedwrap is used to test embedded structures.
|
||||
type embedwrap struct {
|
||||
*embed
|
||||
e *embed
|
||||
}
|
||||
|
||||
// panicer is used to intentionally cause a panic for testing spew properly
|
||||
// handles them
|
||||
type panicer int
|
||||
|
||||
func (p panicer) String() string {
|
||||
panic("test panic")
|
||||
}
|
||||
|
||||
// customError is used to test custom error interface invocation.
|
||||
type customError int
|
||||
|
||||
func (e customError) Error() string {
|
||||
return fmt.Sprintf("error: %d", int(e))
|
||||
}
|
||||
|
||||
// stringizeWants converts a slice of wanted test output into a format suitable
|
||||
// for a test error message.
|
||||
func stringizeWants(wants []string) string {
|
||||
s := ""
|
||||
for i, want := range wants {
|
||||
if i > 0 {
|
||||
s += fmt.Sprintf("want%d: %s", i+1, want)
|
||||
} else {
|
||||
s += "want: " + want
|
||||
}
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// testFailed returns whether or not a test failed by checking if the result
|
||||
// of the test is in the slice of wanted strings.
|
||||
func testFailed(result string, wants []string) bool {
|
||||
for _, want := range wants {
|
||||
if result == want {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
type sortableStruct struct {
|
||||
x int
|
||||
}
|
||||
|
||||
func (ss sortableStruct) String() string {
|
||||
return fmt.Sprintf("ss.%d", ss.x)
|
||||
}
|
||||
|
||||
type unsortableStruct struct {
|
||||
x int
|
||||
}
|
||||
|
||||
type sortTestCase struct {
|
||||
input []reflect.Value
|
||||
expected []reflect.Value
|
||||
}
|
||||
|
||||
func helpTestSortValues(tests []sortTestCase, cs *spew.ConfigState, t *testing.T) {
|
||||
getInterfaces := func(values []reflect.Value) []interface{} {
|
||||
interfaces := []interface{}{}
|
||||
for _, v := range values {
|
||||
interfaces = append(interfaces, v.Interface())
|
||||
}
|
||||
return interfaces
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
spew.SortValues(test.input, cs)
|
||||
// reflect.DeepEqual cannot really make sense of reflect.Value,
|
||||
// probably because of all the pointer tricks. For instance,
|
||||
// v(2.0) != v(2.0) on a 32-bits system. Turn them into interface{}
|
||||
// instead.
|
||||
input := getInterfaces(test.input)
|
||||
expected := getInterfaces(test.expected)
|
||||
if !reflect.DeepEqual(input, expected) {
|
||||
t.Errorf("Sort mismatch:\n %v != %v", input, expected)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestSortValues ensures the sort functionality for relect.Value based sorting
|
||||
// works as intended.
|
||||
func TestSortValues(t *testing.T) {
|
||||
v := reflect.ValueOf
|
||||
|
||||
a := v("a")
|
||||
b := v("b")
|
||||
c := v("c")
|
||||
embedA := v(embed{"a"})
|
||||
embedB := v(embed{"b"})
|
||||
embedC := v(embed{"c"})
|
||||
tests := []sortTestCase{
|
||||
// No values.
|
||||
{
|
||||
[]reflect.Value{},
|
||||
[]reflect.Value{},
|
||||
},
|
||||
// Bools.
|
||||
{
|
||||
[]reflect.Value{v(false), v(true), v(false)},
|
||||
[]reflect.Value{v(false), v(false), v(true)},
|
||||
},
|
||||
// Ints.
|
||||
{
|
||||
[]reflect.Value{v(2), v(1), v(3)},
|
||||
[]reflect.Value{v(1), v(2), v(3)},
|
||||
},
|
||||
// Uints.
|
||||
{
|
||||
[]reflect.Value{v(uint8(2)), v(uint8(1)), v(uint8(3))},
|
||||
[]reflect.Value{v(uint8(1)), v(uint8(2)), v(uint8(3))},
|
||||
},
|
||||
// Floats.
|
||||
{
|
||||
[]reflect.Value{v(2.0), v(1.0), v(3.0)},
|
||||
[]reflect.Value{v(1.0), v(2.0), v(3.0)},
|
||||
},
|
||||
// Strings.
|
||||
{
|
||||
[]reflect.Value{b, a, c},
|
||||
[]reflect.Value{a, b, c},
|
||||
},
|
||||
// Array
|
||||
{
|
||||
[]reflect.Value{v([3]int{3, 2, 1}), v([3]int{1, 3, 2}), v([3]int{1, 2, 3})},
|
||||
[]reflect.Value{v([3]int{1, 2, 3}), v([3]int{1, 3, 2}), v([3]int{3, 2, 1})},
|
||||
},
|
||||
// Uintptrs.
|
||||
{
|
||||
[]reflect.Value{v(uintptr(2)), v(uintptr(1)), v(uintptr(3))},
|
||||
[]reflect.Value{v(uintptr(1)), v(uintptr(2)), v(uintptr(3))},
|
||||
},
|
||||
// SortableStructs.
|
||||
{
|
||||
// Note: not sorted - DisableMethods is set.
|
||||
[]reflect.Value{v(sortableStruct{2}), v(sortableStruct{1}), v(sortableStruct{3})},
|
||||
[]reflect.Value{v(sortableStruct{2}), v(sortableStruct{1}), v(sortableStruct{3})},
|
||||
},
|
||||
// UnsortableStructs.
|
||||
{
|
||||
// Note: not sorted - SpewKeys is false.
|
||||
[]reflect.Value{v(unsortableStruct{2}), v(unsortableStruct{1}), v(unsortableStruct{3})},
|
||||
[]reflect.Value{v(unsortableStruct{2}), v(unsortableStruct{1}), v(unsortableStruct{3})},
|
||||
},
|
||||
// Invalid.
|
||||
{
|
||||
[]reflect.Value{embedB, embedA, embedC},
|
||||
[]reflect.Value{embedB, embedA, embedC},
|
||||
},
|
||||
}
|
||||
cs := spew.ConfigState{DisableMethods: true, SpewKeys: false}
|
||||
helpTestSortValues(tests, &cs, t)
|
||||
}
|
||||
|
||||
// TestSortValuesWithMethods ensures the sort functionality for relect.Value
|
||||
// based sorting works as intended when using string methods.
|
||||
func TestSortValuesWithMethods(t *testing.T) {
|
||||
v := reflect.ValueOf
|
||||
|
||||
a := v("a")
|
||||
b := v("b")
|
||||
c := v("c")
|
||||
tests := []sortTestCase{
|
||||
// Ints.
|
||||
{
|
||||
[]reflect.Value{v(2), v(1), v(3)},
|
||||
[]reflect.Value{v(1), v(2), v(3)},
|
||||
},
|
||||
// Strings.
|
||||
{
|
||||
[]reflect.Value{b, a, c},
|
||||
[]reflect.Value{a, b, c},
|
||||
},
|
||||
// SortableStructs.
|
||||
{
|
||||
[]reflect.Value{v(sortableStruct{2}), v(sortableStruct{1}), v(sortableStruct{3})},
|
||||
[]reflect.Value{v(sortableStruct{1}), v(sortableStruct{2}), v(sortableStruct{3})},
|
||||
},
|
||||
// UnsortableStructs.
|
||||
{
|
||||
// Note: not sorted - SpewKeys is false.
|
||||
[]reflect.Value{v(unsortableStruct{2}), v(unsortableStruct{1}), v(unsortableStruct{3})},
|
||||
[]reflect.Value{v(unsortableStruct{2}), v(unsortableStruct{1}), v(unsortableStruct{3})},
|
||||
},
|
||||
}
|
||||
cs := spew.ConfigState{DisableMethods: false, SpewKeys: false}
|
||||
helpTestSortValues(tests, &cs, t)
|
||||
}
|
||||
|
||||
// TestSortValuesWithSpew ensures the sort functionality for relect.Value
|
||||
// based sorting works as intended when using spew to stringify keys.
|
||||
func TestSortValuesWithSpew(t *testing.T) {
|
||||
v := reflect.ValueOf
|
||||
|
||||
a := v("a")
|
||||
b := v("b")
|
||||
c := v("c")
|
||||
tests := []sortTestCase{
|
||||
// Ints.
|
||||
{
|
||||
[]reflect.Value{v(2), v(1), v(3)},
|
||||
[]reflect.Value{v(1), v(2), v(3)},
|
||||
},
|
||||
// Strings.
|
||||
{
|
||||
[]reflect.Value{b, a, c},
|
||||
[]reflect.Value{a, b, c},
|
||||
},
|
||||
// SortableStructs.
|
||||
{
|
||||
[]reflect.Value{v(sortableStruct{2}), v(sortableStruct{1}), v(sortableStruct{3})},
|
||||
[]reflect.Value{v(sortableStruct{1}), v(sortableStruct{2}), v(sortableStruct{3})},
|
||||
},
|
||||
// UnsortableStructs.
|
||||
{
|
||||
[]reflect.Value{v(unsortableStruct{2}), v(unsortableStruct{1}), v(unsortableStruct{3})},
|
||||
[]reflect.Value{v(unsortableStruct{1}), v(unsortableStruct{2}), v(unsortableStruct{3})},
|
||||
},
|
||||
}
|
||||
cs := spew.ConfigState{DisableMethods: true, SpewKeys: true}
|
||||
helpTestSortValues(tests, &cs, t)
|
||||
}
|
||||
10
vendor/github.com/davecgh/go-spew/spew/dump.go
сгенерированный
поставляемый
@@ -35,16 +35,16 @@ var (
|
||||
|
||||
// cCharRE is a regular expression that matches a cgo char.
|
||||
// It is used to detect character arrays to hexdump them.
|
||||
cCharRE = regexp.MustCompile(`^.*\._Ctype_char$`)
|
||||
cCharRE = regexp.MustCompile("^.*\\._Ctype_char$")
|
||||
|
||||
// cUnsignedCharRE is a regular expression that matches a cgo unsigned
|
||||
// char. It is used to detect unsigned character arrays to hexdump
|
||||
// them.
|
||||
cUnsignedCharRE = regexp.MustCompile(`^.*\._Ctype_unsignedchar$`)
|
||||
cUnsignedCharRE = regexp.MustCompile("^.*\\._Ctype_unsignedchar$")
|
||||
|
||||
// cUint8tCharRE is a regular expression that matches a cgo uint8_t.
|
||||
// It is used to detect uint8_t arrays to hexdump them.
|
||||
cUint8tCharRE = regexp.MustCompile(`^.*\._Ctype_uint8_t$`)
|
||||
cUint8tCharRE = regexp.MustCompile("^.*\\._Ctype_uint8_t$")
|
||||
)
|
||||
|
||||
// dumpState contains information about the state of a dump operation.
|
||||
@@ -143,10 +143,10 @@ func (d *dumpState) dumpPtr(v reflect.Value) {
|
||||
// Display dereferenced value.
|
||||
d.w.Write(openParenBytes)
|
||||
switch {
|
||||
case nilFound:
|
||||
case nilFound == true:
|
||||
d.w.Write(nilAngleBytes)
|
||||
|
||||
case cycleFound:
|
||||
case cycleFound == true:
|
||||
d.w.Write(circularBytes)
|
||||
|
||||
default:
|
||||
|
||||
1042
vendor/github.com/davecgh/go-spew/spew/dump_test.go
сгенерированный
поставляемый
101
vendor/github.com/davecgh/go-spew/spew/dumpcgo_test.go
сгенерированный
поставляемый
@@ -1,101 +0,0 @@
|
||||
// Copyright (c) 2013-2016 Dave Collins <dave@davec.name>
|
||||
//
|
||||
// Permission to use, copy, modify, and distribute this software for any
|
||||
// purpose with or without fee is hereby granted, provided that the above
|
||||
// copyright notice and this permission notice appear in all copies.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
||||
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
||||
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
|
||||
// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
||||
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
|
||||
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
|
||||
// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
||||
|
||||
// NOTE: Due to the following build constraints, this file will only be compiled
|
||||
// when both cgo is supported and "-tags testcgo" is added to the go test
|
||||
// command line. This means the cgo tests are only added (and hence run) when
|
||||
// specifially requested. This configuration is used because spew itself
|
||||
// does not require cgo to run even though it does handle certain cgo types
|
||||
// specially. Rather than forcing all clients to require cgo and an external
|
||||
// C compiler just to run the tests, this scheme makes them optional.
|
||||
// +build cgo,testcgo
|
||||
|
||||
package spew_test
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/davecgh/go-spew/spew/testdata"
|
||||
)
|
||||
|
||||
func addCgoDumpTests() {
|
||||
// C char pointer.
|
||||
v := testdata.GetCgoCharPointer()
|
||||
nv := testdata.GetCgoNullCharPointer()
|
||||
pv := &v
|
||||
vcAddr := fmt.Sprintf("%p", v)
|
||||
vAddr := fmt.Sprintf("%p", pv)
|
||||
pvAddr := fmt.Sprintf("%p", &pv)
|
||||
vt := "*testdata._Ctype_char"
|
||||
vs := "116"
|
||||
addDumpTest(v, "("+vt+")("+vcAddr+")("+vs+")\n")
|
||||
addDumpTest(pv, "(*"+vt+")("+vAddr+"->"+vcAddr+")("+vs+")\n")
|
||||
addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+"->"+vcAddr+")("+vs+")\n")
|
||||
addDumpTest(nv, "("+vt+")(<nil>)\n")
|
||||
|
||||
// C char array.
|
||||
v2, v2l, v2c := testdata.GetCgoCharArray()
|
||||
v2Len := fmt.Sprintf("%d", v2l)
|
||||
v2Cap := fmt.Sprintf("%d", v2c)
|
||||
v2t := "[6]testdata._Ctype_char"
|
||||
v2s := "(len=" + v2Len + " cap=" + v2Cap + ") " +
|
||||
"{\n 00000000 74 65 73 74 32 00 " +
|
||||
" |test2.|\n}"
|
||||
addDumpTest(v2, "("+v2t+") "+v2s+"\n")
|
||||
|
||||
// C unsigned char array.
|
||||
v3, v3l, v3c := testdata.GetCgoUnsignedCharArray()
|
||||
v3Len := fmt.Sprintf("%d", v3l)
|
||||
v3Cap := fmt.Sprintf("%d", v3c)
|
||||
v3t := "[6]testdata._Ctype_unsignedchar"
|
||||
v3t2 := "[6]testdata._Ctype_uchar"
|
||||
v3s := "(len=" + v3Len + " cap=" + v3Cap + ") " +
|
||||
"{\n 00000000 74 65 73 74 33 00 " +
|
||||
" |test3.|\n}"
|
||||
addDumpTest(v3, "("+v3t+") "+v3s+"\n", "("+v3t2+") "+v3s+"\n")
|
||||
|
||||
// C signed char array.
|
||||
v4, v4l, v4c := testdata.GetCgoSignedCharArray()
|
||||
v4Len := fmt.Sprintf("%d", v4l)
|
||||
v4Cap := fmt.Sprintf("%d", v4c)
|
||||
v4t := "[6]testdata._Ctype_schar"
|
||||
v4t2 := "testdata._Ctype_schar"
|
||||
v4s := "(len=" + v4Len + " cap=" + v4Cap + ") " +
|
||||
"{\n (" + v4t2 + ") 116,\n (" + v4t2 + ") 101,\n (" + v4t2 +
|
||||
") 115,\n (" + v4t2 + ") 116,\n (" + v4t2 + ") 52,\n (" + v4t2 +
|
||||
") 0\n}"
|
||||
addDumpTest(v4, "("+v4t+") "+v4s+"\n")
|
||||
|
||||
// C uint8_t array.
|
||||
v5, v5l, v5c := testdata.GetCgoUint8tArray()
|
||||
v5Len := fmt.Sprintf("%d", v5l)
|
||||
v5Cap := fmt.Sprintf("%d", v5c)
|
||||
v5t := "[6]testdata._Ctype_uint8_t"
|
||||
v5t2 := "[6]testdata._Ctype_uchar"
|
||||
v5s := "(len=" + v5Len + " cap=" + v5Cap + ") " +
|
||||
"{\n 00000000 74 65 73 74 35 00 " +
|
||||
" |test5.|\n}"
|
||||
addDumpTest(v5, "("+v5t+") "+v5s+"\n", "("+v5t2+") "+v5s+"\n")
|
||||
|
||||
// C typedefed unsigned char array.
|
||||
v6, v6l, v6c := testdata.GetCgoTypdefedUnsignedCharArray()
|
||||
v6Len := fmt.Sprintf("%d", v6l)
|
||||
v6Cap := fmt.Sprintf("%d", v6c)
|
||||
v6t := "[6]testdata._Ctype_custom_uchar_t"
|
||||
v6t2 := "[6]testdata._Ctype_uchar"
|
||||
v6s := "(len=" + v6Len + " cap=" + v6Cap + ") " +
|
||||
"{\n 00000000 74 65 73 74 36 00 " +
|
||||
" |test6.|\n}"
|
||||
addDumpTest(v6, "("+v6t+") "+v6s+"\n", "("+v6t2+") "+v6s+"\n")
|
||||
}
|
||||
26
vendor/github.com/davecgh/go-spew/spew/dumpnocgo_test.go
сгенерированный
поставляемый
@@ -1,26 +0,0 @@
|
||||
// Copyright (c) 2013 Dave Collins <dave@davec.name>
|
||||
//
|
||||
// Permission to use, copy, modify, and distribute this software for any
|
||||
// purpose with or without fee is hereby granted, provided that the above
|
||||
// copyright notice and this permission notice appear in all copies.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
||||
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
||||
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
|
||||
// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
||||
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
|
||||
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
|
||||
// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
||||
|
||||
// NOTE: Due to the following build constraints, this file will only be compiled
|
||||
// when either cgo is not supported or "-tags testcgo" is not added to the go
|
||||
// test command line. This file intentionally does not setup any cgo tests in
|
||||
// this scenario.
|
||||
// +build !cgo !testcgo
|
||||
|
||||
package spew_test
|
||||
|
||||
func addCgoDumpTests() {
|
||||
// Don't add any tests for cgo since this file is only compiled when
|
||||
// there should not be any cgo tests.
|
||||
}
|
||||
226
vendor/github.com/davecgh/go-spew/spew/example_test.go
сгенерированный
поставляемый
@@ -1,226 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2013-2016 Dave Collins <dave@davec.name>
|
||||
*
|
||||
* Permission to use, copy, modify, and distribute this software for any
|
||||
* purpose with or without fee is hereby granted, provided that the above
|
||||
* copyright notice and this permission notice appear in all copies.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
||||
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
||||
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
|
||||
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
||||
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
|
||||
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
|
||||
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
||||
*/
|
||||
|
||||
package spew_test
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/davecgh/go-spew/spew"
|
||||
)
|
||||
|
||||
type Flag int
|
||||
|
||||
const (
|
||||
flagOne Flag = iota
|
||||
flagTwo
|
||||
)
|
||||
|
||||
var flagStrings = map[Flag]string{
|
||||
flagOne: "flagOne",
|
||||
flagTwo: "flagTwo",
|
||||
}
|
||||
|
||||
func (f Flag) String() string {
|
||||
if s, ok := flagStrings[f]; ok {
|
||||
return s
|
||||
}
|
||||
return fmt.Sprintf("Unknown flag (%d)", int(f))
|
||||
}
|
||||
|
||||
type Bar struct {
|
||||
data uintptr
|
||||
}
|
||||
|
||||
type Foo struct {
|
||||
unexportedField Bar
|
||||
ExportedField map[interface{}]interface{}
|
||||
}
|
||||
|
||||
// This example demonstrates how to use Dump to dump variables to stdout.
|
||||
func ExampleDump() {
|
||||
// The following package level declarations are assumed for this example:
|
||||
/*
|
||||
type Flag int
|
||||
|
||||
const (
|
||||
flagOne Flag = iota
|
||||
flagTwo
|
||||
)
|
||||
|
||||
var flagStrings = map[Flag]string{
|
||||
flagOne: "flagOne",
|
||||
flagTwo: "flagTwo",
|
||||
}
|
||||
|
||||
func (f Flag) String() string {
|
||||
if s, ok := flagStrings[f]; ok {
|
||||
return s
|
||||
}
|
||||
return fmt.Sprintf("Unknown flag (%d)", int(f))
|
||||
}
|
||||
|
||||
type Bar struct {
|
||||
data uintptr
|
||||
}
|
||||
|
||||
type Foo struct {
|
||||
unexportedField Bar
|
||||
ExportedField map[interface{}]interface{}
|
||||
}
|
||||
*/
|
||||
|
||||
// Setup some sample data structures for the example.
|
||||
bar := Bar{uintptr(0)}
|
||||
s1 := Foo{bar, map[interface{}]interface{}{"one": true}}
|
||||
f := Flag(5)
|
||||
b := []byte{
|
||||
0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18,
|
||||
0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20,
|
||||
0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28,
|
||||
0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30,
|
||||
0x31, 0x32,
|
||||
}
|
||||
|
||||
// Dump!
|
||||
spew.Dump(s1, f, b)
|
||||
|
||||
// Output:
|
||||
// (spew_test.Foo) {
|
||||
// unexportedField: (spew_test.Bar) {
|
||||
// data: (uintptr) <nil>
|
||||
// },
|
||||
// ExportedField: (map[interface {}]interface {}) (len=1) {
|
||||
// (string) (len=3) "one": (bool) true
|
||||
// }
|
||||
// }
|
||||
// (spew_test.Flag) Unknown flag (5)
|
||||
// ([]uint8) (len=34 cap=34) {
|
||||
// 00000000 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 20 |............... |
|
||||
// 00000010 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f 30 |!"#$%&'()*+,-./0|
|
||||
// 00000020 31 32 |12|
|
||||
// }
|
||||
//
|
||||
}
|
||||
|
||||
// This example demonstrates how to use Printf to display a variable with a
|
||||
// format string and inline formatting.
|
||||
func ExamplePrintf() {
|
||||
// Create a double pointer to a uint 8.
|
||||
ui8 := uint8(5)
|
||||
pui8 := &ui8
|
||||
ppui8 := &pui8
|
||||
|
||||
// Create a circular data type.
|
||||
type circular struct {
|
||||
ui8 uint8
|
||||
c *circular
|
||||
}
|
||||
c := circular{ui8: 1}
|
||||
c.c = &c
|
||||
|
||||
// Print!
|
||||
spew.Printf("ppui8: %v\n", ppui8)
|
||||
spew.Printf("circular: %v\n", c)
|
||||
|
||||
// Output:
|
||||
// ppui8: <**>5
|
||||
// circular: {1 <*>{1 <*><shown>}}
|
||||
}
|
||||
|
||||
// This example demonstrates how to use a ConfigState.
|
||||
func ExampleConfigState() {
|
||||
// Modify the indent level of the ConfigState only. The global
|
||||
// configuration is not modified.
|
||||
scs := spew.ConfigState{Indent: "\t"}
|
||||
|
||||
// Output using the ConfigState instance.
|
||||
v := map[string]int{"one": 1}
|
||||
scs.Printf("v: %v\n", v)
|
||||
scs.Dump(v)
|
||||
|
||||
// Output:
|
||||
// v: map[one:1]
|
||||
// (map[string]int) (len=1) {
|
||||
// (string) (len=3) "one": (int) 1
|
||||
// }
|
||||
}
|
||||
|
||||
// This example demonstrates how to use ConfigState.Dump to dump variables to
|
||||
// stdout
|
||||
func ExampleConfigState_Dump() {
|
||||
// See the top-level Dump example for details on the types used in this
|
||||
// example.
|
||||
|
||||
// Create two ConfigState instances with different indentation.
|
||||
scs := spew.ConfigState{Indent: "\t"}
|
||||
scs2 := spew.ConfigState{Indent: " "}
|
||||
|
||||
// Setup some sample data structures for the example.
|
||||
bar := Bar{uintptr(0)}
|
||||
s1 := Foo{bar, map[interface{}]interface{}{"one": true}}
|
||||
|
||||
// Dump using the ConfigState instances.
|
||||
scs.Dump(s1)
|
||||
scs2.Dump(s1)
|
||||
|
||||
// Output:
|
||||
// (spew_test.Foo) {
|
||||
// unexportedField: (spew_test.Bar) {
|
||||
// data: (uintptr) <nil>
|
||||
// },
|
||||
// ExportedField: (map[interface {}]interface {}) (len=1) {
|
||||
// (string) (len=3) "one": (bool) true
|
||||
// }
|
||||
// }
|
||||
// (spew_test.Foo) {
|
||||
// unexportedField: (spew_test.Bar) {
|
||||
// data: (uintptr) <nil>
|
||||
// },
|
||||
// ExportedField: (map[interface {}]interface {}) (len=1) {
|
||||
// (string) (len=3) "one": (bool) true
|
||||
// }
|
||||
// }
|
||||
//
|
||||
}
|
||||
|
||||
// This example demonstrates how to use ConfigState.Printf to display a variable
|
||||
// with a format string and inline formatting.
|
||||
func ExampleConfigState_Printf() {
|
||||
// See the top-level Dump example for details on the types used in this
|
||||
// example.
|
||||
|
||||
// Create two ConfigState instances and modify the method handling of the
|
||||
// first ConfigState only.
|
||||
scs := spew.NewDefaultConfig()
|
||||
scs2 := spew.NewDefaultConfig()
|
||||
scs.DisableMethods = true
|
||||
|
||||
// Alternatively
|
||||
// scs := spew.ConfigState{Indent: " ", DisableMethods: true}
|
||||
// scs2 := spew.ConfigState{Indent: " "}
|
||||
|
||||
// This is of type Flag which implements a Stringer and has raw value 1.
|
||||
f := flagTwo
|
||||
|
||||
// Dump using the ConfigState instances.
|
||||
scs.Printf("f: %v\n", f)
|
||||
scs2.Printf("f: %v\n", f)
|
||||
|
||||
// Output:
|
||||
// f: 1
|
||||
// f: flagTwo
|
||||
}
|
||||
4
vendor/github.com/davecgh/go-spew/spew/format.go
сгенерированный
поставляемый
@@ -182,10 +182,10 @@ func (f *formatState) formatPtr(v reflect.Value) {
|
||||
|
||||
// Display dereferenced value.
|
||||
switch {
|
||||
case nilFound:
|
||||
case nilFound == true:
|
||||
f.fs.Write(nilAngleBytes)
|
||||
|
||||
case cycleFound:
|
||||
case cycleFound == true:
|
||||
f.fs.Write(circularShortBytes)
|
||||
|
||||
default:
|
||||
|
||||
1558
vendor/github.com/davecgh/go-spew/spew/format_test.go
сгенерированный
поставляемый
84
vendor/github.com/davecgh/go-spew/spew/internal_test.go
сгенерированный
поставляемый
@@ -1,84 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2013-2016 Dave Collins <dave@davec.name>
|
||||
*
|
||||
* Permission to use, copy, modify, and distribute this software for any
|
||||
* purpose with or without fee is hereby granted, provided that the above
|
||||
* copyright notice and this permission notice appear in all copies.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
||||
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
||||
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
|
||||
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
||||
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
|
||||
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
|
||||
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
||||
*/
|
||||
|
||||
/*
|
||||
This test file is part of the spew package rather than than the spew_test
|
||||
package because it needs access to internals to properly test certain cases
|
||||
which are not possible via the public interface since they should never happen.
|
||||
*/
|
||||
|
||||
package spew
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// dummyFmtState implements a fake fmt.State to use for testing invalid
|
||||
// reflect.Value handling. This is necessary because the fmt package catches
|
||||
// invalid values before invoking the formatter on them.
|
||||
type dummyFmtState struct {
|
||||
bytes.Buffer
|
||||
}
|
||||
|
||||
func (dfs *dummyFmtState) Flag(f int) bool {
|
||||
return f == int('+')
|
||||
}
|
||||
|
||||
func (dfs *dummyFmtState) Precision() (int, bool) {
|
||||
return 0, false
|
||||
}
|
||||
|
||||
func (dfs *dummyFmtState) Width() (int, bool) {
|
||||
return 0, false
|
||||
}
|
||||
|
||||
// TestInvalidReflectValue ensures the dump and formatter code handles an
|
||||
// invalid reflect value properly. This needs access to internal state since it
|
||||
// should never happen in real code and therefore can't be tested via the public
|
||||
// API.
|
||||
func TestInvalidReflectValue(t *testing.T) {
|
||||
i := 1
|
||||
|
||||
// Dump invalid reflect value.
|
||||
v := new(reflect.Value)
|
||||
buf := new(bytes.Buffer)
|
||||
d := dumpState{w: buf, cs: &Config}
|
||||
d.dump(*v)
|
||||
s := buf.String()
|
||||
want := "<invalid>"
|
||||
if s != want {
|
||||
t.Errorf("InvalidReflectValue #%d\n got: %s want: %s", i, s, want)
|
||||
}
|
||||
i++
|
||||
|
||||
// Formatter invalid reflect value.
|
||||
buf2 := new(dummyFmtState)
|
||||
f := formatState{value: *v, cs: &Config, fs: buf2}
|
||||
f.format(*v)
|
||||
s = buf2.String()
|
||||
want = "<invalid>"
|
||||
if s != want {
|
||||
t.Errorf("InvalidReflectValue #%d got: %s want: %s", i, s, want)
|
||||
}
|
||||
}
|
||||
|
||||
// SortValues makes the internal sortValues function available to the test
|
||||
// package.
|
||||
func SortValues(values []reflect.Value, cs *ConfigState) {
|
||||
sortValues(values, cs)
|
||||
}
|
||||
101
vendor/github.com/davecgh/go-spew/spew/internalunsafe_test.go
сгенерированный
поставляемый
@@ -1,101 +0,0 @@
|
||||
// Copyright (c) 2013-2016 Dave Collins <dave@davec.name>
|
||||
|
||||
// Permission to use, copy, modify, and distribute this software for any
|
||||
// purpose with or without fee is hereby granted, provided that the above
|
||||
// copyright notice and this permission notice appear in all copies.
|
||||
|
||||
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
||||
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
||||
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
|
||||
// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
||||
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
|
||||
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
|
||||
// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
||||
|
||||
// NOTE: Due to the following build constraints, this file will only be compiled
|
||||
// when the code is not running on Google App Engine, compiled by GopherJS, and
|
||||
// "-tags safe" is not added to the go build command line. The "disableunsafe"
|
||||
// tag is deprecated and thus should not be used.
|
||||
// +build !js,!appengine,!safe,!disableunsafe,go1.4
|
||||
|
||||
/*
|
||||
This test file is part of the spew package rather than than the spew_test
|
||||
package because it needs access to internals to properly test certain cases
|
||||
which are not possible via the public interface since they should never happen.
|
||||
*/
|
||||
|
||||
package spew
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// changeKind uses unsafe to intentionally change the kind of a reflect.Value to
|
||||
// the maximum kind value which does not exist. This is needed to test the
|
||||
// fallback code which punts to the standard fmt library for new types that
|
||||
// might get added to the language.
|
||||
func changeKind(v *reflect.Value, readOnly bool) {
|
||||
flags := flagField(v)
|
||||
if readOnly {
|
||||
*flags |= flagRO
|
||||
} else {
|
||||
*flags &^= flagRO
|
||||
}
|
||||
*flags |= flagKindMask
|
||||
}
|
||||
|
||||
// TestAddedReflectValue tests functionaly of the dump and formatter code which
|
||||
// falls back to the standard fmt library for new types that might get added to
|
||||
// the language.
|
||||
func TestAddedReflectValue(t *testing.T) {
|
||||
i := 1
|
||||
|
||||
// Dump using a reflect.Value that is exported.
|
||||
v := reflect.ValueOf(int8(5))
|
||||
changeKind(&v, false)
|
||||
buf := new(bytes.Buffer)
|
||||
d := dumpState{w: buf, cs: &Config}
|
||||
d.dump(v)
|
||||
s := buf.String()
|
||||
want := "(int8) 5"
|
||||
if s != want {
|
||||
t.Errorf("TestAddedReflectValue #%d\n got: %s want: %s", i, s, want)
|
||||
}
|
||||
i++
|
||||
|
||||
// Dump using a reflect.Value that is not exported.
|
||||
changeKind(&v, true)
|
||||
buf.Reset()
|
||||
d.dump(v)
|
||||
s = buf.String()
|
||||
want = "(int8) <int8 Value>"
|
||||
if s != want {
|
||||
t.Errorf("TestAddedReflectValue #%d\n got: %s want: %s", i, s, want)
|
||||
}
|
||||
i++
|
||||
|
||||
// Formatter using a reflect.Value that is exported.
|
||||
changeKind(&v, false)
|
||||
buf2 := new(dummyFmtState)
|
||||
f := formatState{value: v, cs: &Config, fs: buf2}
|
||||
f.format(v)
|
||||
s = buf2.String()
|
||||
want = "5"
|
||||
if s != want {
|
||||
t.Errorf("TestAddedReflectValue #%d got: %s want: %s", i, s, want)
|
||||
}
|
||||
i++
|
||||
|
||||
// Formatter using a reflect.Value that is not exported.
|
||||
changeKind(&v, true)
|
||||
buf2.Reset()
|
||||
f = formatState{value: v, cs: &Config, fs: buf2}
|
||||
f.format(v)
|
||||
s = buf2.String()
|
||||
want = "<int8 Value>"
|
||||
if s != want {
|
||||
t.Errorf("TestAddedReflectValue #%d got: %s want: %s", i, s, want)
|
||||
}
|
||||
}
|
||||
320
vendor/github.com/davecgh/go-spew/spew/spew_test.go
сгенерированный
поставляемый
@@ -1,320 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2013-2016 Dave Collins <dave@davec.name>
|
||||
*
|
||||
* Permission to use, copy, modify, and distribute this software for any
|
||||
* purpose with or without fee is hereby granted, provided that the above
|
||||
* copyright notice and this permission notice appear in all copies.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
||||
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
||||
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
|
||||
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
||||
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
|
||||
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
|
||||
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
||||
*/
|
||||
|
||||
package spew_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"github.com/davecgh/go-spew/spew"
|
||||
)
|
||||
|
||||
// spewFunc is used to identify which public function of the spew package or
|
||||
// ConfigState a test applies to.
|
||||
type spewFunc int
|
||||
|
||||
const (
|
||||
fCSFdump spewFunc = iota
|
||||
fCSFprint
|
||||
fCSFprintf
|
||||
fCSFprintln
|
||||
fCSPrint
|
||||
fCSPrintln
|
||||
fCSSdump
|
||||
fCSSprint
|
||||
fCSSprintf
|
||||
fCSSprintln
|
||||
fCSErrorf
|
||||
fCSNewFormatter
|
||||
fErrorf
|
||||
fFprint
|
||||
fFprintln
|
||||
fPrint
|
||||
fPrintln
|
||||
fSdump
|
||||
fSprint
|
||||
fSprintf
|
||||
fSprintln
|
||||
)
|
||||
|
||||
// Map of spewFunc values to names for pretty printing.
|
||||
var spewFuncStrings = map[spewFunc]string{
|
||||
fCSFdump: "ConfigState.Fdump",
|
||||
fCSFprint: "ConfigState.Fprint",
|
||||
fCSFprintf: "ConfigState.Fprintf",
|
||||
fCSFprintln: "ConfigState.Fprintln",
|
||||
fCSSdump: "ConfigState.Sdump",
|
||||
fCSPrint: "ConfigState.Print",
|
||||
fCSPrintln: "ConfigState.Println",
|
||||
fCSSprint: "ConfigState.Sprint",
|
||||
fCSSprintf: "ConfigState.Sprintf",
|
||||
fCSSprintln: "ConfigState.Sprintln",
|
||||
fCSErrorf: "ConfigState.Errorf",
|
||||
fCSNewFormatter: "ConfigState.NewFormatter",
|
||||
fErrorf: "spew.Errorf",
|
||||
fFprint: "spew.Fprint",
|
||||
fFprintln: "spew.Fprintln",
|
||||
fPrint: "spew.Print",
|
||||
fPrintln: "spew.Println",
|
||||
fSdump: "spew.Sdump",
|
||||
fSprint: "spew.Sprint",
|
||||
fSprintf: "spew.Sprintf",
|
||||
fSprintln: "spew.Sprintln",
|
||||
}
|
||||
|
||||
func (f spewFunc) String() string {
|
||||
if s, ok := spewFuncStrings[f]; ok {
|
||||
return s
|
||||
}
|
||||
return fmt.Sprintf("Unknown spewFunc (%d)", int(f))
|
||||
}
|
||||
|
||||
// spewTest is used to describe a test to be performed against the public
|
||||
// functions of the spew package or ConfigState.
|
||||
type spewTest struct {
|
||||
cs *spew.ConfigState
|
||||
f spewFunc
|
||||
format string
|
||||
in interface{}
|
||||
want string
|
||||
}
|
||||
|
||||
// spewTests houses the tests to be performed against the public functions of
|
||||
// the spew package and ConfigState.
|
||||
//
|
||||
// These tests are only intended to ensure the public functions are exercised
|
||||
// and are intentionally not exhaustive of types. The exhaustive type
|
||||
// tests are handled in the dump and format tests.
|
||||
var spewTests []spewTest
|
||||
|
||||
// redirStdout is a helper function to return the standard output from f as a
|
||||
// byte slice.
|
||||
func redirStdout(f func()) ([]byte, error) {
|
||||
tempFile, err := ioutil.TempFile("", "ss-test")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
fileName := tempFile.Name()
|
||||
defer os.Remove(fileName) // Ignore error
|
||||
|
||||
origStdout := os.Stdout
|
||||
os.Stdout = tempFile
|
||||
f()
|
||||
os.Stdout = origStdout
|
||||
tempFile.Close()
|
||||
|
||||
return ioutil.ReadFile(fileName)
|
||||
}
|
||||
|
||||
func initSpewTests() {
|
||||
// Config states with various settings.
|
||||
scsDefault := spew.NewDefaultConfig()
|
||||
scsNoMethods := &spew.ConfigState{Indent: " ", DisableMethods: true}
|
||||
scsNoPmethods := &spew.ConfigState{Indent: " ", DisablePointerMethods: true}
|
||||
scsMaxDepth := &spew.ConfigState{Indent: " ", MaxDepth: 1}
|
||||
scsContinue := &spew.ConfigState{Indent: " ", ContinueOnMethod: true}
|
||||
scsNoPtrAddr := &spew.ConfigState{DisablePointerAddresses: true}
|
||||
scsNoCap := &spew.ConfigState{DisableCapacities: true}
|
||||
|
||||
// Variables for tests on types which implement Stringer interface with and
|
||||
// without a pointer receiver.
|
||||
ts := stringer("test")
|
||||
tps := pstringer("test")
|
||||
|
||||
type ptrTester struct {
|
||||
s *struct{}
|
||||
}
|
||||
tptr := &ptrTester{s: &struct{}{}}
|
||||
|
||||
// depthTester is used to test max depth handling for structs, array, slices
|
||||
// and maps.
|
||||
type depthTester struct {
|
||||
ic indirCir1
|
||||
arr [1]string
|
||||
slice []string
|
||||
m map[string]int
|
||||
}
|
||||
dt := depthTester{indirCir1{nil}, [1]string{"arr"}, []string{"slice"},
|
||||
map[string]int{"one": 1}}
|
||||
|
||||
// Variable for tests on types which implement error interface.
|
||||
te := customError(10)
|
||||
|
||||
spewTests = []spewTest{
|
||||
{scsDefault, fCSFdump, "", int8(127), "(int8) 127\n"},
|
||||
{scsDefault, fCSFprint, "", int16(32767), "32767"},
|
||||
{scsDefault, fCSFprintf, "%v", int32(2147483647), "2147483647"},
|
||||
{scsDefault, fCSFprintln, "", int(2147483647), "2147483647\n"},
|
||||
{scsDefault, fCSPrint, "", int64(9223372036854775807), "9223372036854775807"},
|
||||
{scsDefault, fCSPrintln, "", uint8(255), "255\n"},
|
||||
{scsDefault, fCSSdump, "", uint8(64), "(uint8) 64\n"},
|
||||
{scsDefault, fCSSprint, "", complex(1, 2), "(1+2i)"},
|
||||
{scsDefault, fCSSprintf, "%v", complex(float32(3), 4), "(3+4i)"},
|
||||
{scsDefault, fCSSprintln, "", complex(float64(5), 6), "(5+6i)\n"},
|
||||
{scsDefault, fCSErrorf, "%#v", uint16(65535), "(uint16)65535"},
|
||||
{scsDefault, fCSNewFormatter, "%v", uint32(4294967295), "4294967295"},
|
||||
{scsDefault, fErrorf, "%v", uint64(18446744073709551615), "18446744073709551615"},
|
||||
{scsDefault, fFprint, "", float32(3.14), "3.14"},
|
||||
{scsDefault, fFprintln, "", float64(6.28), "6.28\n"},
|
||||
{scsDefault, fPrint, "", true, "true"},
|
||||
{scsDefault, fPrintln, "", false, "false\n"},
|
||||
{scsDefault, fSdump, "", complex(-10, -20), "(complex128) (-10-20i)\n"},
|
||||
{scsDefault, fSprint, "", complex(-1, -2), "(-1-2i)"},
|
||||
{scsDefault, fSprintf, "%v", complex(float32(-3), -4), "(-3-4i)"},
|
||||
{scsDefault, fSprintln, "", complex(float64(-5), -6), "(-5-6i)\n"},
|
||||
{scsNoMethods, fCSFprint, "", ts, "test"},
|
||||
{scsNoMethods, fCSFprint, "", &ts, "<*>test"},
|
||||
{scsNoMethods, fCSFprint, "", tps, "test"},
|
||||
{scsNoMethods, fCSFprint, "", &tps, "<*>test"},
|
||||
{scsNoPmethods, fCSFprint, "", ts, "stringer test"},
|
||||
{scsNoPmethods, fCSFprint, "", &ts, "<*>stringer test"},
|
||||
{scsNoPmethods, fCSFprint, "", tps, "test"},
|
||||
{scsNoPmethods, fCSFprint, "", &tps, "<*>stringer test"},
|
||||
{scsMaxDepth, fCSFprint, "", dt, "{{<max>} [<max>] [<max>] map[<max>]}"},
|
||||
{scsMaxDepth, fCSFdump, "", dt, "(spew_test.depthTester) {\n" +
|
||||
" ic: (spew_test.indirCir1) {\n <max depth reached>\n },\n" +
|
||||
" arr: ([1]string) (len=1 cap=1) {\n <max depth reached>\n },\n" +
|
||||
" slice: ([]string) (len=1 cap=1) {\n <max depth reached>\n },\n" +
|
||||
" m: (map[string]int) (len=1) {\n <max depth reached>\n }\n}\n"},
|
||||
{scsContinue, fCSFprint, "", ts, "(stringer test) test"},
|
||||
{scsContinue, fCSFdump, "", ts, "(spew_test.stringer) " +
|
||||
"(len=4) (stringer test) \"test\"\n"},
|
||||
{scsContinue, fCSFprint, "", te, "(error: 10) 10"},
|
||||
{scsContinue, fCSFdump, "", te, "(spew_test.customError) " +
|
||||
"(error: 10) 10\n"},
|
||||
{scsNoPtrAddr, fCSFprint, "", tptr, "<*>{<*>{}}"},
|
||||
{scsNoPtrAddr, fCSSdump, "", tptr, "(*spew_test.ptrTester)({\ns: (*struct {})({\n})\n})\n"},
|
||||
{scsNoCap, fCSSdump, "", make([]string, 0, 10), "([]string) {\n}\n"},
|
||||
{scsNoCap, fCSSdump, "", make([]string, 1, 10), "([]string) (len=1) {\n(string) \"\"\n}\n"},
|
||||
}
|
||||
}
|
||||
|
||||
// TestSpew executes all of the tests described by spewTests.
|
||||
func TestSpew(t *testing.T) {
|
||||
initSpewTests()
|
||||
|
||||
t.Logf("Running %d tests", len(spewTests))
|
||||
for i, test := range spewTests {
|
||||
buf := new(bytes.Buffer)
|
||||
switch test.f {
|
||||
case fCSFdump:
|
||||
test.cs.Fdump(buf, test.in)
|
||||
|
||||
case fCSFprint:
|
||||
test.cs.Fprint(buf, test.in)
|
||||
|
||||
case fCSFprintf:
|
||||
test.cs.Fprintf(buf, test.format, test.in)
|
||||
|
||||
case fCSFprintln:
|
||||
test.cs.Fprintln(buf, test.in)
|
||||
|
||||
case fCSPrint:
|
||||
b, err := redirStdout(func() { test.cs.Print(test.in) })
|
||||
if err != nil {
|
||||
t.Errorf("%v #%d %v", test.f, i, err)
|
||||
continue
|
||||
}
|
||||
buf.Write(b)
|
||||
|
||||
case fCSPrintln:
|
||||
b, err := redirStdout(func() { test.cs.Println(test.in) })
|
||||
if err != nil {
|
||||
t.Errorf("%v #%d %v", test.f, i, err)
|
||||
continue
|
||||
}
|
||||
buf.Write(b)
|
||||
|
||||
case fCSSdump:
|
||||
str := test.cs.Sdump(test.in)
|
||||
buf.WriteString(str)
|
||||
|
||||
case fCSSprint:
|
||||
str := test.cs.Sprint(test.in)
|
||||
buf.WriteString(str)
|
||||
|
||||
case fCSSprintf:
|
||||
str := test.cs.Sprintf(test.format, test.in)
|
||||
buf.WriteString(str)
|
||||
|
||||
case fCSSprintln:
|
||||
str := test.cs.Sprintln(test.in)
|
||||
buf.WriteString(str)
|
||||
|
||||
case fCSErrorf:
|
||||
err := test.cs.Errorf(test.format, test.in)
|
||||
buf.WriteString(err.Error())
|
||||
|
||||
case fCSNewFormatter:
|
||||
fmt.Fprintf(buf, test.format, test.cs.NewFormatter(test.in))
|
||||
|
||||
case fErrorf:
|
||||
err := spew.Errorf(test.format, test.in)
|
||||
buf.WriteString(err.Error())
|
||||
|
||||
case fFprint:
|
||||
spew.Fprint(buf, test.in)
|
||||
|
||||
case fFprintln:
|
||||
spew.Fprintln(buf, test.in)
|
||||
|
||||
case fPrint:
|
||||
b, err := redirStdout(func() { spew.Print(test.in) })
|
||||
if err != nil {
|
||||
t.Errorf("%v #%d %v", test.f, i, err)
|
||||
continue
|
||||
}
|
||||
buf.Write(b)
|
||||
|
||||
case fPrintln:
|
||||
b, err := redirStdout(func() { spew.Println(test.in) })
|
||||
if err != nil {
|
||||
t.Errorf("%v #%d %v", test.f, i, err)
|
||||
continue
|
||||
}
|
||||
buf.Write(b)
|
||||
|
||||
case fSdump:
|
||||
str := spew.Sdump(test.in)
|
||||
buf.WriteString(str)
|
||||
|
||||
case fSprint:
|
||||
str := spew.Sprint(test.in)
|
||||
buf.WriteString(str)
|
||||
|
||||
case fSprintf:
|
||||
str := spew.Sprintf(test.format, test.in)
|
||||
buf.WriteString(str)
|
||||
|
||||
case fSprintln:
|
||||
str := spew.Sprintln(test.in)
|
||||
buf.WriteString(str)
|
||||
|
||||
default:
|
||||
t.Errorf("%v #%d unrecognized function", test.f, i)
|
||||
continue
|
||||
}
|
||||
s := buf.String()
|
||||
if test.want != s {
|
||||
t.Errorf("ConfigState #%d\n got: %s want: %s", i, s, test.want)
|
||||
continue
|
||||
}
|
||||
}
|
||||
}
|
||||
82
vendor/github.com/davecgh/go-spew/spew/testdata/dumpcgo.go
сгенерированный
поставляемый
@@ -1,82 +0,0 @@
|
||||
// Copyright (c) 2013 Dave Collins <dave@davec.name>
|
||||
//
|
||||
// Permission to use, copy, modify, and distribute this software for any
|
||||
// purpose with or without fee is hereby granted, provided that the above
|
||||
// copyright notice and this permission notice appear in all copies.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
||||
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
||||
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
|
||||
// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
||||
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
|
||||
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
|
||||
// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
||||
|
||||
// NOTE: Due to the following build constraints, this file will only be compiled
|
||||
// when both cgo is supported and "-tags testcgo" is added to the go test
|
||||
// command line. This code should really only be in the dumpcgo_test.go file,
|
||||
// but unfortunately Go will not allow cgo in test files, so this is a
|
||||
// workaround to allow cgo types to be tested. This configuration is used
|
||||
// because spew itself does not require cgo to run even though it does handle
|
||||
// certain cgo types specially. Rather than forcing all clients to require cgo
|
||||
// and an external C compiler just to run the tests, this scheme makes them
|
||||
// optional.
|
||||
// +build cgo,testcgo
|
||||
|
||||
package testdata
|
||||
|
||||
/*
|
||||
#include <stdint.h>
|
||||
typedef unsigned char custom_uchar_t;
|
||||
|
||||
char *ncp = 0;
|
||||
char *cp = "test";
|
||||
char ca[6] = {'t', 'e', 's', 't', '2', '\0'};
|
||||
unsigned char uca[6] = {'t', 'e', 's', 't', '3', '\0'};
|
||||
signed char sca[6] = {'t', 'e', 's', 't', '4', '\0'};
|
||||
uint8_t ui8ta[6] = {'t', 'e', 's', 't', '5', '\0'};
|
||||
custom_uchar_t tuca[6] = {'t', 'e', 's', 't', '6', '\0'};
|
||||
*/
|
||||
import "C"
|
||||
|
||||
// GetCgoNullCharPointer returns a null char pointer via cgo. This is only
|
||||
// used for tests.
|
||||
func GetCgoNullCharPointer() interface{} {
|
||||
return C.ncp
|
||||
}
|
||||
|
||||
// GetCgoCharPointer returns a char pointer via cgo. This is only used for
|
||||
// tests.
|
||||
func GetCgoCharPointer() interface{} {
|
||||
return C.cp
|
||||
}
|
||||
|
||||
// GetCgoCharArray returns a char array via cgo and the array's len and cap.
|
||||
// This is only used for tests.
|
||||
func GetCgoCharArray() (interface{}, int, int) {
|
||||
return C.ca, len(C.ca), cap(C.ca)
|
||||
}
|
||||
|
||||
// GetCgoUnsignedCharArray returns an unsigned char array via cgo and the
|
||||
// array's len and cap. This is only used for tests.
|
||||
func GetCgoUnsignedCharArray() (interface{}, int, int) {
|
||||
return C.uca, len(C.uca), cap(C.uca)
|
||||
}
|
||||
|
||||
// GetCgoSignedCharArray returns a signed char array via cgo and the array's len
|
||||
// and cap. This is only used for tests.
|
||||
func GetCgoSignedCharArray() (interface{}, int, int) {
|
||||
return C.sca, len(C.sca), cap(C.sca)
|
||||
}
|
||||
|
||||
// GetCgoUint8tArray returns a uint8_t array via cgo and the array's len and
|
||||
// cap. This is only used for tests.
|
||||
func GetCgoUint8tArray() (interface{}, int, int) {
|
||||
return C.ui8ta, len(C.ui8ta), cap(C.ui8ta)
|
||||
}
|
||||
|
||||
// GetCgoTypdefedUnsignedCharArray returns a typedefed unsigned char array via
|
||||
// cgo and the array's len and cap. This is only used for tests.
|
||||
func GetCgoTypdefedUnsignedCharArray() (interface{}, int, int) {
|
||||
return C.tuca, len(C.tuca), cap(C.tuca)
|
||||
}
|
||||
61
vendor/github.com/davecgh/go-spew/test_coverage.txt
сгенерированный
поставляемый
@@ -1,61 +0,0 @@
|
||||
|
||||
github.com/davecgh/go-spew/spew/dump.go dumpState.dump 100.00% (88/88)
|
||||
github.com/davecgh/go-spew/spew/format.go formatState.format 100.00% (82/82)
|
||||
github.com/davecgh/go-spew/spew/format.go formatState.formatPtr 100.00% (52/52)
|
||||
github.com/davecgh/go-spew/spew/dump.go dumpState.dumpPtr 100.00% (44/44)
|
||||
github.com/davecgh/go-spew/spew/dump.go dumpState.dumpSlice 100.00% (39/39)
|
||||
github.com/davecgh/go-spew/spew/common.go handleMethods 100.00% (30/30)
|
||||
github.com/davecgh/go-spew/spew/common.go printHexPtr 100.00% (18/18)
|
||||
github.com/davecgh/go-spew/spew/common.go unsafeReflectValue 100.00% (13/13)
|
||||
github.com/davecgh/go-spew/spew/format.go formatState.constructOrigFormat 100.00% (12/12)
|
||||
github.com/davecgh/go-spew/spew/dump.go fdump 100.00% (11/11)
|
||||
github.com/davecgh/go-spew/spew/format.go formatState.Format 100.00% (11/11)
|
||||
github.com/davecgh/go-spew/spew/common.go init 100.00% (10/10)
|
||||
github.com/davecgh/go-spew/spew/common.go printComplex 100.00% (9/9)
|
||||
github.com/davecgh/go-spew/spew/common.go valuesSorter.Less 100.00% (8/8)
|
||||
github.com/davecgh/go-spew/spew/format.go formatState.buildDefaultFormat 100.00% (7/7)
|
||||
github.com/davecgh/go-spew/spew/format.go formatState.unpackValue 100.00% (5/5)
|
||||
github.com/davecgh/go-spew/spew/dump.go dumpState.indent 100.00% (4/4)
|
||||
github.com/davecgh/go-spew/spew/common.go catchPanic 100.00% (4/4)
|
||||
github.com/davecgh/go-spew/spew/config.go ConfigState.convertArgs 100.00% (4/4)
|
||||
github.com/davecgh/go-spew/spew/spew.go convertArgs 100.00% (4/4)
|
||||
github.com/davecgh/go-spew/spew/format.go newFormatter 100.00% (3/3)
|
||||
github.com/davecgh/go-spew/spew/dump.go Sdump 100.00% (3/3)
|
||||
github.com/davecgh/go-spew/spew/common.go printBool 100.00% (3/3)
|
||||
github.com/davecgh/go-spew/spew/common.go sortValues 100.00% (3/3)
|
||||
github.com/davecgh/go-spew/spew/config.go ConfigState.Sdump 100.00% (3/3)
|
||||
github.com/davecgh/go-spew/spew/dump.go dumpState.unpackValue 100.00% (3/3)
|
||||
github.com/davecgh/go-spew/spew/spew.go Printf 100.00% (1/1)
|
||||
github.com/davecgh/go-spew/spew/spew.go Println 100.00% (1/1)
|
||||
github.com/davecgh/go-spew/spew/spew.go Sprint 100.00% (1/1)
|
||||
github.com/davecgh/go-spew/spew/spew.go Sprintf 100.00% (1/1)
|
||||
github.com/davecgh/go-spew/spew/spew.go Sprintln 100.00% (1/1)
|
||||
github.com/davecgh/go-spew/spew/common.go printFloat 100.00% (1/1)
|
||||
github.com/davecgh/go-spew/spew/config.go NewDefaultConfig 100.00% (1/1)
|
||||
github.com/davecgh/go-spew/spew/common.go printInt 100.00% (1/1)
|
||||
github.com/davecgh/go-spew/spew/common.go printUint 100.00% (1/1)
|
||||
github.com/davecgh/go-spew/spew/common.go valuesSorter.Len 100.00% (1/1)
|
||||
github.com/davecgh/go-spew/spew/common.go valuesSorter.Swap 100.00% (1/1)
|
||||
github.com/davecgh/go-spew/spew/config.go ConfigState.Errorf 100.00% (1/1)
|
||||
github.com/davecgh/go-spew/spew/config.go ConfigState.Fprint 100.00% (1/1)
|
||||
github.com/davecgh/go-spew/spew/config.go ConfigState.Fprintf 100.00% (1/1)
|
||||
github.com/davecgh/go-spew/spew/config.go ConfigState.Fprintln 100.00% (1/1)
|
||||
github.com/davecgh/go-spew/spew/config.go ConfigState.Print 100.00% (1/1)
|
||||
github.com/davecgh/go-spew/spew/config.go ConfigState.Printf 100.00% (1/1)
|
||||
github.com/davecgh/go-spew/spew/config.go ConfigState.Println 100.00% (1/1)
|
||||
github.com/davecgh/go-spew/spew/config.go ConfigState.Sprint 100.00% (1/1)
|
||||
github.com/davecgh/go-spew/spew/config.go ConfigState.Sprintf 100.00% (1/1)
|
||||
github.com/davecgh/go-spew/spew/config.go ConfigState.Sprintln 100.00% (1/1)
|
||||
github.com/davecgh/go-spew/spew/config.go ConfigState.NewFormatter 100.00% (1/1)
|
||||
github.com/davecgh/go-spew/spew/config.go ConfigState.Fdump 100.00% (1/1)
|
||||
github.com/davecgh/go-spew/spew/config.go ConfigState.Dump 100.00% (1/1)
|
||||
github.com/davecgh/go-spew/spew/dump.go Fdump 100.00% (1/1)
|
||||
github.com/davecgh/go-spew/spew/dump.go Dump 100.00% (1/1)
|
||||
github.com/davecgh/go-spew/spew/spew.go Fprintln 100.00% (1/1)
|
||||
github.com/davecgh/go-spew/spew/format.go NewFormatter 100.00% (1/1)
|
||||
github.com/davecgh/go-spew/spew/spew.go Errorf 100.00% (1/1)
|
||||
github.com/davecgh/go-spew/spew/spew.go Fprint 100.00% (1/1)
|
||||
github.com/davecgh/go-spew/spew/spew.go Fprintf 100.00% (1/1)
|
||||
github.com/davecgh/go-spew/spew/spew.go Print 100.00% (1/1)
|
||||
github.com/davecgh/go-spew/spew ------------------------------- 100.00% (505/505)
|
||||
|
||||
251
vendor/github.com/dgryski/dgoogauth/googauth_test.go
сгенерированный
поставляемый
@@ -1,251 +0,0 @@
|
||||
package dgoogauth
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Test vectors via:
|
||||
// http://code.google.com/p/google-authenticator/source/browse/libpam/pam_google_authenticator_unittest.c
|
||||
// https://google-authenticator.googlecode.com/hg/libpam/totp.html
|
||||
|
||||
var codeTests = []struct {
|
||||
secret string
|
||||
value int64
|
||||
code int
|
||||
}{
|
||||
{"2SH3V3GDW7ZNMGYE", 1, 293240},
|
||||
{"2SH3V3GDW7ZNMGYE", 5, 932068},
|
||||
{"2SH3V3GDW7ZNMGYE", 10000, 50548},
|
||||
}
|
||||
|
||||
func TestCode(t *testing.T) {
|
||||
|
||||
for _, v := range codeTests {
|
||||
c := ComputeCode(v.secret, v.value)
|
||||
|
||||
if c != v.code {
|
||||
t.Errorf("computeCode(%s, %d): got %d expected %d\n", v.secret, v.value, c, v.code)
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
func TestScratchCode(t *testing.T) {
|
||||
|
||||
var cotp OTPConfig
|
||||
|
||||
cotp.ScratchCodes = []int{11112222, 22223333}
|
||||
|
||||
var scratchTests = []struct {
|
||||
code int
|
||||
result bool
|
||||
}{
|
||||
{33334444, false},
|
||||
{11112222, true},
|
||||
{11112222, false},
|
||||
{22223333, true},
|
||||
{22223333, false},
|
||||
{33334444, false},
|
||||
}
|
||||
|
||||
for _, s := range scratchTests {
|
||||
r := cotp.checkScratchCodes(s.code)
|
||||
if r != s.result {
|
||||
t.Errorf("scratchcode(%d) failed: got %t expected %t", s.code, r, s.result)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestHotpCode(t *testing.T) {
|
||||
|
||||
var cotp OTPConfig
|
||||
|
||||
// reuse our test values from above
|
||||
// perhaps create more?
|
||||
cotp.Secret = "2SH3V3GDW7ZNMGYE"
|
||||
cotp.HotpCounter = 1
|
||||
cotp.WindowSize = 3
|
||||
|
||||
var counterCodes = []struct {
|
||||
code int
|
||||
result bool
|
||||
counter int
|
||||
}{
|
||||
{ /* 1 */ 293240, true, 2}, // increments on success
|
||||
{ /* 1 */ 293240, false, 3}, // and failure
|
||||
{ /* 5 */ 932068, true, 6}, // inside of window
|
||||
{ /* 10 */ 481725, false, 7}, // outside of window
|
||||
{ /* 10 */ 481725, false, 8}, // outside of window
|
||||
{ /* 10 */ 481725, true, 11}, // now inside of window
|
||||
}
|
||||
|
||||
for i, s := range counterCodes {
|
||||
r := cotp.checkHotpCode(s.code)
|
||||
if r != s.result {
|
||||
t.Errorf("counterCode(%d) (step %d) failed: got %t expected %t", s.code, i, r, s.result)
|
||||
}
|
||||
if cotp.HotpCounter != s.counter {
|
||||
t.Errorf("hotpCounter incremented poorly: got %d expected %d", cotp.HotpCounter, s.counter)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestTotpCode(t *testing.T) {
|
||||
|
||||
var cotp OTPConfig
|
||||
|
||||
// reuse our test values from above
|
||||
cotp.Secret = "2SH3V3GDW7ZNMGYE"
|
||||
cotp.WindowSize = 5
|
||||
|
||||
var windowTest = []struct {
|
||||
code int
|
||||
t0 int
|
||||
result bool
|
||||
}{
|
||||
{50548, 9997, false},
|
||||
{50548, 9998, true},
|
||||
{50548, 9999, true},
|
||||
{50548, 10000, true},
|
||||
{50548, 10001, true},
|
||||
{50548, 10002, true},
|
||||
{50548, 10003, false},
|
||||
}
|
||||
|
||||
for i, s := range windowTest {
|
||||
r := cotp.checkTotpCode(s.t0, s.code)
|
||||
if r != s.result {
|
||||
t.Errorf("counterCode(%d) (step %d) failed: got %t expected %t", s.code, i, r, s.result)
|
||||
}
|
||||
}
|
||||
|
||||
cotp.DisallowReuse = make([]int, 0)
|
||||
var noreuseTest = []struct {
|
||||
code int
|
||||
t0 int
|
||||
result bool
|
||||
disallowed []int
|
||||
}{
|
||||
{50548 /* 10000 */, 9997, false, []int{}},
|
||||
{50548 /* 10000 */, 9998, true, []int{10000}},
|
||||
{50548 /* 10000 */, 9999, false, []int{10000}},
|
||||
{478726 /* 10001 */, 10001, true, []int{10000, 10001}},
|
||||
{646986 /* 10002 */, 10002, true, []int{10000, 10001, 10002}},
|
||||
{842639 /* 10003 */, 10003, true, []int{10001, 10002, 10003}},
|
||||
}
|
||||
|
||||
for i, s := range noreuseTest {
|
||||
r := cotp.checkTotpCode(s.t0, s.code)
|
||||
if r != s.result {
|
||||
t.Errorf("timeCode(%d) (step %d) failed: got %t expected %t", s.code, i, r, s.result)
|
||||
}
|
||||
if len(cotp.DisallowReuse) != len(s.disallowed) {
|
||||
t.Errorf("timeCode(%d) (step %d) failed: disallowReuse len mismatch: got %d expected %d", s.code, i, len(cotp.DisallowReuse), len(s.disallowed))
|
||||
} else {
|
||||
same := true
|
||||
for j := range s.disallowed {
|
||||
if s.disallowed[j] != cotp.DisallowReuse[j] {
|
||||
same = false
|
||||
}
|
||||
}
|
||||
if !same {
|
||||
t.Errorf("timeCode(%d) (step %d) failed: disallowReused: got %v expected %v", s.code, i, cotp.DisallowReuse, s.disallowed)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthenticate(t *testing.T) {
|
||||
|
||||
otpconf := &OTPConfig{
|
||||
Secret: "2SH3V3GDW7ZNMGYE",
|
||||
WindowSize: 3,
|
||||
HotpCounter: 1,
|
||||
ScratchCodes: []int{11112222, 22223333},
|
||||
}
|
||||
|
||||
type attempt struct {
|
||||
code string
|
||||
result bool
|
||||
}
|
||||
|
||||
var attempts = []attempt{
|
||||
{"foobar", false}, // not digits
|
||||
{"1fooba", false}, // not valid number
|
||||
{"1111111", false}, // bad length
|
||||
{ /* 1 */ "293240", true}, // hopt increments on success
|
||||
{ /* 1 */ "293240", false}, // hopt failure
|
||||
{"33334444", false}, // scratch
|
||||
{"11112222", true},
|
||||
{"11112222", false},
|
||||
}
|
||||
|
||||
for _, a := range attempts {
|
||||
r, _ := otpconf.Authenticate(a.code)
|
||||
if r != a.result {
|
||||
t.Errorf("bad result from code=%s: got %t expected %t\n", a.code, r, a.result)
|
||||
}
|
||||
}
|
||||
|
||||
// let's check some time-based codes
|
||||
otpconf.HotpCounter = 0
|
||||
// I haven't mocked the clock, so we'll just compute one
|
||||
var t0 int64
|
||||
if otpconf.UTC {
|
||||
t0 = int64(time.Now().UTC().Unix() / 30)
|
||||
} else {
|
||||
t0 = int64(time.Now().Unix() / 30)
|
||||
}
|
||||
c := ComputeCode(otpconf.Secret, t0)
|
||||
code := fmt.Sprintf("%06d", c)
|
||||
|
||||
attempts = []attempt{
|
||||
{code + "1", false},
|
||||
{code, true},
|
||||
}
|
||||
|
||||
for _, a := range attempts {
|
||||
r, _ := otpconf.Authenticate(a.code)
|
||||
if r != a.result {
|
||||
t.Errorf("bad result from code=%s: got %t expected %t\n", a.code, r, a.result)
|
||||
}
|
||||
|
||||
otpconf.UTC = true
|
||||
r, _ = otpconf.Authenticate(a.code)
|
||||
if r != a.result {
|
||||
t.Errorf("bad result from code=%s: got %t expected %t\n", a.code, r, a.result)
|
||||
}
|
||||
otpconf.UTC = false
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func TestProvisionURI(t *testing.T) {
|
||||
otpconf := OTPConfig{
|
||||
Secret: "x",
|
||||
}
|
||||
|
||||
cases := []struct {
|
||||
user, iss string
|
||||
hotp bool
|
||||
out string
|
||||
}{
|
||||
{"test", "", false, "otpauth://totp/test?secret=x"},
|
||||
{"test", "", true, "otpauth://hotp/test?counter=1&secret=x"},
|
||||
{"test", "Company", true, "otpauth://hotp/Company:test?counter=1&issuer=Company&secret=x"},
|
||||
{"test", "Company", false, "otpauth://totp/Company:test?issuer=Company&secret=x"},
|
||||
}
|
||||
|
||||
for i, c := range cases {
|
||||
otpconf.HotpCounter = 0
|
||||
if c.hotp {
|
||||
otpconf.HotpCounter = 1
|
||||
}
|
||||
got := otpconf.ProvisionURIWithIssuer(c.user, c.iss)
|
||||
if got != c.out {
|
||||
t.Errorf("%d: want %q, got %q", i, c.out, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
233
vendor/github.com/dimchansky/utfbom/utfbom_test.go
сгенерированный
поставляемый
@@ -1,233 +0,0 @@
|
||||
package utfbom
|
||||
|
||||
import (
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"reflect"
|
||||
"testing"
|
||||
"testing/iotest"
|
||||
"time"
|
||||
)
|
||||
|
||||
var testCases = []struct {
|
||||
name string
|
||||
input []byte
|
||||
inputError error
|
||||
encoding Encoding
|
||||
output []byte
|
||||
}{
|
||||
{"1", []byte{}, nil, Unknown, []byte{}},
|
||||
{"2", []byte("hello"), nil, Unknown, []byte("hello")},
|
||||
{"3", []byte("\xEF\xBB\xBF"), nil, UTF8, []byte{}},
|
||||
{"4", []byte("\xEF\xBB\xBFhello"), nil, UTF8, []byte("hello")},
|
||||
{"5", []byte("\xFE\xFF"), nil, UTF16BigEndian, []byte{}},
|
||||
{"6", []byte("\xFF\xFE"), nil, UTF16LittleEndian, []byte{}},
|
||||
{"7", []byte("\x00\x00\xFE\xFF"), nil, UTF32BigEndian, []byte{}},
|
||||
{"8", []byte("\xFF\xFE\x00\x00"), nil, UTF32LittleEndian, []byte{}},
|
||||
{"5", []byte("\xFE\xFF\x00\x68\x00\x65\x00\x6C\x00\x6C\x00\x6F"), nil,
|
||||
UTF16BigEndian, []byte{0x00, 0x68, 0x00, 0x65, 0x00, 0x6C, 0x00, 0x6C, 0x00, 0x6F}},
|
||||
{"6", []byte("\xFF\xFE\x68\x00\x65\x00\x6C\x00\x6C\x00\x6F\x00"), nil,
|
||||
UTF16LittleEndian, []byte{0x68, 0x00, 0x65, 0x00, 0x6C, 0x00, 0x6C, 0x00, 0x6F, 0x00}},
|
||||
{"7", []byte("\x00\x00\xFE\xFF\x00\x00\x00\x68\x00\x00\x00\x65\x00\x00\x00\x6C\x00\x00\x00\x6C\x00\x00\x00\x6F"), nil,
|
||||
UTF32BigEndian,
|
||||
[]byte{0x00, 0x00, 0x00, 0x68, 0x00, 0x00, 0x00, 0x65, 0x00, 0x00, 0x00, 0x6C, 0x00, 0x00, 0x00, 0x6C, 0x00, 0x00, 0x00, 0x6F}},
|
||||
{"8", []byte("\xFF\xFE\x00\x00\x68\x00\x00\x00\x65\x00\x00\x00\x6C\x00\x00\x00\x6C\x00\x00\x00\x6F\x00\x00\x00"), nil,
|
||||
UTF32LittleEndian,
|
||||
[]byte{0x68, 0x00, 0x00, 0x00, 0x65, 0x00, 0x00, 0x00, 0x6C, 0x00, 0x00, 0x00, 0x6C, 0x00, 0x00, 0x00, 0x6F, 0x00, 0x00, 0x00}},
|
||||
{"9", []byte("\xEF"), nil, Unknown, []byte("\xEF")},
|
||||
{"10", []byte("\xEF\xBB"), nil, Unknown, []byte("\xEF\xBB")},
|
||||
{"11", []byte("\xEF\xBB\xBF"), io.ErrClosedPipe, UTF8, []byte{}},
|
||||
{"12", []byte("\xFE\xFF"), io.ErrClosedPipe, Unknown, []byte("\xFE\xFF")},
|
||||
{"13", []byte("\xFE"), io.ErrClosedPipe, Unknown, []byte("\xFE")},
|
||||
{"14", []byte("\xFF\xFE"), io.ErrClosedPipe, Unknown, []byte("\xFF\xFE")},
|
||||
{"15", []byte("\x00\x00\xFE\xFF"), io.ErrClosedPipe, UTF32BigEndian, []byte{}},
|
||||
{"16", []byte("\x00\x00\xFE"), io.ErrClosedPipe, Unknown, []byte{0x00, 0x00, 0xFE}},
|
||||
{"17", []byte("\x00\x00"), io.ErrClosedPipe, Unknown, []byte{0x00, 0x00}},
|
||||
{"18", []byte("\x00"), io.ErrClosedPipe, Unknown, []byte{0x00}},
|
||||
{"19", []byte("\xFF\xFE\x00\x00"), io.ErrClosedPipe, UTF32LittleEndian, []byte{}},
|
||||
{"20", []byte("\xFF\xFE\x00"), io.ErrClosedPipe, Unknown, []byte{0xFF, 0xFE, 0x00}},
|
||||
{"21", []byte("\xFF\xFE"), io.ErrClosedPipe, Unknown, []byte{0xFF, 0xFE}},
|
||||
{"22", []byte("\xFF"), io.ErrClosedPipe, Unknown, []byte{0xFF}},
|
||||
{"23", []byte("\x68\x65"), nil, Unknown, []byte{0x68, 0x65}},
|
||||
}
|
||||
|
||||
type sliceReader struct {
|
||||
input []byte
|
||||
inputError error
|
||||
}
|
||||
|
||||
func (r *sliceReader) Read(p []byte) (n int, err error) {
|
||||
if len(p) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
if err = r.getError(); err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
n = copy(p, r.input)
|
||||
r.input = r.input[n:]
|
||||
err = r.getError()
|
||||
return
|
||||
}
|
||||
|
||||
func (r *sliceReader) getError() (err error) {
|
||||
if len(r.input) == 0 {
|
||||
if r.inputError == nil {
|
||||
err = io.EOF
|
||||
} else {
|
||||
err = r.inputError
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
var readMakers = []struct {
|
||||
name string
|
||||
fn func(io.Reader) io.Reader
|
||||
}{
|
||||
{"full", func(r io.Reader) io.Reader { return r }},
|
||||
{"byte", iotest.OneByteReader},
|
||||
}
|
||||
|
||||
func TestSkip(t *testing.T) {
|
||||
for _, tc := range testCases {
|
||||
for _, readMaker := range readMakers {
|
||||
r := readMaker.fn(&sliceReader{tc.input, tc.inputError})
|
||||
|
||||
sr, enc := Skip(r)
|
||||
if enc != tc.encoding {
|
||||
t.Fatalf("test %v reader=%s: expected encoding %v, but got %v", tc.name, readMaker.name, tc.encoding, enc)
|
||||
}
|
||||
|
||||
output, err := ioutil.ReadAll(sr)
|
||||
if !reflect.DeepEqual(output, tc.output) {
|
||||
t.Fatalf("test %v reader=%s: expected to read %+#v, but got %+#v", tc.name, readMaker.name, tc.output, output)
|
||||
}
|
||||
if err != tc.inputError {
|
||||
t.Fatalf("test %v reader=%s: expected to get %+#v error, but got %+#v", tc.name, readMaker.name, tc.inputError, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSkipSkip(t *testing.T) {
|
||||
for _, tc := range testCases {
|
||||
for _, readMaker := range readMakers {
|
||||
r := readMaker.fn(&sliceReader{tc.input, tc.inputError})
|
||||
|
||||
sr0, _ := Skip(r)
|
||||
sr, enc := Skip(sr0)
|
||||
if enc != Unknown {
|
||||
t.Fatalf("test %v reader=%s: expected encoding %v, but got %v", tc.name, readMaker.name, Unknown, enc)
|
||||
}
|
||||
|
||||
output, err := ioutil.ReadAll(sr)
|
||||
if !reflect.DeepEqual(output, tc.output) {
|
||||
t.Fatalf("test %v reader=%s: expected to read %+#v, but got %+#v", tc.name, readMaker.name, tc.output, output)
|
||||
}
|
||||
if err != tc.inputError {
|
||||
t.Fatalf("test %v reader=%s: expected to get %+#v error, but got %+#v", tc.name, readMaker.name, tc.inputError, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSkipOnly(t *testing.T) {
|
||||
for _, tc := range testCases {
|
||||
for _, readMaker := range readMakers {
|
||||
r := readMaker.fn(&sliceReader{tc.input, tc.inputError})
|
||||
|
||||
sr := SkipOnly(r)
|
||||
|
||||
output, err := ioutil.ReadAll(sr)
|
||||
if !reflect.DeepEqual(output, tc.output) {
|
||||
t.Fatalf("test %v reader=%s: expected to read %+#v, but got %+#v", tc.name, readMaker.name, tc.output, output)
|
||||
}
|
||||
if err != tc.inputError {
|
||||
t.Fatalf("test %v reader=%s: expected to get %+#v error, but got %+#v", tc.name, readMaker.name, tc.inputError, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type zeroReader struct{}
|
||||
|
||||
func (zeroReader) Read(p []byte) (int, error) {
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
type readerEncoding struct {
|
||||
Rd *Reader
|
||||
Enc Encoding
|
||||
}
|
||||
|
||||
func TestSkipZeroReader(t *testing.T) {
|
||||
var z zeroReader
|
||||
|
||||
c := make(chan readerEncoding)
|
||||
go func() {
|
||||
r, enc := Skip(z)
|
||||
c <- readerEncoding{r, enc}
|
||||
}()
|
||||
|
||||
select {
|
||||
case re := <-c:
|
||||
if re.Enc != Unknown {
|
||||
t.Error("Unknown encoding expected")
|
||||
} else {
|
||||
var b [1]byte
|
||||
n, err := re.Rd.Read(b[:])
|
||||
if n != 0 {
|
||||
t.Error("unexpected bytes count:", n)
|
||||
}
|
||||
if err != io.ErrNoProgress {
|
||||
t.Error("unexpected error:", err)
|
||||
}
|
||||
}
|
||||
case <-time.After(time.Second):
|
||||
t.Error("test timed out (endless loop in Skip?)")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSkipOnlyZeroReader(t *testing.T) {
|
||||
var z zeroReader
|
||||
|
||||
c := make(chan *Reader)
|
||||
go func() {
|
||||
r := SkipOnly(z)
|
||||
c <- r
|
||||
}()
|
||||
|
||||
select {
|
||||
case r := <-c:
|
||||
var b [1]byte
|
||||
n, err := r.Read(b[:])
|
||||
if n != 0 {
|
||||
t.Error("unexpected bytes count:", n)
|
||||
}
|
||||
if err != io.ErrNoProgress {
|
||||
t.Error("unexpected error:", err)
|
||||
}
|
||||
case <-time.After(time.Second):
|
||||
t.Error("test timed out (endless loop in Skip?)")
|
||||
}
|
||||
}
|
||||
|
||||
func TestReader_ReadEmpty(t *testing.T) {
|
||||
for _, tc := range testCases {
|
||||
for _, readMaker := range readMakers {
|
||||
r := readMaker.fn(&sliceReader{tc.input, tc.inputError})
|
||||
|
||||
sr := SkipOnly(r)
|
||||
|
||||
n, err := sr.Read(nil)
|
||||
if n != 0 {
|
||||
t.Fatalf("test %v reader=%s: expected to read zero bytes, but got %v", tc.name, readMaker.name, n)
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatalf("test %v reader=%s: expected to get <nil> error, but got %+#v", tc.name, readMaker.name, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
16
vendor/github.com/disintegration/imaging/.travis.yml
сгенерированный
поставляемый
@@ -1,17 +1,13 @@
|
||||
language: go
|
||||
|
||||
sudo: false
|
||||
|
||||
go:
|
||||
- 1.2
|
||||
- 1.7
|
||||
- 1.8
|
||||
- 1.9
|
||||
- "1.7.x"
|
||||
- "1.8.x"
|
||||
- "1.9.x"
|
||||
- "1.10.x"
|
||||
|
||||
before_install:
|
||||
- go get golang.org/x/tools/cmd/cover
|
||||
- go get github.com/mattn/goveralls
|
||||
|
||||
script:
|
||||
- go test -v -covermode=count -coverprofile=coverage.out
|
||||
- $HOME/gopath/bin/goveralls -service=travis-ci -coverprofile=coverage.out
|
||||
- go test -v -race -cover
|
||||
- $GOPATH/bin/goveralls -service=travis-ci
|
||||
|
||||
2
vendor/github.com/disintegration/imaging/LICENSE
сгенерированный
поставляемый
@@ -1,6 +1,6 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2012-2017 Grigory Dryapak
|
||||
Copyright (c) 2012-2018 Grigory Dryapak
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
|
||||
63
vendor/github.com/disintegration/imaging/README.md
сгенерированный
поставляемый
@@ -2,19 +2,16 @@
|
||||
|
||||
[](https://godoc.org/github.com/disintegration/imaging)
|
||||
[](https://travis-ci.org/disintegration/imaging)
|
||||
[](https://coveralls.io/github/disintegration/imaging?branch=master)
|
||||
[](https://coveralls.io/github/disintegration/imaging?branch=master)
|
||||
[](https://goreportcard.com/report/github.com/disintegration/imaging)
|
||||
|
||||
Package imaging provides basic image manipulation functions (resize, rotate, flip, crop, etc.).
|
||||
This package is based on the standard Go image package and works best along with it.
|
||||
Package imaging provides basic image processing functions (resize, rotate, crop, brightness/contrast adjustments, etc.).
|
||||
|
||||
Image manipulation functions provided by the package take any image type
|
||||
that implements `image.Image` interface as an input, and return a new image of
|
||||
`*image.NRGBA` type (32bit RGBA colors, not premultiplied by alpha).
|
||||
All the image processing functions provided by the package accept any image type that implements `image.Image` interface
|
||||
as an input, and return a new image of `*image.NRGBA` type (32bit RGBA colors, not premultiplied by alpha).
|
||||
|
||||
## Installation
|
||||
|
||||
Imaging requires Go version 1.2 or greater.
|
||||
|
||||
go get -u github.com/disintegration/imaging
|
||||
|
||||
## Documentation
|
||||
@@ -46,19 +43,19 @@ Imaging supports image resizing using various resampling filters. The most notab
|
||||
- `Box` - Simple and fast averaging filter appropriate for downscaling. When upscaling it's similar to NearestNeighbor.
|
||||
- `Linear` - Bilinear filter, smooth and reasonably fast.
|
||||
- `MitchellNetravali` - А smooth bicubic filter.
|
||||
- `CatmullRom` - A sharp bicubic filter.
|
||||
- `CatmullRom` - A sharp bicubic filter.
|
||||
- `Gaussian` - Blurring filter that uses gaussian function, useful for noise removal.
|
||||
- `Lanczos` - High-quality resampling filter for photographic images yielding sharp results, but it's slower than cubic filters.
|
||||
- `Lanczos` - High-quality resampling filter for photographic images yielding sharp results, slower than cubic filters.
|
||||
|
||||
The full list of supported filters: NearestNeighbor, Box, Linear, Hermite, MitchellNetravali, CatmullRom, BSpline, Gaussian, Lanczos, Hann, Hamming, Blackman, Bartlett, Welch, Cosine. Custom filters can be created using ResampleFilter struct.
|
||||
|
||||
**Resampling filters comparison**
|
||||
|
||||
The original image.
|
||||
Original image:
|
||||
|
||||

|
||||

|
||||
|
||||
The same image resized from 512x512px to 128x128px using different resampling filters.
|
||||
The same image resized from 600x400px to 150x100px using different resampling filters.
|
||||
From faster (lower quality) to slower (higher quality):
|
||||
|
||||
Filter | Resize result
|
||||
@@ -79,7 +76,7 @@ Sigma parameter allows to control the strength of the blurring effect.
|
||||
|
||||
Original image | Sigma = 0.5 | Sigma = 1.5
|
||||
-----------------------------------|----------------------------------------|---------------------------------------
|
||||
 |  | 
|
||||
 |  | 
|
||||
|
||||
### Sharpening
|
||||
|
||||
@@ -91,7 +88,7 @@ dstImage := imaging.Sharpen(srcImage, 0.5)
|
||||
|
||||
Original image | Sigma = 0.5 | Sigma = 1.5
|
||||
-----------------------------------|-------------------------------------------|------------------------------------------
|
||||
 |  | 
|
||||
 |  | 
|
||||
|
||||
### Gamma correction
|
||||
|
||||
@@ -101,7 +98,7 @@ dstImage := imaging.AdjustGamma(srcImage, 0.75)
|
||||
|
||||
Original image | Gamma = 0.75 | Gamma = 1.25
|
||||
-----------------------------------|------------------------------------------|-----------------------------------------
|
||||
 |  | 
|
||||
 |  | 
|
||||
|
||||
### Contrast adjustment
|
||||
|
||||
@@ -109,9 +106,9 @@ Original image | Gamma = 0.75 |
|
||||
dstImage := imaging.AdjustContrast(srcImage, 20)
|
||||
```
|
||||
|
||||
Original image | Contrast = 10 | Contrast = -10
|
||||
Original image | Contrast = 15 | Contrast = -15
|
||||
-----------------------------------|--------------------------------------------|-------------------------------------------
|
||||
 |  | 
|
||||
 |  | 
|
||||
|
||||
### Brightness adjustment
|
||||
|
||||
@@ -121,7 +118,7 @@ dstImage := imaging.AdjustBrightness(srcImage, 20)
|
||||
|
||||
Original image | Brightness = 10 | Brightness = -10
|
||||
-----------------------------------|----------------------------------------------|---------------------------------------------
|
||||
 |  | 
|
||||
 |  | 
|
||||
|
||||
## Example code
|
||||
|
||||
@@ -137,20 +134,20 @@ import (
|
||||
)
|
||||
|
||||
func main() {
|
||||
// Open the test image.
|
||||
src, err := imaging.Open("testdata/lena_512.png")
|
||||
// Open a test image.
|
||||
src, err := imaging.Open("testdata/flowers.png")
|
||||
if err != nil {
|
||||
log.Fatalf("Open failed: %v", err)
|
||||
log.Fatalf("failed to open image: %v", err)
|
||||
}
|
||||
|
||||
// Crop the original image to 350x350px size using the center anchor.
|
||||
src = imaging.CropAnchor(src, 350, 350, imaging.Center)
|
||||
// Crop the original image to 300x300px size using the center anchor.
|
||||
src = imaging.CropAnchor(src, 300, 300, imaging.Center)
|
||||
|
||||
// Resize the cropped image to width = 256px preserving the aspect ratio.
|
||||
src = imaging.Resize(src, 256, 0, imaging.Lanczos)
|
||||
// Resize the cropped image to width = 200px preserving the aspect ratio.
|
||||
src = imaging.Resize(src, 200, 0, imaging.Lanczos)
|
||||
|
||||
// Create a blurred version of the image.
|
||||
img1 := imaging.Blur(src, 2)
|
||||
img1 := imaging.Blur(src, 5)
|
||||
|
||||
// Create a grayscale version of the image with higher contrast and sharpness.
|
||||
img2 := imaging.Grayscale(src)
|
||||
@@ -172,16 +169,16 @@ func main() {
|
||||
)
|
||||
|
||||
// Create a new image and paste the four produced images into it.
|
||||
dst := imaging.New(512, 512, color.NRGBA{0, 0, 0, 0})
|
||||
dst := imaging.New(400, 400, color.NRGBA{0, 0, 0, 0})
|
||||
dst = imaging.Paste(dst, img1, image.Pt(0, 0))
|
||||
dst = imaging.Paste(dst, img2, image.Pt(0, 256))
|
||||
dst = imaging.Paste(dst, img3, image.Pt(256, 0))
|
||||
dst = imaging.Paste(dst, img4, image.Pt(256, 256))
|
||||
dst = imaging.Paste(dst, img2, image.Pt(0, 200))
|
||||
dst = imaging.Paste(dst, img3, image.Pt(200, 0))
|
||||
dst = imaging.Paste(dst, img4, image.Pt(200, 200))
|
||||
|
||||
// Save the resulting image using JPEG format.
|
||||
// Save the resulting image as JPEG.
|
||||
err = imaging.Save(dst, "testdata/out_example.jpg")
|
||||
if err != nil {
|
||||
log.Fatalf("Save failed: %v", err)
|
||||
log.Fatalf("failed to save image: %v", err)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
260
vendor/github.com/disintegration/imaging/adjust.go
сгенерированный
поставляемый
@@ -6,52 +6,97 @@ import (
|
||||
"math"
|
||||
)
|
||||
|
||||
// AdjustFunc applies the fn function to each pixel of the img image and returns the adjusted image.
|
||||
//
|
||||
// Example:
|
||||
//
|
||||
// dstImage = imaging.AdjustFunc(
|
||||
// srcImage,
|
||||
// func(c color.NRGBA) color.NRGBA {
|
||||
// // shift the red channel by 16
|
||||
// r := int(c.R) + 16
|
||||
// if r > 255 {
|
||||
// r = 255
|
||||
// }
|
||||
// return color.NRGBA{uint8(r), c.G, c.B, c.A}
|
||||
// }
|
||||
// )
|
||||
//
|
||||
func AdjustFunc(img image.Image, fn func(c color.NRGBA) color.NRGBA) *image.NRGBA {
|
||||
src := toNRGBA(img)
|
||||
width := src.Bounds().Max.X
|
||||
height := src.Bounds().Max.Y
|
||||
dst := image.NewNRGBA(image.Rect(0, 0, width, height))
|
||||
|
||||
parallel(height, func(partStart, partEnd int) {
|
||||
for y := partStart; y < partEnd; y++ {
|
||||
for x := 0; x < width; x++ {
|
||||
i := y*src.Stride + x*4
|
||||
j := y*dst.Stride + x*4
|
||||
|
||||
r := src.Pix[i+0]
|
||||
g := src.Pix[i+1]
|
||||
b := src.Pix[i+2]
|
||||
a := src.Pix[i+3]
|
||||
|
||||
c := fn(color.NRGBA{r, g, b, a})
|
||||
|
||||
dst.Pix[j+0] = c.R
|
||||
dst.Pix[j+1] = c.G
|
||||
dst.Pix[j+2] = c.B
|
||||
dst.Pix[j+3] = c.A
|
||||
// Grayscale produces a grayscale version of the image.
|
||||
func Grayscale(img image.Image) *image.NRGBA {
|
||||
src := newScanner(img)
|
||||
dst := image.NewNRGBA(image.Rect(0, 0, src.w, src.h))
|
||||
parallel(0, src.h, func(ys <-chan int) {
|
||||
for y := range ys {
|
||||
i := y * dst.Stride
|
||||
src.scan(0, y, src.w, y+1, dst.Pix[i:i+src.w*4])
|
||||
for x := 0; x < src.w; x++ {
|
||||
r := dst.Pix[i+0]
|
||||
g := dst.Pix[i+1]
|
||||
b := dst.Pix[i+2]
|
||||
f := 0.299*float64(r) + 0.587*float64(g) + 0.114*float64(b)
|
||||
y := uint8(f + 0.5)
|
||||
dst.Pix[i+0] = y
|
||||
dst.Pix[i+1] = y
|
||||
dst.Pix[i+2] = y
|
||||
i += 4
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
return dst
|
||||
}
|
||||
|
||||
// Invert produces an inverted (negated) version of the image.
|
||||
func Invert(img image.Image) *image.NRGBA {
|
||||
src := newScanner(img)
|
||||
dst := image.NewNRGBA(image.Rect(0, 0, src.w, src.h))
|
||||
parallel(0, src.h, func(ys <-chan int) {
|
||||
for y := range ys {
|
||||
i := y * dst.Stride
|
||||
src.scan(0, y, src.w, y+1, dst.Pix[i:i+src.w*4])
|
||||
for x := 0; x < src.w; x++ {
|
||||
dst.Pix[i+0] = 255 - dst.Pix[i+0]
|
||||
dst.Pix[i+1] = 255 - dst.Pix[i+1]
|
||||
dst.Pix[i+2] = 255 - dst.Pix[i+2]
|
||||
i += 4
|
||||
}
|
||||
}
|
||||
})
|
||||
return dst
|
||||
}
|
||||
|
||||
// AdjustContrast changes the contrast of the image using the percentage parameter and returns the adjusted image.
|
||||
// The percentage must be in range (-100, 100). The percentage = 0 gives the original image.
|
||||
// The percentage = -100 gives solid gray image.
|
||||
//
|
||||
// Examples:
|
||||
//
|
||||
// dstImage = imaging.AdjustContrast(srcImage, -10) // decrease image contrast by 10%
|
||||
// dstImage = imaging.AdjustContrast(srcImage, 20) // increase image contrast by 20%
|
||||
//
|
||||
func AdjustContrast(img image.Image, percentage float64) *image.NRGBA {
|
||||
percentage = math.Min(math.Max(percentage, -100.0), 100.0)
|
||||
lut := make([]uint8, 256)
|
||||
|
||||
v := (100.0 + percentage) / 100.0
|
||||
for i := 0; i < 256; i++ {
|
||||
if 0 <= v && v <= 1 {
|
||||
lut[i] = clamp((0.5 + (float64(i)/255.0-0.5)*v) * 255.0)
|
||||
} else if 1 < v && v < 2 {
|
||||
lut[i] = clamp((0.5 + (float64(i)/255.0-0.5)*(1/(2.0-v))) * 255.0)
|
||||
} else {
|
||||
lut[i] = uint8(float64(i)/255.0+0.5) * 255
|
||||
}
|
||||
}
|
||||
|
||||
return adjustLUT(img, lut)
|
||||
}
|
||||
|
||||
// AdjustBrightness changes the brightness of the image using the percentage parameter and returns the adjusted image.
|
||||
// The percentage must be in range (-100, 100). The percentage = 0 gives the original image.
|
||||
// The percentage = -100 gives solid black image. The percentage = 100 gives solid white image.
|
||||
//
|
||||
// Examples:
|
||||
//
|
||||
// dstImage = imaging.AdjustBrightness(srcImage, -15) // decrease image brightness by 15%
|
||||
// dstImage = imaging.AdjustBrightness(srcImage, 10) // increase image brightness by 10%
|
||||
//
|
||||
func AdjustBrightness(img image.Image, percentage float64) *image.NRGBA {
|
||||
percentage = math.Min(math.Max(percentage, -100.0), 100.0)
|
||||
lut := make([]uint8, 256)
|
||||
|
||||
shift := 255.0 * percentage / 100.0
|
||||
for i := 0; i < 256; i++ {
|
||||
lut[i] = clamp(float64(i) + shift)
|
||||
}
|
||||
|
||||
return adjustLUT(img, lut)
|
||||
}
|
||||
|
||||
// AdjustGamma performs a gamma correction on the image and returns the adjusted image.
|
||||
// Gamma parameter must be positive. Gamma = 1.0 gives the original image.
|
||||
// Gamma less than 1.0 darkens the image and gamma greater than 1.0 lightens it.
|
||||
@@ -68,15 +113,7 @@ func AdjustGamma(img image.Image, gamma float64) *image.NRGBA {
|
||||
lut[i] = clamp(math.Pow(float64(i)/255.0, e) * 255.0)
|
||||
}
|
||||
|
||||
fn := func(c color.NRGBA) color.NRGBA {
|
||||
return color.NRGBA{lut[c.R], lut[c.G], lut[c.B], c.A}
|
||||
}
|
||||
|
||||
return AdjustFunc(img, fn)
|
||||
}
|
||||
|
||||
func sigmoid(a, b, x float64) float64 {
|
||||
return 1 / (1 + math.Exp(b*(a-x)))
|
||||
return adjustLUT(img, lut)
|
||||
}
|
||||
|
||||
// AdjustSigmoid changes the contrast of the image using a sigmoidal function and returns the adjusted image.
|
||||
@@ -118,83 +155,68 @@ func AdjustSigmoid(img image.Image, midpoint, factor float64) *image.NRGBA {
|
||||
}
|
||||
}
|
||||
|
||||
fn := func(c color.NRGBA) color.NRGBA {
|
||||
return color.NRGBA{lut[c.R], lut[c.G], lut[c.B], c.A}
|
||||
}
|
||||
|
||||
return AdjustFunc(img, fn)
|
||||
return adjustLUT(img, lut)
|
||||
}
|
||||
|
||||
// AdjustContrast changes the contrast of the image using the percentage parameter and returns the adjusted image.
|
||||
// The percentage must be in range (-100, 100). The percentage = 0 gives the original image.
|
||||
// The percentage = -100 gives solid grey image.
|
||||
//
|
||||
// Examples:
|
||||
//
|
||||
// dstImage = imaging.AdjustContrast(srcImage, -10) // decrease image contrast by 10%
|
||||
// dstImage = imaging.AdjustContrast(srcImage, 20) // increase image contrast by 20%
|
||||
//
|
||||
func AdjustContrast(img image.Image, percentage float64) *image.NRGBA {
|
||||
percentage = math.Min(math.Max(percentage, -100.0), 100.0)
|
||||
lut := make([]uint8, 256)
|
||||
func sigmoid(a, b, x float64) float64 {
|
||||
return 1 / (1 + math.Exp(b*(a-x)))
|
||||
}
|
||||
|
||||
v := (100.0 + percentage) / 100.0
|
||||
for i := 0; i < 256; i++ {
|
||||
if 0 <= v && v <= 1 {
|
||||
lut[i] = clamp((0.5 + (float64(i)/255.0-0.5)*v) * 255.0)
|
||||
} else if 1 < v && v < 2 {
|
||||
lut[i] = clamp((0.5 + (float64(i)/255.0-0.5)*(1/(2.0-v))) * 255.0)
|
||||
} else {
|
||||
lut[i] = uint8(float64(i)/255.0+0.5) * 255
|
||||
// adjustLUT applies the given lookup table to the colors of the image.
|
||||
func adjustLUT(img image.Image, lut []uint8) *image.NRGBA {
|
||||
src := newScanner(img)
|
||||
dst := image.NewNRGBA(image.Rect(0, 0, src.w, src.h))
|
||||
parallel(0, src.h, func(ys <-chan int) {
|
||||
for y := range ys {
|
||||
i := y * dst.Stride
|
||||
src.scan(0, y, src.w, y+1, dst.Pix[i:i+src.w*4])
|
||||
for x := 0; x < src.w; x++ {
|
||||
dst.Pix[i+0] = lut[dst.Pix[i+0]]
|
||||
dst.Pix[i+1] = lut[dst.Pix[i+1]]
|
||||
dst.Pix[i+2] = lut[dst.Pix[i+2]]
|
||||
i += 4
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn := func(c color.NRGBA) color.NRGBA {
|
||||
return color.NRGBA{lut[c.R], lut[c.G], lut[c.B], c.A}
|
||||
}
|
||||
|
||||
return AdjustFunc(img, fn)
|
||||
})
|
||||
return dst
|
||||
}
|
||||
|
||||
// AdjustBrightness changes the brightness of the image using the percentage parameter and returns the adjusted image.
|
||||
// The percentage must be in range (-100, 100). The percentage = 0 gives the original image.
|
||||
// The percentage = -100 gives solid black image. The percentage = 100 gives solid white image.
|
||||
// AdjustFunc applies the fn function to each pixel of the img image and returns the adjusted image.
|
||||
//
|
||||
// Examples:
|
||||
// Example:
|
||||
//
|
||||
// dstImage = imaging.AdjustBrightness(srcImage, -15) // decrease image brightness by 15%
|
||||
// dstImage = imaging.AdjustBrightness(srcImage, 10) // increase image brightness by 10%
|
||||
// dstImage = imaging.AdjustFunc(
|
||||
// srcImage,
|
||||
// func(c color.NRGBA) color.NRGBA {
|
||||
// // shift the red channel by 16
|
||||
// r := int(c.R) + 16
|
||||
// if r > 255 {
|
||||
// r = 255
|
||||
// }
|
||||
// return color.NRGBA{uint8(r), c.G, c.B, c.A}
|
||||
// }
|
||||
// )
|
||||
//
|
||||
func AdjustBrightness(img image.Image, percentage float64) *image.NRGBA {
|
||||
percentage = math.Min(math.Max(percentage, -100.0), 100.0)
|
||||
lut := make([]uint8, 256)
|
||||
|
||||
shift := 255.0 * percentage / 100.0
|
||||
for i := 0; i < 256; i++ {
|
||||
lut[i] = clamp(float64(i) + shift)
|
||||
}
|
||||
|
||||
fn := func(c color.NRGBA) color.NRGBA {
|
||||
return color.NRGBA{lut[c.R], lut[c.G], lut[c.B], c.A}
|
||||
}
|
||||
|
||||
return AdjustFunc(img, fn)
|
||||
}
|
||||
|
||||
// Grayscale produces grayscale version of the image.
|
||||
func Grayscale(img image.Image) *image.NRGBA {
|
||||
fn := func(c color.NRGBA) color.NRGBA {
|
||||
f := 0.299*float64(c.R) + 0.587*float64(c.G) + 0.114*float64(c.B)
|
||||
y := uint8(f + 0.5)
|
||||
return color.NRGBA{y, y, y, c.A}
|
||||
}
|
||||
return AdjustFunc(img, fn)
|
||||
}
|
||||
|
||||
// Invert produces inverted (negated) version of the image.
|
||||
func Invert(img image.Image) *image.NRGBA {
|
||||
fn := func(c color.NRGBA) color.NRGBA {
|
||||
return color.NRGBA{255 - c.R, 255 - c.G, 255 - c.B, c.A}
|
||||
}
|
||||
return AdjustFunc(img, fn)
|
||||
func AdjustFunc(img image.Image, fn func(c color.NRGBA) color.NRGBA) *image.NRGBA {
|
||||
src := newScanner(img)
|
||||
dst := image.NewNRGBA(image.Rect(0, 0, src.w, src.h))
|
||||
parallel(0, src.h, func(ys <-chan int) {
|
||||
for y := range ys {
|
||||
i := y * dst.Stride
|
||||
src.scan(0, y, src.w, y+1, dst.Pix[i:i+src.w*4])
|
||||
for x := 0; x < src.w; x++ {
|
||||
r := dst.Pix[i+0]
|
||||
g := dst.Pix[i+1]
|
||||
b := dst.Pix[i+2]
|
||||
a := dst.Pix[i+3]
|
||||
c := fn(color.NRGBA{r, g, b, a})
|
||||
dst.Pix[i+0] = c.R
|
||||
dst.Pix[i+1] = c.G
|
||||
dst.Pix[i+2] = c.B
|
||||
dst.Pix[i+3] = c.A
|
||||
i += 4
|
||||
}
|
||||
}
|
||||
})
|
||||
return dst
|
||||
}
|
||||
|
||||
564
vendor/github.com/disintegration/imaging/adjust_test.go
сгенерированный
поставляемый
@@ -1,564 +0,0 @@
|
||||
package imaging
|
||||
|
||||
import (
|
||||
"image"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestGrayscale(t *testing.T) {
|
||||
td := []struct {
|
||||
desc string
|
||||
src image.Image
|
||||
want *image.NRGBA
|
||||
}{
|
||||
{
|
||||
"Grayscale 3x3",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 2, 2),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0xcc, 0x00, 0x00, 0x01, 0x00, 0xcc, 0x00, 0x02, 0x00, 0x00, 0xcc, 0x03,
|
||||
0x11, 0x22, 0x33, 0xff, 0x33, 0x22, 0x11, 0xff, 0xaa, 0x33, 0xbb, 0xff,
|
||||
0x00, 0x00, 0x00, 0xff, 0x33, 0x33, 0x33, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 3, 3),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0x3d, 0x3d, 0x3d, 0x01, 0x78, 0x78, 0x78, 0x02, 0x17, 0x17, 0x17, 0x03,
|
||||
0x1f, 0x1f, 0x1f, 0xff, 0x25, 0x25, 0x25, 0xff, 0x66, 0x66, 0x66, 0xff,
|
||||
0x00, 0x00, 0x00, 0xff, 0x33, 0x33, 0x33, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
for _, d := range td {
|
||||
got := Grayscale(d.src)
|
||||
want := d.want
|
||||
if !compareNRGBA(got, want, 0) {
|
||||
t.Errorf("test [%s] failed: %#v", d.desc, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestInvert(t *testing.T) {
|
||||
td := []struct {
|
||||
desc string
|
||||
src image.Image
|
||||
want *image.NRGBA
|
||||
}{
|
||||
{
|
||||
"Invert 3x3",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 2, 2),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0xcc, 0x00, 0x00, 0x01, 0x00, 0xcc, 0x00, 0x02, 0x00, 0x00, 0xcc, 0x03,
|
||||
0x11, 0x22, 0x33, 0xff, 0x33, 0x22, 0x11, 0xff, 0xaa, 0x33, 0xbb, 0xff,
|
||||
0x00, 0x00, 0x00, 0xff, 0x33, 0x33, 0x33, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 3, 3),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0x33, 0xff, 0xff, 0x01, 0xff, 0x33, 0xff, 0x02, 0xff, 0xff, 0x33, 0x03,
|
||||
0xee, 0xdd, 0xcc, 0xff, 0xcc, 0xdd, 0xee, 0xff, 0x55, 0xcc, 0x44, 0xff,
|
||||
0xff, 0xff, 0xff, 0xff, 0xcc, 0xcc, 0xcc, 0xff, 0x00, 0x00, 0x00, 0xff,
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
for _, d := range td {
|
||||
got := Invert(d.src)
|
||||
want := d.want
|
||||
if !compareNRGBA(got, want, 0) {
|
||||
t.Errorf("test [%s] failed: %#v", d.desc, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdjustContrast(t *testing.T) {
|
||||
td := []struct {
|
||||
desc string
|
||||
src image.Image
|
||||
p float64
|
||||
want *image.NRGBA
|
||||
}{
|
||||
{
|
||||
"AdjustContrast 3x3 10",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 2, 2),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0xcc, 0x00, 0x00, 0x01, 0x00, 0xcc, 0x00, 0x02, 0x00, 0x00, 0xcc, 0x03,
|
||||
0x11, 0x22, 0x33, 0xff, 0x33, 0x22, 0x11, 0xff, 0xaa, 0x33, 0xbb, 0xff,
|
||||
0x00, 0x00, 0x00, 0xff, 0x33, 0x33, 0x33, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
10,
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 3, 3),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0xd5, 0x00, 0x00, 0x01, 0x00, 0xd5, 0x00, 0x02, 0x00, 0x00, 0xd5, 0x03,
|
||||
0x05, 0x18, 0x2b, 0xff, 0x2b, 0x18, 0x05, 0xff, 0xaf, 0x2b, 0xc2, 0xff,
|
||||
0x00, 0x00, 0x00, 0xff, 0x2b, 0x2b, 0x2b, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
"AdjustContrast 3x3 100",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 2, 2),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0xcc, 0x00, 0x00, 0x01, 0x00, 0xcc, 0x00, 0x02, 0x00, 0x00, 0xcc, 0x03,
|
||||
0x11, 0x22, 0x33, 0xff, 0x33, 0x22, 0x11, 0xff, 0xaa, 0x33, 0xbb, 0xff,
|
||||
0x00, 0x00, 0x00, 0xff, 0x33, 0x33, 0x33, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
100,
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 3, 3),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0xff, 0x00, 0x00, 0x01, 0x00, 0xff, 0x00, 0x02, 0x00, 0x00, 0xff, 0x03,
|
||||
0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0x00, 0xff, 0xff, 0x00, 0xff, 0xff,
|
||||
0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
"AdjustContrast 3x3 -10",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 2, 2),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0xcc, 0x00, 0x00, 0x01, 0x00, 0xcc, 0x00, 0x02, 0x00, 0x00, 0xcc, 0x03,
|
||||
0x11, 0x22, 0x33, 0xff, 0x33, 0x22, 0x11, 0xff, 0xaa, 0x33, 0xbb, 0xff,
|
||||
0x00, 0x00, 0x00, 0xff, 0x33, 0x33, 0x33, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
-10,
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 3, 3),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0xc4, 0x0d, 0x0d, 0x01, 0x0d, 0xc4, 0x0d, 0x02, 0x0d, 0x0d, 0xc4, 0x03,
|
||||
0x1c, 0x2b, 0x3b, 0xff, 0x3b, 0x2b, 0x1c, 0xff, 0xa6, 0x3b, 0xb5, 0xff,
|
||||
0x0d, 0x0d, 0x0d, 0xff, 0x3b, 0x3b, 0x3b, 0xff, 0xf2, 0xf2, 0xf2, 0xff,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
"AdjustContrast 3x3 -100",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 2, 2),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0xcc, 0x00, 0x00, 0x01, 0x00, 0xcc, 0x00, 0x02, 0x00, 0x00, 0xcc, 0x03,
|
||||
0x11, 0x22, 0x33, 0xff, 0x33, 0x22, 0x11, 0xff, 0xaa, 0x33, 0xbb, 0xff,
|
||||
0x00, 0x00, 0x00, 0xff, 0x33, 0x33, 0x33, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
-100,
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 3, 3),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0x80, 0x80, 0x80, 0x01, 0x80, 0x80, 0x80, 0x02, 0x80, 0x80, 0x80, 0x03,
|
||||
0x80, 0x80, 0x80, 0xff, 0x80, 0x80, 0x80, 0xff, 0x80, 0x80, 0x80, 0xff,
|
||||
0x80, 0x80, 0x80, 0xff, 0x80, 0x80, 0x80, 0xff, 0x80, 0x80, 0x80, 0xff,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
"AdjustContrast 3x3 0",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 2, 2),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0xcc, 0x00, 0x00, 0x01, 0x00, 0xcc, 0x00, 0x02, 0x00, 0x00, 0xcc, 0x03,
|
||||
0x11, 0x22, 0x33, 0xff, 0x33, 0x22, 0x11, 0xff, 0xaa, 0x33, 0xbb, 0xff,
|
||||
0x00, 0x00, 0x00, 0xff, 0x33, 0x33, 0x33, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
0,
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 3, 3),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0xcc, 0x00, 0x00, 0x01, 0x00, 0xcc, 0x00, 0x02, 0x00, 0x00, 0xcc, 0x03,
|
||||
0x11, 0x22, 0x33, 0xff, 0x33, 0x22, 0x11, 0xff, 0xaa, 0x33, 0xbb, 0xff,
|
||||
0x00, 0x00, 0x00, 0xff, 0x33, 0x33, 0x33, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
for _, d := range td {
|
||||
got := AdjustContrast(d.src, d.p)
|
||||
want := d.want
|
||||
if !compareNRGBA(got, want, 0) {
|
||||
t.Errorf("test [%s] failed: %#v", d.desc, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdjustContrastGolden(t *testing.T) {
|
||||
src, err := Open("testdata/lena_128.png")
|
||||
if err != nil {
|
||||
t.Errorf("Open: %v", err)
|
||||
}
|
||||
for name, p := range map[string]float64{
|
||||
"out_contrast_m10.png": -10,
|
||||
"out_contrast_p10.png": 10,
|
||||
} {
|
||||
got := AdjustContrast(src, p)
|
||||
want, err := Open("testdata/" + name)
|
||||
if err != nil {
|
||||
t.Errorf("Open: %v", err)
|
||||
}
|
||||
if !compareNRGBA(got, toNRGBA(want), 0) {
|
||||
t.Errorf("resulting image differs from golden: %s", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdjustBrightness(t *testing.T) {
|
||||
td := []struct {
|
||||
desc string
|
||||
src image.Image
|
||||
p float64
|
||||
want *image.NRGBA
|
||||
}{
|
||||
{
|
||||
"AdjustBrightness 3x3 10",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 2, 2),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0xcc, 0x00, 0x00, 0x01, 0x00, 0xcc, 0x00, 0x02, 0x00, 0x00, 0xcc, 0x03,
|
||||
0x11, 0x22, 0x33, 0xff, 0x33, 0x22, 0x11, 0xff, 0xaa, 0x33, 0xbb, 0xff,
|
||||
0x00, 0x00, 0x00, 0xff, 0x33, 0x33, 0x33, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
10,
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 3, 3),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0xe6, 0x1a, 0x1a, 0x01, 0x1a, 0xe6, 0x1a, 0x02, 0x1a, 0x1a, 0xe6, 0x03,
|
||||
0x2b, 0x3c, 0x4d, 0xff, 0x4d, 0x3c, 0x2b, 0xff, 0xc4, 0x4d, 0xd5, 0xff,
|
||||
0x1a, 0x1a, 0x1a, 0xff, 0x4d, 0x4d, 0x4d, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
"AdjustBrightness 3x3 100",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 2, 2),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0xcc, 0x00, 0x00, 0x01, 0x00, 0xcc, 0x00, 0x02, 0x00, 0x00, 0xcc, 0x03,
|
||||
0x11, 0x22, 0x33, 0xff, 0x33, 0x22, 0x11, 0xff, 0xaa, 0x33, 0xbb, 0xff,
|
||||
0x00, 0x00, 0x00, 0xff, 0x33, 0x33, 0x33, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
100,
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 3, 3),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0xff, 0xff, 0xff, 0x01, 0xff, 0xff, 0xff, 0x02, 0xff, 0xff, 0xff, 0x03,
|
||||
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
"AdjustBrightness 3x3 -10",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 2, 2),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0xcc, 0x00, 0x00, 0x01, 0x00, 0xcc, 0x00, 0x02, 0x00, 0x00, 0xcc, 0x03,
|
||||
0x11, 0x22, 0x33, 0xff, 0x33, 0x22, 0x11, 0xff, 0xaa, 0x33, 0xbb, 0xff,
|
||||
0x00, 0x00, 0x00, 0xff, 0x33, 0x33, 0x33, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
-10,
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 3, 3),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0xb3, 0x00, 0x00, 0x01, 0x00, 0xb3, 0x00, 0x02, 0x00, 0x00, 0xb3, 0x03,
|
||||
0x00, 0x09, 0x1a, 0xff, 0x1a, 0x09, 0x00, 0xff, 0x91, 0x1a, 0xa2, 0xff,
|
||||
0x00, 0x00, 0x00, 0xff, 0x1a, 0x1a, 0x1a, 0xff, 0xe6, 0xe6, 0xe6, 0xff,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
"AdjustBrightness 3x3 -100",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 2, 2),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0xcc, 0x00, 0x00, 0x01, 0x00, 0xcc, 0x00, 0x02, 0x00, 0x00, 0xcc, 0x03,
|
||||
0x11, 0x22, 0x33, 0xff, 0x33, 0x22, 0x11, 0xff, 0xaa, 0x33, 0xbb, 0xff,
|
||||
0x00, 0x00, 0x00, 0xff, 0x33, 0x33, 0x33, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
-100,
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 3, 3),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x03,
|
||||
0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0x00, 0xff,
|
||||
0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0x00, 0xff,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
"AdjustBrightness 3x3 0",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 2, 2),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0xcc, 0x00, 0x00, 0x01, 0x00, 0xcc, 0x00, 0x02, 0x00, 0x00, 0xcc, 0x03,
|
||||
0x11, 0x22, 0x33, 0xff, 0x33, 0x22, 0x11, 0xff, 0xaa, 0x33, 0xbb, 0xff,
|
||||
0x00, 0x00, 0x00, 0xff, 0x33, 0x33, 0x33, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
0,
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 3, 3),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0xcc, 0x00, 0x00, 0x01, 0x00, 0xcc, 0x00, 0x02, 0x00, 0x00, 0xcc, 0x03,
|
||||
0x11, 0x22, 0x33, 0xff, 0x33, 0x22, 0x11, 0xff, 0xaa, 0x33, 0xbb, 0xff,
|
||||
0x00, 0x00, 0x00, 0xff, 0x33, 0x33, 0x33, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
for _, d := range td {
|
||||
got := AdjustBrightness(d.src, d.p)
|
||||
want := d.want
|
||||
if !compareNRGBA(got, want, 0) {
|
||||
t.Errorf("test [%s] failed: %#v", d.desc, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdjustBrightnessGolden(t *testing.T) {
|
||||
src, err := Open("testdata/lena_128.png")
|
||||
if err != nil {
|
||||
t.Errorf("Open: %v", err)
|
||||
}
|
||||
for name, p := range map[string]float64{
|
||||
"out_brightness_m10.png": -10,
|
||||
"out_brightness_p10.png": 10,
|
||||
} {
|
||||
got := AdjustBrightness(src, p)
|
||||
want, err := Open("testdata/" + name)
|
||||
if err != nil {
|
||||
t.Errorf("Open: %v", err)
|
||||
}
|
||||
if !compareNRGBA(got, toNRGBA(want), 0) {
|
||||
t.Errorf("resulting image differs from golden: %s", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdjustGamma(t *testing.T) {
|
||||
td := []struct {
|
||||
desc string
|
||||
src image.Image
|
||||
p float64
|
||||
want *image.NRGBA
|
||||
}{
|
||||
{
|
||||
"AdjustGamma 3x3 0.75",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 2, 2),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0xcc, 0x00, 0x00, 0x01, 0x00, 0xcc, 0x00, 0x02, 0x00, 0x00, 0xcc, 0x03,
|
||||
0x11, 0x22, 0x33, 0xff, 0x33, 0x22, 0x11, 0xff, 0xaa, 0x33, 0xbb, 0xff,
|
||||
0x00, 0x00, 0x00, 0xff, 0x33, 0x33, 0x33, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
0.75,
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 3, 3),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0xbd, 0x00, 0x00, 0x01, 0x00, 0xbd, 0x00, 0x02, 0x00, 0x00, 0xbd, 0x03,
|
||||
0x07, 0x11, 0x1e, 0xff, 0x1e, 0x11, 0x07, 0xff, 0x95, 0x1e, 0xa9, 0xff,
|
||||
0x00, 0x00, 0x00, 0xff, 0x1e, 0x1e, 0x1e, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
"AdjustGamma 3x3 1.5",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 2, 2),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0xcc, 0x00, 0x00, 0x01, 0x00, 0xcc, 0x00, 0x02, 0x00, 0x00, 0xcc, 0x03,
|
||||
0x11, 0x22, 0x33, 0xff, 0x33, 0x22, 0x11, 0xff, 0xaa, 0x33, 0xbb, 0xff,
|
||||
0x00, 0x00, 0x00, 0xff, 0x33, 0x33, 0x33, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
1.5,
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 3, 3),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0xdc, 0x00, 0x00, 0x01, 0x00, 0xdc, 0x00, 0x02, 0x00, 0x00, 0xdc, 0x03,
|
||||
0x2a, 0x43, 0x57, 0xff, 0x57, 0x43, 0x2a, 0xff, 0xc3, 0x57, 0xcf, 0xff,
|
||||
0x00, 0x00, 0x00, 0xff, 0x57, 0x57, 0x57, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
"AdjustGamma 3x3 1.0",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 2, 2),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0xcc, 0x00, 0x00, 0x01, 0x00, 0xcc, 0x00, 0x02, 0x00, 0x00, 0xcc, 0x03,
|
||||
0x11, 0x22, 0x33, 0xff, 0x33, 0x22, 0x11, 0xff, 0xaa, 0x33, 0xbb, 0xff,
|
||||
0x00, 0x00, 0x00, 0xff, 0x33, 0x33, 0x33, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
1.0,
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 3, 3),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0xcc, 0x00, 0x00, 0x01, 0x00, 0xcc, 0x00, 0x02, 0x00, 0x00, 0xcc, 0x03,
|
||||
0x11, 0x22, 0x33, 0xff, 0x33, 0x22, 0x11, 0xff, 0xaa, 0x33, 0xbb, 0xff,
|
||||
0x00, 0x00, 0x00, 0xff, 0x33, 0x33, 0x33, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
for _, d := range td {
|
||||
got := AdjustGamma(d.src, d.p)
|
||||
want := d.want
|
||||
if !compareNRGBA(got, want, 0) {
|
||||
t.Errorf("test [%s] failed: %#v", d.desc, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdjustGammaGolden(t *testing.T) {
|
||||
src, err := Open("testdata/lena_128.png")
|
||||
if err != nil {
|
||||
t.Errorf("Open: %v", err)
|
||||
}
|
||||
for name, g := range map[string]float64{
|
||||
"out_gamma_0.75.png": 0.75,
|
||||
"out_gamma_1.25.png": 1.25,
|
||||
} {
|
||||
got := AdjustGamma(src, g)
|
||||
want, err := Open("testdata/" + name)
|
||||
if err != nil {
|
||||
t.Errorf("Open: %v", err)
|
||||
}
|
||||
if !compareNRGBA(got, toNRGBA(want), 0) {
|
||||
t.Errorf("resulting image differs from golden: %s", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdjustSigmoid(t *testing.T) {
|
||||
td := []struct {
|
||||
desc string
|
||||
src image.Image
|
||||
m float64
|
||||
p float64
|
||||
want *image.NRGBA
|
||||
}{
|
||||
{
|
||||
"AdjustSigmoid 3x3 0.5 3.0",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 2, 2),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0xcc, 0x00, 0x00, 0x01, 0x00, 0xcc, 0x00, 0x02, 0x00, 0x00, 0xcc, 0x03,
|
||||
0x11, 0x22, 0x33, 0xff, 0x33, 0x22, 0x11, 0xff, 0xaa, 0x33, 0xbb, 0xff,
|
||||
0x00, 0x00, 0x00, 0xff, 0x33, 0x33, 0x33, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
0.5,
|
||||
3.0,
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 3, 3),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0xd4, 0x00, 0x00, 0x01, 0x00, 0xd4, 0x00, 0x02, 0x00, 0x00, 0xd4, 0x03,
|
||||
0x0d, 0x1b, 0x2b, 0xff, 0x2b, 0x1b, 0x0d, 0xff, 0xb1, 0x2b, 0xc3, 0xff,
|
||||
0x00, 0x00, 0x00, 0xff, 0x2b, 0x2b, 0x2b, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
"AdjustSigmoid 3x3 0.5 -3.0",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 2, 2),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0xcc, 0x00, 0x00, 0x01, 0x00, 0xcc, 0x00, 0x02, 0x00, 0x00, 0xcc, 0x03,
|
||||
0x11, 0x22, 0x33, 0xff, 0x33, 0x22, 0x11, 0xff, 0xaa, 0x33, 0xbb, 0xff,
|
||||
0x00, 0x00, 0x00, 0xff, 0x33, 0x33, 0x33, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
0.5,
|
||||
-3.0,
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 3, 3),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0xc4, 0x00, 0x00, 0x01, 0x00, 0xc4, 0x00, 0x02, 0x00, 0x00, 0xc4, 0x03,
|
||||
0x16, 0x2a, 0x3b, 0xff, 0x3b, 0x2a, 0x16, 0xff, 0xa4, 0x3b, 0xb3, 0xff,
|
||||
0x00, 0x00, 0x00, 0xff, 0x3b, 0x3b, 0x3b, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
"AdjustSigmoid 3x3 0.5 0.0",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 2, 2),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0xcc, 0x00, 0x00, 0x01, 0x00, 0xcc, 0x00, 0x02, 0x00, 0x00, 0xcc, 0x03,
|
||||
0x11, 0x22, 0x33, 0xff, 0x33, 0x22, 0x11, 0xff, 0xaa, 0x33, 0xbb, 0xff,
|
||||
0x00, 0x00, 0x00, 0xff, 0x33, 0x33, 0x33, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
0.5,
|
||||
0.0,
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 3, 3),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0xcc, 0x00, 0x00, 0x01, 0x00, 0xcc, 0x00, 0x02, 0x00, 0x00, 0xcc, 0x03,
|
||||
0x11, 0x22, 0x33, 0xff, 0x33, 0x22, 0x11, 0xff, 0xaa, 0x33, 0xbb, 0xff,
|
||||
0x00, 0x00, 0x00, 0xff, 0x33, 0x33, 0x33, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
for _, d := range td {
|
||||
got := AdjustSigmoid(d.src, d.m, d.p)
|
||||
want := d.want
|
||||
if !compareNRGBA(got, want, 0) {
|
||||
t.Errorf("test [%s] failed: %#v", d.desc, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
312
vendor/github.com/disintegration/imaging/clone.go
сгенерированный
поставляемый
@@ -1,312 +0,0 @@
|
||||
package imaging
|
||||
|
||||
import (
|
||||
"image"
|
||||
"image/color"
|
||||
)
|
||||
|
||||
// Clone returns a copy of the given image.
|
||||
func Clone(img image.Image) *image.NRGBA {
|
||||
dstBounds := img.Bounds().Sub(img.Bounds().Min)
|
||||
dst := image.NewNRGBA(dstBounds)
|
||||
|
||||
switch src := img.(type) {
|
||||
case *image.NRGBA:
|
||||
copyNRGBA(dst, src)
|
||||
case *image.NRGBA64:
|
||||
copyNRGBA64(dst, src)
|
||||
case *image.RGBA:
|
||||
copyRGBA(dst, src)
|
||||
case *image.RGBA64:
|
||||
copyRGBA64(dst, src)
|
||||
case *image.Gray:
|
||||
copyGray(dst, src)
|
||||
case *image.Gray16:
|
||||
copyGray16(dst, src)
|
||||
case *image.YCbCr:
|
||||
copyYCbCr(dst, src)
|
||||
case *image.Paletted:
|
||||
copyPaletted(dst, src)
|
||||
default:
|
||||
copyImage(dst, src)
|
||||
}
|
||||
|
||||
return dst
|
||||
}
|
||||
|
||||
func copyNRGBA(dst *image.NRGBA, src *image.NRGBA) {
|
||||
srcMinX := src.Rect.Min.X
|
||||
srcMinY := src.Rect.Min.Y
|
||||
dstW := dst.Rect.Dx()
|
||||
dstH := dst.Rect.Dy()
|
||||
rowSize := dstW * 4
|
||||
parallel(dstH, func(partStart, partEnd int) {
|
||||
for dstY := partStart; dstY < partEnd; dstY++ {
|
||||
di := dst.PixOffset(0, dstY)
|
||||
si := src.PixOffset(srcMinX, srcMinY+dstY)
|
||||
copy(dst.Pix[di:di+rowSize], src.Pix[si:si+rowSize])
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func copyNRGBA64(dst *image.NRGBA, src *image.NRGBA64) {
|
||||
srcMinX := src.Rect.Min.X
|
||||
srcMinY := src.Rect.Min.Y
|
||||
dstW := dst.Rect.Dx()
|
||||
dstH := dst.Rect.Dy()
|
||||
parallel(dstH, func(partStart, partEnd int) {
|
||||
for dstY := partStart; dstY < partEnd; dstY++ {
|
||||
di := dst.PixOffset(0, dstY)
|
||||
si := src.PixOffset(srcMinX, srcMinY+dstY)
|
||||
for dstX := 0; dstX < dstW; dstX++ {
|
||||
dst.Pix[di+0] = src.Pix[si+0]
|
||||
dst.Pix[di+1] = src.Pix[si+2]
|
||||
dst.Pix[di+2] = src.Pix[si+4]
|
||||
dst.Pix[di+3] = src.Pix[si+6]
|
||||
di += 4
|
||||
si += 8
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func copyRGBA(dst *image.NRGBA, src *image.RGBA) {
|
||||
srcMinX := src.Rect.Min.X
|
||||
srcMinY := src.Rect.Min.Y
|
||||
dstW := dst.Rect.Dx()
|
||||
dstH := dst.Rect.Dy()
|
||||
parallel(dstH, func(partStart, partEnd int) {
|
||||
for dstY := partStart; dstY < partEnd; dstY++ {
|
||||
di := dst.PixOffset(0, dstY)
|
||||
si := src.PixOffset(srcMinX, srcMinY+dstY)
|
||||
for dstX := 0; dstX < dstW; dstX++ {
|
||||
a := src.Pix[si+3]
|
||||
dst.Pix[di+3] = a
|
||||
|
||||
switch a {
|
||||
case 0:
|
||||
dst.Pix[di+0] = 0
|
||||
dst.Pix[di+1] = 0
|
||||
dst.Pix[di+2] = 0
|
||||
case 0xff:
|
||||
dst.Pix[di+0] = src.Pix[si+0]
|
||||
dst.Pix[di+1] = src.Pix[si+1]
|
||||
dst.Pix[di+2] = src.Pix[si+2]
|
||||
default:
|
||||
var tmp uint16
|
||||
tmp = uint16(src.Pix[si+0]) * 0xff / uint16(a)
|
||||
dst.Pix[di+0] = uint8(tmp)
|
||||
tmp = uint16(src.Pix[si+1]) * 0xff / uint16(a)
|
||||
dst.Pix[di+1] = uint8(tmp)
|
||||
tmp = uint16(src.Pix[si+2]) * 0xff / uint16(a)
|
||||
dst.Pix[di+2] = uint8(tmp)
|
||||
}
|
||||
|
||||
di += 4
|
||||
si += 4
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func copyRGBA64(dst *image.NRGBA, src *image.RGBA64) {
|
||||
srcMinX := src.Rect.Min.X
|
||||
srcMinY := src.Rect.Min.Y
|
||||
dstW := dst.Rect.Dx()
|
||||
dstH := dst.Rect.Dy()
|
||||
parallel(dstH, func(partStart, partEnd int) {
|
||||
for dstY := partStart; dstY < partEnd; dstY++ {
|
||||
di := dst.PixOffset(0, dstY)
|
||||
si := src.PixOffset(srcMinX, srcMinY+dstY)
|
||||
for dstX := 0; dstX < dstW; dstX++ {
|
||||
a := src.Pix[si+6]
|
||||
dst.Pix[di+3] = a
|
||||
|
||||
switch a {
|
||||
case 0:
|
||||
dst.Pix[di+0] = 0
|
||||
dst.Pix[di+1] = 0
|
||||
dst.Pix[di+2] = 0
|
||||
case 0xff:
|
||||
dst.Pix[di+0] = src.Pix[si+0]
|
||||
dst.Pix[di+1] = src.Pix[si+2]
|
||||
dst.Pix[di+2] = src.Pix[si+4]
|
||||
default:
|
||||
var tmp uint16
|
||||
tmp = uint16(src.Pix[si+0]) * 0xff / uint16(a)
|
||||
dst.Pix[di+0] = uint8(tmp)
|
||||
tmp = uint16(src.Pix[si+2]) * 0xff / uint16(a)
|
||||
dst.Pix[di+1] = uint8(tmp)
|
||||
tmp = uint16(src.Pix[si+4]) * 0xff / uint16(a)
|
||||
dst.Pix[di+2] = uint8(tmp)
|
||||
}
|
||||
|
||||
di += 4
|
||||
si += 8
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func copyGray(dst *image.NRGBA, src *image.Gray) {
|
||||
srcMinX := src.Rect.Min.X
|
||||
srcMinY := src.Rect.Min.Y
|
||||
dstW := dst.Rect.Dx()
|
||||
dstH := dst.Rect.Dy()
|
||||
parallel(dstH, func(partStart, partEnd int) {
|
||||
for dstY := partStart; dstY < partEnd; dstY++ {
|
||||
di := dst.PixOffset(0, dstY)
|
||||
si := src.PixOffset(srcMinX, srcMinY+dstY)
|
||||
for dstX := 0; dstX < dstW; dstX++ {
|
||||
c := src.Pix[si]
|
||||
dst.Pix[di+0] = c
|
||||
dst.Pix[di+1] = c
|
||||
dst.Pix[di+2] = c
|
||||
dst.Pix[di+3] = 0xff
|
||||
di += 4
|
||||
si++
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func copyGray16(dst *image.NRGBA, src *image.Gray16) {
|
||||
srcMinX := src.Rect.Min.X
|
||||
srcMinY := src.Rect.Min.Y
|
||||
dstW := dst.Rect.Dx()
|
||||
dstH := dst.Rect.Dy()
|
||||
parallel(dstH, func(partStart, partEnd int) {
|
||||
for dstY := partStart; dstY < partEnd; dstY++ {
|
||||
di := dst.PixOffset(0, dstY)
|
||||
si := src.PixOffset(srcMinX, srcMinY+dstY)
|
||||
for dstX := 0; dstX < dstW; dstX++ {
|
||||
c := src.Pix[si]
|
||||
dst.Pix[di+0] = c
|
||||
dst.Pix[di+1] = c
|
||||
dst.Pix[di+2] = c
|
||||
dst.Pix[di+3] = 0xff
|
||||
di += 4
|
||||
si += 2
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func copyYCbCr(dst *image.NRGBA, src *image.YCbCr) {
|
||||
srcMinX := src.Rect.Min.X
|
||||
srcMinY := src.Rect.Min.Y
|
||||
dstW := dst.Rect.Dx()
|
||||
dstH := dst.Rect.Dy()
|
||||
parallel(dstH, func(partStart, partEnd int) {
|
||||
for dstY := partStart; dstY < partEnd; dstY++ {
|
||||
srcY := srcMinY + dstY
|
||||
di := dst.PixOffset(0, dstY)
|
||||
for dstX := 0; dstX < dstW; dstX++ {
|
||||
srcX := srcMinX + dstX
|
||||
|
||||
siy := (srcY-srcMinY)*src.YStride + (srcX - srcMinX)
|
||||
|
||||
var sic int
|
||||
switch src.SubsampleRatio {
|
||||
case image.YCbCrSubsampleRatio444:
|
||||
sic = (srcY-srcMinY)*src.CStride + (srcX - srcMinX)
|
||||
case image.YCbCrSubsampleRatio422:
|
||||
sic = (srcY-srcMinY)*src.CStride + (srcX/2 - srcMinX/2)
|
||||
case image.YCbCrSubsampleRatio420:
|
||||
sic = (srcY/2-srcMinY/2)*src.CStride + (srcX/2 - srcMinX/2)
|
||||
case image.YCbCrSubsampleRatio440:
|
||||
sic = (srcY/2-srcMinY/2)*src.CStride + (srcX - srcMinX)
|
||||
default:
|
||||
sic = src.COffset(srcX, srcY)
|
||||
}
|
||||
|
||||
y := int32(src.Y[siy])
|
||||
cb := int32(src.Cb[sic]) - 128
|
||||
cr := int32(src.Cr[sic]) - 128
|
||||
|
||||
r := (y<<16 + 91881*cr + 1<<15) >> 16
|
||||
if r > 255 {
|
||||
r = 255
|
||||
} else if r < 0 {
|
||||
r = 0
|
||||
}
|
||||
|
||||
g := (y<<16 - 22554*cb - 46802*cr + 1<<15) >> 16
|
||||
if g > 255 {
|
||||
g = 255
|
||||
} else if g < 0 {
|
||||
g = 0
|
||||
}
|
||||
|
||||
b := (y<<16 + 116130*cb + 1<<15) >> 16
|
||||
if b > 255 {
|
||||
b = 255
|
||||
} else if b < 0 {
|
||||
b = 0
|
||||
}
|
||||
|
||||
dst.Pix[di+0] = uint8(r)
|
||||
dst.Pix[di+1] = uint8(g)
|
||||
dst.Pix[di+2] = uint8(b)
|
||||
dst.Pix[di+3] = 255
|
||||
|
||||
di += 4
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func copyPaletted(dst *image.NRGBA, src *image.Paletted) {
|
||||
srcMinX := src.Rect.Min.X
|
||||
srcMinY := src.Rect.Min.Y
|
||||
dstW := dst.Rect.Dx()
|
||||
dstH := dst.Rect.Dy()
|
||||
plen := len(src.Palette)
|
||||
pnew := make([]color.NRGBA, plen)
|
||||
for i := 0; i < plen; i++ {
|
||||
pnew[i] = color.NRGBAModel.Convert(src.Palette[i]).(color.NRGBA)
|
||||
}
|
||||
parallel(dstH, func(partStart, partEnd int) {
|
||||
for dstY := partStart; dstY < partEnd; dstY++ {
|
||||
di := dst.PixOffset(0, dstY)
|
||||
si := src.PixOffset(srcMinX, srcMinY+dstY)
|
||||
for dstX := 0; dstX < dstW; dstX++ {
|
||||
c := pnew[src.Pix[si]]
|
||||
dst.Pix[di+0] = c.R
|
||||
dst.Pix[di+1] = c.G
|
||||
dst.Pix[di+2] = c.B
|
||||
dst.Pix[di+3] = c.A
|
||||
di += 4
|
||||
si++
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func copyImage(dst *image.NRGBA, src image.Image) {
|
||||
srcMinX := src.Bounds().Min.X
|
||||
srcMinY := src.Bounds().Min.Y
|
||||
dstW := dst.Bounds().Dx()
|
||||
dstH := dst.Bounds().Dy()
|
||||
parallel(dstH, func(partStart, partEnd int) {
|
||||
for dstY := partStart; dstY < partEnd; dstY++ {
|
||||
di := dst.PixOffset(0, dstY)
|
||||
for dstX := 0; dstX < dstW; dstX++ {
|
||||
c := color.NRGBAModel.Convert(src.At(srcMinX+dstX, srcMinY+dstY)).(color.NRGBA)
|
||||
dst.Pix[di+0] = c.R
|
||||
dst.Pix[di+1] = c.G
|
||||
dst.Pix[di+2] = c.B
|
||||
dst.Pix[di+3] = c.A
|
||||
di += 4
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// toNRGBA converts any image type to *image.NRGBA with min-point at (0, 0).
|
||||
func toNRGBA(img image.Image) *image.NRGBA {
|
||||
if img, ok := img.(*image.NRGBA); ok && img.Bounds().Min.Eq(image.ZP) {
|
||||
return img
|
||||
}
|
||||
return Clone(img)
|
||||
}
|
||||
247
vendor/github.com/disintegration/imaging/clone_test.go
сгенерированный
поставляемый
@@ -1,247 +0,0 @@
|
||||
package imaging
|
||||
|
||||
import (
|
||||
"image"
|
||||
"image/color"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestClone(t *testing.T) {
|
||||
td := []struct {
|
||||
desc string
|
||||
src image.Image
|
||||
want *image.NRGBA
|
||||
}{
|
||||
{
|
||||
"Clone NRGBA",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 0, 1),
|
||||
Stride: 1 * 4,
|
||||
Pix: []uint8{0x00, 0x11, 0x22, 0x33, 0xcc, 0xdd, 0xee, 0xff},
|
||||
},
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 1, 2),
|
||||
Stride: 1 * 4,
|
||||
Pix: []uint8{0x00, 0x11, 0x22, 0x33, 0xcc, 0xdd, 0xee, 0xff},
|
||||
},
|
||||
},
|
||||
{
|
||||
"Clone NRGBA64",
|
||||
&image.NRGBA64{
|
||||
Rect: image.Rect(-1, -1, 0, 1),
|
||||
Stride: 1 * 8,
|
||||
Pix: []uint8{
|
||||
0x00, 0x00, 0x11, 0x11, 0x22, 0x22, 0x33, 0x33,
|
||||
0xcc, 0xcc, 0xdd, 0xdd, 0xee, 0xee, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 1, 2),
|
||||
Stride: 1 * 4,
|
||||
Pix: []uint8{0x00, 0x11, 0x22, 0x33, 0xcc, 0xdd, 0xee, 0xff},
|
||||
},
|
||||
},
|
||||
{
|
||||
"Clone RGBA",
|
||||
&image.RGBA{
|
||||
Rect: image.Rect(-1, -1, 0, 2),
|
||||
Stride: 1 * 4,
|
||||
Pix: []uint8{0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x22, 0x33, 0xcc, 0xdd, 0xee, 0xff},
|
||||
},
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 1, 3),
|
||||
Stride: 1 * 4,
|
||||
Pix: []uint8{0x00, 0x00, 0x00, 0x00, 0x00, 0x55, 0xaa, 0x33, 0xcc, 0xdd, 0xee, 0xff},
|
||||
},
|
||||
},
|
||||
{
|
||||
"Clone RGBA64",
|
||||
&image.RGBA64{
|
||||
Rect: image.Rect(-1, -1, 0, 2),
|
||||
Stride: 1 * 8,
|
||||
Pix: []uint8{
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x11, 0x11, 0x22, 0x22, 0x33, 0x33,
|
||||
0xcc, 0xcc, 0xdd, 0xdd, 0xee, 0xee, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 1, 3),
|
||||
Stride: 1 * 4,
|
||||
Pix: []uint8{0x00, 0x00, 0x00, 0x00, 0x00, 0x55, 0xaa, 0x33, 0xcc, 0xdd, 0xee, 0xff},
|
||||
},
|
||||
},
|
||||
{
|
||||
"Clone Gray",
|
||||
&image.Gray{
|
||||
Rect: image.Rect(-1, -1, 0, 1),
|
||||
Stride: 1 * 1,
|
||||
Pix: []uint8{0x11, 0xee},
|
||||
},
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 1, 2),
|
||||
Stride: 1 * 4,
|
||||
Pix: []uint8{0x11, 0x11, 0x11, 0xff, 0xee, 0xee, 0xee, 0xff},
|
||||
},
|
||||
},
|
||||
{
|
||||
"Clone Gray16",
|
||||
&image.Gray16{
|
||||
Rect: image.Rect(-1, -1, 0, 1),
|
||||
Stride: 1 * 2,
|
||||
Pix: []uint8{0x11, 0x11, 0xee, 0xee},
|
||||
},
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 1, 2),
|
||||
Stride: 1 * 4,
|
||||
Pix: []uint8{0x11, 0x11, 0x11, 0xff, 0xee, 0xee, 0xee, 0xff},
|
||||
},
|
||||
},
|
||||
{
|
||||
"Clone Alpha",
|
||||
&image.Alpha{
|
||||
Rect: image.Rect(-1, -1, 0, 1),
|
||||
Stride: 1 * 1,
|
||||
Pix: []uint8{0x11, 0xee},
|
||||
},
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 1, 2),
|
||||
Stride: 1 * 4,
|
||||
Pix: []uint8{0xff, 0xff, 0xff, 0x11, 0xff, 0xff, 0xff, 0xee},
|
||||
},
|
||||
},
|
||||
{
|
||||
"Clone YCbCr",
|
||||
&image.YCbCr{
|
||||
Rect: image.Rect(-1, -1, 5, 0),
|
||||
SubsampleRatio: image.YCbCrSubsampleRatio444,
|
||||
YStride: 6,
|
||||
CStride: 6,
|
||||
Y: []uint8{0x00, 0xff, 0x7f, 0x26, 0x4b, 0x0e},
|
||||
Cb: []uint8{0x80, 0x80, 0x80, 0x6b, 0x56, 0xc0},
|
||||
Cr: []uint8{0x80, 0x80, 0x80, 0xc0, 0x4b, 0x76},
|
||||
},
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 6, 1),
|
||||
Stride: 6 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x00, 0x00, 0xff,
|
||||
0xff, 0xff, 0xff, 0xff,
|
||||
0x7f, 0x7f, 0x7f, 0xff,
|
||||
0x7f, 0x00, 0x00, 0xff,
|
||||
0x00, 0x7f, 0x00, 0xff,
|
||||
0x00, 0x00, 0x7f, 0xff,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
"Clone YCbCr 444",
|
||||
&image.YCbCr{
|
||||
Y: []uint8{0x4c, 0x69, 0x1d, 0xb1, 0x96, 0xe2, 0x26, 0x34, 0xe, 0x59, 0x4b, 0x71, 0x0, 0x4c, 0x99, 0xff},
|
||||
Cb: []uint8{0x55, 0xd4, 0xff, 0x8e, 0x2c, 0x01, 0x6b, 0xaa, 0xc0, 0x95, 0x56, 0x40, 0x80, 0x80, 0x80, 0x80},
|
||||
Cr: []uint8{0xff, 0xeb, 0x6b, 0x36, 0x15, 0x95, 0xc0, 0xb5, 0x76, 0x41, 0x4b, 0x8c, 0x80, 0x80, 0x80, 0x80},
|
||||
YStride: 4,
|
||||
CStride: 4,
|
||||
SubsampleRatio: image.YCbCrSubsampleRatio444,
|
||||
Rect: image.Rectangle{Min: image.Point{X: 0, Y: 0}, Max: image.Point{X: 4, Y: 4}},
|
||||
},
|
||||
&image.NRGBA{
|
||||
Pix: []uint8{0xff, 0x0, 0x0, 0xff, 0xff, 0x0, 0xff, 0xff, 0x0, 0x0, 0xff, 0xff, 0x49, 0xe1, 0xca, 0xff, 0x0, 0xff, 0x0, 0xff, 0xff, 0xff, 0x0, 0xff, 0x7f, 0x0, 0x0, 0xff, 0x7f, 0x0, 0x7f, 0xff, 0x0, 0x0, 0x7f, 0xff, 0x0, 0x7f, 0x7f, 0xff, 0x0, 0x7f, 0x0, 0xff, 0x82, 0x7f, 0x0, 0xff, 0x0, 0x0, 0x0, 0xff, 0x4c, 0x4c, 0x4c, 0xff, 0x99, 0x99, 0x99, 0xff, 0xff, 0xff, 0xff, 0xff},
|
||||
Stride: 16,
|
||||
Rect: image.Rectangle{Min: image.Point{X: 0, Y: 0}, Max: image.Point{X: 4, Y: 4}},
|
||||
},
|
||||
},
|
||||
{
|
||||
"Clone YCbCr 440",
|
||||
&image.YCbCr{
|
||||
Y: []uint8{0x4c, 0x69, 0x1d, 0xb1, 0x96, 0xe2, 0x26, 0x34, 0xe, 0x59, 0x4b, 0x71, 0x0, 0x4c, 0x99, 0xff},
|
||||
Cb: []uint8{0x2c, 0x01, 0x6b, 0xaa, 0x80, 0x80, 0x80, 0x80},
|
||||
Cr: []uint8{0x15, 0x95, 0xc0, 0xb5, 0x80, 0x80, 0x80, 0x80},
|
||||
YStride: 4,
|
||||
CStride: 4,
|
||||
SubsampleRatio: image.YCbCrSubsampleRatio440,
|
||||
Rect: image.Rectangle{Min: image.Point{X: 0, Y: 0}, Max: image.Point{X: 4, Y: 4}},
|
||||
},
|
||||
&image.NRGBA{
|
||||
Pix: []uint8{0x0, 0xb5, 0x0, 0xff, 0x86, 0x86, 0x0, 0xff, 0x77, 0x0, 0x0, 0xff, 0xfb, 0x7d, 0xfb, 0xff, 0x0, 0xff, 0x1, 0xff, 0xff, 0xff, 0x1, 0xff, 0x80, 0x0, 0x1, 0xff, 0x7e, 0x0, 0x7e, 0xff, 0xe, 0xe, 0xe, 0xff, 0x59, 0x59, 0x59, 0xff, 0x4b, 0x4b, 0x4b, 0xff, 0x71, 0x71, 0x71, 0xff, 0x0, 0x0, 0x0, 0xff, 0x4c, 0x4c, 0x4c, 0xff, 0x99, 0x99, 0x99, 0xff, 0xff, 0xff, 0xff, 0xff},
|
||||
Stride: 16,
|
||||
Rect: image.Rectangle{Min: image.Point{X: 0, Y: 0}, Max: image.Point{X: 4, Y: 4}},
|
||||
},
|
||||
},
|
||||
{
|
||||
"Clone YCbCr 422",
|
||||
&image.YCbCr{
|
||||
Y: []uint8{0x4c, 0x69, 0x1d, 0xb1, 0x96, 0xe2, 0x26, 0x34, 0xe, 0x59, 0x4b, 0x71, 0x0, 0x4c, 0x99, 0xff},
|
||||
Cb: []uint8{0xd4, 0x8e, 0x01, 0xaa, 0x95, 0x40, 0x80, 0x80},
|
||||
Cr: []uint8{0xeb, 0x36, 0x95, 0xb5, 0x41, 0x8c, 0x80, 0x80},
|
||||
YStride: 4,
|
||||
CStride: 2,
|
||||
SubsampleRatio: image.YCbCrSubsampleRatio422,
|
||||
Rect: image.Rectangle{Min: image.Point{X: 0, Y: 0}, Max: image.Point{X: 4, Y: 4}},
|
||||
},
|
||||
&image.NRGBA{
|
||||
Pix: []uint8{0xe2, 0x0, 0xe1, 0xff, 0xff, 0x0, 0xfe, 0xff, 0x0, 0x4d, 0x36, 0xff, 0x49, 0xe1, 0xca, 0xff, 0xb3, 0xb3, 0x0, 0xff, 0xff, 0xff, 0x1, 0xff, 0x70, 0x0, 0x70, 0xff, 0x7e, 0x0, 0x7e, 0xff, 0x0, 0x34, 0x33, 0xff, 0x1, 0x7f, 0x7e, 0xff, 0x5c, 0x58, 0x0, 0xff, 0x82, 0x7e, 0x0, 0xff, 0x0, 0x0, 0x0, 0xff, 0x4c, 0x4c, 0x4c, 0xff, 0x99, 0x99, 0x99, 0xff, 0xff, 0xff, 0xff, 0xff},
|
||||
Stride: 16,
|
||||
Rect: image.Rectangle{Min: image.Point{X: 0, Y: 0}, Max: image.Point{X: 4, Y: 4}},
|
||||
},
|
||||
},
|
||||
{
|
||||
"Clone YCbCr 420",
|
||||
&image.YCbCr{
|
||||
Y: []uint8{0x4c, 0x69, 0x1d, 0xb1, 0x96, 0xe2, 0x26, 0x34, 0xe, 0x59, 0x4b, 0x71, 0x0, 0x4c, 0x99, 0xff},
|
||||
Cb: []uint8{0x01, 0xaa, 0x80, 0x80},
|
||||
Cr: []uint8{0x95, 0xb5, 0x80, 0x80},
|
||||
YStride: 4, CStride: 2,
|
||||
SubsampleRatio: image.YCbCrSubsampleRatio420,
|
||||
Rect: image.Rectangle{Min: image.Point{X: 0, Y: 0}, Max: image.Point{X: 4, Y: 4}},
|
||||
},
|
||||
&image.NRGBA{
|
||||
Pix: []uint8{0x69, 0x69, 0x0, 0xff, 0x86, 0x86, 0x0, 0xff, 0x67, 0x0, 0x67, 0xff, 0xfb, 0x7d, 0xfb, 0xff, 0xb3, 0xb3, 0x0, 0xff, 0xff, 0xff, 0x1, 0xff, 0x70, 0x0, 0x70, 0xff, 0x7e, 0x0, 0x7e, 0xff, 0xe, 0xe, 0xe, 0xff, 0x59, 0x59, 0x59, 0xff, 0x4b, 0x4b, 0x4b, 0xff, 0x71, 0x71, 0x71, 0xff, 0x0, 0x0, 0x0, 0xff, 0x4c, 0x4c, 0x4c, 0xff, 0x99, 0x99, 0x99, 0xff, 0xff, 0xff, 0xff, 0xff},
|
||||
Stride: 16,
|
||||
Rect: image.Rectangle{Min: image.Point{X: 0, Y: 0}, Max: image.Point{X: 4, Y: 4}},
|
||||
},
|
||||
},
|
||||
{
|
||||
"Clone Paletted",
|
||||
&image.Paletted{
|
||||
Rect: image.Rect(-1, -1, 5, 0),
|
||||
Stride: 6 * 1,
|
||||
Palette: color.Palette{
|
||||
color.NRGBA{R: 0x00, G: 0x00, B: 0x00, A: 0xff},
|
||||
color.NRGBA{R: 0xff, G: 0xff, B: 0xff, A: 0xff},
|
||||
color.NRGBA{R: 0x7f, G: 0x7f, B: 0x7f, A: 0xff},
|
||||
color.NRGBA{R: 0x7f, G: 0x00, B: 0x00, A: 0xff},
|
||||
color.NRGBA{R: 0x00, G: 0x7f, B: 0x00, A: 0xff},
|
||||
color.NRGBA{R: 0x00, G: 0x00, B: 0x7f, A: 0xff},
|
||||
},
|
||||
Pix: []uint8{0x0, 0x1, 0x2, 0x3, 0x4, 0x5},
|
||||
},
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 6, 1),
|
||||
Stride: 6 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x00, 0x00, 0xff,
|
||||
0xff, 0xff, 0xff, 0xff,
|
||||
0x7f, 0x7f, 0x7f, 0xff,
|
||||
0x7f, 0x00, 0x00, 0xff,
|
||||
0x00, 0x7f, 0x00, 0xff,
|
||||
0x00, 0x00, 0x7f, 0xff,
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, d := range td {
|
||||
got := Clone(d.src)
|
||||
want := d.want
|
||||
|
||||
delta := 0
|
||||
if _, ok := d.src.(*image.YCbCr); ok {
|
||||
delta = 1
|
||||
}
|
||||
|
||||
if !compareNRGBA(got, want, delta) {
|
||||
t.Errorf("test [%s] failed: %#v", d.desc, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
6
vendor/github.com/disintegration/imaging/convolution.go
сгенерированный
поставляемый
@@ -58,8 +58,6 @@ func convolve(img image.Image, kernel []float64, options *ConvolveOptions) *imag
|
||||
m = 1
|
||||
case 25:
|
||||
m = 2
|
||||
default:
|
||||
return dst
|
||||
}
|
||||
|
||||
i := 0
|
||||
@@ -72,8 +70,8 @@ func convolve(img image.Image, kernel []float64, options *ConvolveOptions) *imag
|
||||
}
|
||||
}
|
||||
|
||||
parallel(h, func(partStart, partEnd int) {
|
||||
for y := partStart; y < partEnd; y++ {
|
||||
parallel(0, h, func(ys <-chan int) {
|
||||
for y := range ys {
|
||||
for x := 0; x < w; x++ {
|
||||
var r, g, b float64
|
||||
for _, c := range coefs {
|
||||
|
||||
275
vendor/github.com/disintegration/imaging/convolution_test.go
сгенерированный
поставляемый
@@ -1,275 +0,0 @@
|
||||
package imaging
|
||||
|
||||
import (
|
||||
"image"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestConvolve3x3(t *testing.T) {
|
||||
testCases := []struct {
|
||||
desc string
|
||||
src image.Image
|
||||
kernel [9]float64
|
||||
options *ConvolveOptions
|
||||
want *image.NRGBA
|
||||
}{
|
||||
{
|
||||
"Convolve3x3 0x0",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 0, 0),
|
||||
Stride: 0,
|
||||
Pix: []uint8{},
|
||||
},
|
||||
[9]float64{
|
||||
0, 0, 0,
|
||||
0, 1, 0,
|
||||
0, 0, 0,
|
||||
},
|
||||
nil,
|
||||
&image.NRGBA{Rect: image.Rect(0, 0, 0, 0)},
|
||||
},
|
||||
{
|
||||
"Convolve3x3 4x4 identity",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 3, 3),
|
||||
Stride: 4 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
|
||||
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
|
||||
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f,
|
||||
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f,
|
||||
},
|
||||
},
|
||||
[9]float64{
|
||||
0, 0, 0,
|
||||
0, 1, 0,
|
||||
0, 0, 0,
|
||||
},
|
||||
nil,
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 4, 4),
|
||||
Stride: 4 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
|
||||
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
|
||||
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f,
|
||||
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
"Convolve3x3 4x4 abs",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 3, 3),
|
||||
Stride: 4 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
|
||||
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
|
||||
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f,
|
||||
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f,
|
||||
},
|
||||
},
|
||||
[9]float64{
|
||||
0, 0, 0,
|
||||
0, -1, 0,
|
||||
0, 0, 0,
|
||||
},
|
||||
&ConvolveOptions{Abs: true},
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 4, 4),
|
||||
Stride: 4 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
|
||||
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
|
||||
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f,
|
||||
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
"Convolve3x3 4x4 bias",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 3, 3),
|
||||
Stride: 4 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
|
||||
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
|
||||
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f,
|
||||
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f,
|
||||
},
|
||||
},
|
||||
[9]float64{
|
||||
0, 0, 0,
|
||||
0, 1, 0,
|
||||
0, 0, 0,
|
||||
},
|
||||
&ConvolveOptions{Bias: 0x10},
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 4, 4),
|
||||
Stride: 4 * 4,
|
||||
Pix: []uint8{
|
||||
0x10, 0x11, 0x12, 0x03, 0x14, 0x15, 0x16, 0x07, 0x18, 0x19, 0x1a, 0x0b, 0x1c, 0x1d, 0x1e, 0x0f,
|
||||
0x20, 0x21, 0x22, 0x13, 0x24, 0x25, 0x26, 0x17, 0x28, 0x29, 0x2a, 0x1b, 0x2c, 0x2d, 0x2e, 0x1f,
|
||||
0x30, 0x31, 0x32, 0x23, 0x34, 0x35, 0x36, 0x27, 0x38, 0x39, 0x3a, 0x2b, 0x3c, 0x3d, 0x3e, 0x2f,
|
||||
0x40, 0x41, 0x42, 0x33, 0x44, 0x45, 0x46, 0x37, 0x48, 0x49, 0x4a, 0x3b, 0x4c, 0x4d, 0x4e, 0x3f,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
"Convolve3x3 4x4 norm",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 3, 3),
|
||||
Stride: 4 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
|
||||
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
|
||||
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f,
|
||||
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f,
|
||||
},
|
||||
},
|
||||
[9]float64{
|
||||
1, 1, 1,
|
||||
1, 1, 1,
|
||||
1, 1, 1,
|
||||
},
|
||||
&ConvolveOptions{Normalize: true},
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 4, 4),
|
||||
Stride: 4 * 4,
|
||||
Pix: []uint8{
|
||||
0x07, 0x08, 0x09, 0x03, 0x09, 0x0a, 0x0b, 0x07, 0x0d, 0x0e, 0x0f, 0x0b, 0x10, 0x11, 0x12, 0x0f,
|
||||
0x11, 0x12, 0x13, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1b, 0x1c, 0x1d, 0x1f,
|
||||
0x21, 0x22, 0x23, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2b, 0x2c, 0x2d, 0x2f,
|
||||
0x2c, 0x2d, 0x2e, 0x33, 0x2f, 0x30, 0x31, 0x37, 0x33, 0x34, 0x35, 0x3b, 0x35, 0x36, 0x37, 0x3f,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
"Convolve3x3 3x3 laplacian",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 2, 2),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x01, 0x01, 0xff, 0x00, 0x01, 0x02, 0xff, 0x00, 0x01, 0x03, 0xff,
|
||||
0x00, 0x01, 0x04, 0xff, 0x10, 0x10, 0x10, 0xff, 0x00, 0x01, 0x05, 0xff,
|
||||
0x00, 0x01, 0x06, 0xff, 0x00, 0x01, 0x07, 0xff, 0x00, 0x01, 0x08, 0xff,
|
||||
},
|
||||
},
|
||||
[9]float64{
|
||||
-1, -1, -1,
|
||||
-1, 8, -1,
|
||||
-1, -1, -1,
|
||||
},
|
||||
nil,
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 3, 3),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0x00, 0xff,
|
||||
0x00, 0x00, 0x00, 0xff, 0x80, 0x78, 0x5c, 0xff, 0x00, 0x00, 0x00, 0xff,
|
||||
0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0x00, 0xff,
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range testCases {
|
||||
got := Convolve3x3(tc.src, tc.kernel, tc.options)
|
||||
want := tc.want
|
||||
if !compareNRGBA(got, want, 0) {
|
||||
t.Errorf("test [%s] failed: want %#v got %#v", tc.desc, want, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestConvolve5x5(t *testing.T) {
|
||||
testCases := []struct {
|
||||
desc string
|
||||
src image.Image
|
||||
kernel [25]float64
|
||||
options *ConvolveOptions
|
||||
want *image.NRGBA
|
||||
}{
|
||||
{
|
||||
"Convolve5x5 4x4 translate",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 3, 3),
|
||||
Stride: 4 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
|
||||
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
|
||||
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f,
|
||||
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f,
|
||||
},
|
||||
},
|
||||
[25]float64{
|
||||
0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 1,
|
||||
},
|
||||
nil,
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 4, 4),
|
||||
Stride: 4 * 4,
|
||||
Pix: []uint8{
|
||||
0x28, 0x29, 0x2a, 0x03, 0x2c, 0x2d, 0x2e, 0x07, 0x2c, 0x2d, 0x2e, 0x0b, 0x2c, 0x2d, 0x2e, 0x0f,
|
||||
0x38, 0x39, 0x3a, 0x13, 0x3c, 0x3d, 0x3e, 0x17, 0x3c, 0x3d, 0x3e, 0x1b, 0x3c, 0x3d, 0x3e, 0x1f,
|
||||
0x38, 0x39, 0x3a, 0x23, 0x3c, 0x3d, 0x3e, 0x27, 0x3c, 0x3d, 0x3e, 0x2b, 0x3c, 0x3d, 0x3e, 0x2f,
|
||||
0x38, 0x39, 0x3a, 0x33, 0x3c, 0x3d, 0x3e, 0x37, 0x3c, 0x3d, 0x3e, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f,
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range testCases {
|
||||
got := Convolve5x5(tc.src, tc.kernel, tc.options)
|
||||
want := tc.want
|
||||
if !compareNRGBA(got, want, 0) {
|
||||
t.Errorf("test [%s] failed: want %#v got %#v", tc.desc, want, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkConvolve3x3(b *testing.B) {
|
||||
b.StopTimer()
|
||||
img, err := Open("testdata/lena_512.png")
|
||||
if err != nil {
|
||||
b.Fatalf("Open: %v", err)
|
||||
}
|
||||
b.StartTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
Convolve3x3(
|
||||
img,
|
||||
[9]float64{
|
||||
-1, -1, 0,
|
||||
-1, 0, 1,
|
||||
0, 1, 1,
|
||||
},
|
||||
nil,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkConvolve5x5(b *testing.B) {
|
||||
b.StopTimer()
|
||||
img, err := Open("testdata/lena_512.png")
|
||||
if err != nil {
|
||||
b.Fatalf("Open: %v", err)
|
||||
}
|
||||
b.StartTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
Convolve5x5(
|
||||
img,
|
||||
[25]float64{
|
||||
-1, -1, -1, -1, 0,
|
||||
-1, -1, -1, 0, 1,
|
||||
-1, -1, 0, 1, 1,
|
||||
-1, 0, 1, 1, 1,
|
||||
0, 1, 1, 1, 1,
|
||||
},
|
||||
nil,
|
||||
)
|
||||
}
|
||||
}
|
||||
7
vendor/github.com/disintegration/imaging/doc.go
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,7 @@
|
||||
/*
|
||||
Package imaging provides basic image processing functions (resize, rotate, crop, brightness/contrast adjustments, etc.).
|
||||
|
||||
All the image processing functions provided by the package accept any image type that implements image.Image interface
|
||||
as an input, and return a new image of *image.NRGBA type (32bit RGBA colors, not premultiplied by alpha).
|
||||
*/
|
||||
package imaging
|
||||
174
vendor/github.com/disintegration/imaging/effects.go
сгенерированный
поставляемый
@@ -18,11 +18,9 @@ func gaussianBlurKernel(x, sigma float64) float64 {
|
||||
//
|
||||
func Blur(img image.Image, sigma float64) *image.NRGBA {
|
||||
if sigma <= 0 {
|
||||
// sigma parameter must be positive!
|
||||
return Clone(img)
|
||||
}
|
||||
|
||||
src := toNRGBA(img)
|
||||
radius := int(math.Ceil(sigma * 3.0))
|
||||
kernel := make([]float64, radius+1)
|
||||
|
||||
@@ -30,54 +28,50 @@ func Blur(img image.Image, sigma float64) *image.NRGBA {
|
||||
kernel[i] = gaussianBlurKernel(float64(i), sigma)
|
||||
}
|
||||
|
||||
var dst *image.NRGBA
|
||||
dst = blurHorizontal(src, kernel)
|
||||
dst = blurVertical(dst, kernel)
|
||||
|
||||
return dst
|
||||
return blurVertical(blurHorizontal(img, kernel), kernel)
|
||||
}
|
||||
|
||||
func blurHorizontal(src *image.NRGBA, kernel []float64) *image.NRGBA {
|
||||
func blurHorizontal(img image.Image, kernel []float64) *image.NRGBA {
|
||||
src := newScanner(img)
|
||||
dst := image.NewNRGBA(image.Rect(0, 0, src.w, src.h))
|
||||
radius := len(kernel) - 1
|
||||
width := src.Bounds().Max.X
|
||||
height := src.Bounds().Max.Y
|
||||
|
||||
dst := image.NewNRGBA(image.Rect(0, 0, width, height))
|
||||
parallel(0, src.h, func(ys <-chan int) {
|
||||
scanLine := make([]uint8, src.w*4)
|
||||
for y := range ys {
|
||||
src.scan(0, y, src.w, y+1, scanLine)
|
||||
for x := 0; x < src.w; x++ {
|
||||
min := x - radius
|
||||
if min < 0 {
|
||||
min = 0
|
||||
}
|
||||
max := x + radius
|
||||
if max > src.w-1 {
|
||||
max = src.w - 1
|
||||
}
|
||||
|
||||
parallel(width, func(partStart, partEnd int) {
|
||||
for x := partStart; x < partEnd; x++ {
|
||||
start := x - radius
|
||||
if start < 0 {
|
||||
start = 0
|
||||
}
|
||||
|
||||
end := x + radius
|
||||
if end > width-1 {
|
||||
end = width - 1
|
||||
}
|
||||
|
||||
weightSum := 0.0
|
||||
for ix := start; ix <= end; ix++ {
|
||||
weightSum += kernel[absint(x-ix)]
|
||||
}
|
||||
|
||||
for y := 0; y < height; y++ {
|
||||
var r, g, b, a float64
|
||||
for ix := start; ix <= end; ix++ {
|
||||
var r, g, b, a, wsum float64
|
||||
for ix := min; ix <= max; ix++ {
|
||||
i := ix * 4
|
||||
weight := kernel[absint(x-ix)]
|
||||
i := y*src.Stride + ix*4
|
||||
wa := float64(src.Pix[i+3]) * weight
|
||||
r += float64(src.Pix[i+0]) * wa
|
||||
g += float64(src.Pix[i+1]) * wa
|
||||
b += float64(src.Pix[i+2]) * wa
|
||||
wsum += weight
|
||||
wa := float64(scanLine[i+3]) * weight
|
||||
r += float64(scanLine[i+0]) * wa
|
||||
g += float64(scanLine[i+1]) * wa
|
||||
b += float64(scanLine[i+2]) * wa
|
||||
a += wa
|
||||
}
|
||||
if a != 0 {
|
||||
r /= a
|
||||
g /= a
|
||||
b /= a
|
||||
}
|
||||
|
||||
j := y*dst.Stride + x*4
|
||||
dst.Pix[j+0] = clamp(r / a)
|
||||
dst.Pix[j+1] = clamp(g / a)
|
||||
dst.Pix[j+2] = clamp(b / a)
|
||||
dst.Pix[j+3] = clamp(a / weightSum)
|
||||
dst.Pix[j+0] = clamp(r)
|
||||
dst.Pix[j+1] = clamp(g)
|
||||
dst.Pix[j+2] = clamp(b)
|
||||
dst.Pix[j+3] = clamp(a / wsum)
|
||||
}
|
||||
}
|
||||
})
|
||||
@@ -85,47 +79,47 @@ func blurHorizontal(src *image.NRGBA, kernel []float64) *image.NRGBA {
|
||||
return dst
|
||||
}
|
||||
|
||||
func blurVertical(src *image.NRGBA, kernel []float64) *image.NRGBA {
|
||||
func blurVertical(img image.Image, kernel []float64) *image.NRGBA {
|
||||
src := newScanner(img)
|
||||
dst := image.NewNRGBA(image.Rect(0, 0, src.w, src.h))
|
||||
radius := len(kernel) - 1
|
||||
width := src.Bounds().Max.X
|
||||
height := src.Bounds().Max.Y
|
||||
|
||||
dst := image.NewNRGBA(image.Rect(0, 0, width, height))
|
||||
parallel(0, src.w, func(xs <-chan int) {
|
||||
scanLine := make([]uint8, src.h*4)
|
||||
for x := range xs {
|
||||
src.scan(x, 0, x+1, src.h, scanLine)
|
||||
for y := 0; y < src.h; y++ {
|
||||
min := y - radius
|
||||
if min < 0 {
|
||||
min = 0
|
||||
}
|
||||
max := y + radius
|
||||
if max > src.h-1 {
|
||||
max = src.h - 1
|
||||
}
|
||||
|
||||
parallel(height, func(partStart, partEnd int) {
|
||||
for y := partStart; y < partEnd; y++ {
|
||||
start := y - radius
|
||||
if start < 0 {
|
||||
start = 0
|
||||
}
|
||||
|
||||
end := y + radius
|
||||
if end > height-1 {
|
||||
end = height - 1
|
||||
}
|
||||
|
||||
weightSum := 0.0
|
||||
for iy := start; iy <= end; iy++ {
|
||||
weightSum += kernel[absint(y-iy)]
|
||||
}
|
||||
|
||||
for x := 0; x < width; x++ {
|
||||
var r, g, b, a float64
|
||||
for iy := start; iy <= end; iy++ {
|
||||
var r, g, b, a, wsum float64
|
||||
for iy := min; iy <= max; iy++ {
|
||||
i := iy * 4
|
||||
weight := kernel[absint(y-iy)]
|
||||
i := iy*src.Stride + x*4
|
||||
wa := float64(src.Pix[i+3]) * weight
|
||||
r += float64(src.Pix[i+0]) * wa
|
||||
g += float64(src.Pix[i+1]) * wa
|
||||
b += float64(src.Pix[i+2]) * wa
|
||||
wsum += weight
|
||||
wa := float64(scanLine[i+3]) * weight
|
||||
r += float64(scanLine[i+0]) * wa
|
||||
g += float64(scanLine[i+1]) * wa
|
||||
b += float64(scanLine[i+2]) * wa
|
||||
a += wa
|
||||
}
|
||||
if a != 0 {
|
||||
r /= a
|
||||
g /= a
|
||||
b /= a
|
||||
}
|
||||
|
||||
j := y*dst.Stride + x*4
|
||||
dst.Pix[j+0] = clamp(r / a)
|
||||
dst.Pix[j+1] = clamp(g / a)
|
||||
dst.Pix[j+2] = clamp(b / a)
|
||||
dst.Pix[j+3] = clamp(a / weightSum)
|
||||
dst.Pix[j+0] = clamp(r)
|
||||
dst.Pix[j+1] = clamp(g)
|
||||
dst.Pix[j+2] = clamp(b)
|
||||
dst.Pix[j+3] = clamp(a / wsum)
|
||||
}
|
||||
}
|
||||
})
|
||||
@@ -142,31 +136,27 @@ func blurVertical(src *image.NRGBA, kernel []float64) *image.NRGBA {
|
||||
//
|
||||
func Sharpen(img image.Image, sigma float64) *image.NRGBA {
|
||||
if sigma <= 0 {
|
||||
// sigma parameter must be positive!
|
||||
return Clone(img)
|
||||
}
|
||||
|
||||
src := toNRGBA(img)
|
||||
src := newScanner(img)
|
||||
dst := image.NewNRGBA(image.Rect(0, 0, src.w, src.h))
|
||||
blurred := Blur(img, sigma)
|
||||
|
||||
width := src.Bounds().Max.X
|
||||
height := src.Bounds().Max.Y
|
||||
dst := image.NewNRGBA(image.Rect(0, 0, width, height))
|
||||
|
||||
parallel(height, func(partStart, partEnd int) {
|
||||
for y := partStart; y < partEnd; y++ {
|
||||
for x := 0; x < width; x++ {
|
||||
i := y*src.Stride + x*4
|
||||
for j := 0; j < 4; j++ {
|
||||
k := i + j
|
||||
val := int(src.Pix[k])<<1 - int(blurred.Pix[k])
|
||||
if val < 0 {
|
||||
val = 0
|
||||
} else if val > 255 {
|
||||
val = 255
|
||||
}
|
||||
dst.Pix[k] = uint8(val)
|
||||
parallel(0, src.h, func(ys <-chan int) {
|
||||
scanLine := make([]uint8, src.w*4)
|
||||
for y := range ys {
|
||||
src.scan(0, y, src.w, y+1, scanLine)
|
||||
j := y * dst.Stride
|
||||
for i := 0; i < src.w*4; i++ {
|
||||
val := int(scanLine[i])<<1 - int(blurred.Pix[j])
|
||||
if val < 0 {
|
||||
val = 0
|
||||
} else if val > 0xff {
|
||||
val = 0xff
|
||||
}
|
||||
dst.Pix[j] = uint8(val)
|
||||
j++
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
254
vendor/github.com/disintegration/imaging/effects_test.go
сгенерированный
поставляемый
@@ -1,254 +0,0 @@
|
||||
package imaging
|
||||
|
||||
import (
|
||||
"image"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestBlur(t *testing.T) {
|
||||
td := []struct {
|
||||
desc string
|
||||
src image.Image
|
||||
sigma float64
|
||||
want *image.NRGBA
|
||||
}{
|
||||
{
|
||||
"Blur 3x3 0",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 2, 2),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00, 0x66, 0xaa, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
},
|
||||
},
|
||||
0.0,
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 3, 3),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00, 0x66, 0xaa, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
"Blur 3x3 0.5",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 2, 2),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00, 0x66, 0xaa, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
},
|
||||
},
|
||||
0.5,
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 3, 3),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0x66, 0xaa, 0xff, 0x04, 0x66, 0xaa, 0xff, 0x18, 0x66, 0xaa, 0xff, 0x04,
|
||||
0x66, 0xaa, 0xff, 0x18, 0x66, 0xaa, 0xff, 0x9e, 0x66, 0xaa, 0xff, 0x18,
|
||||
0x66, 0xaa, 0xff, 0x04, 0x66, 0xaa, 0xff, 0x18, 0x66, 0xaa, 0xff, 0x04,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
"Blur 3x3 10",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 2, 2),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00, 0x66, 0xaa, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
},
|
||||
},
|
||||
10,
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 3, 3),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0x66, 0xaa, 0xff, 0x1c, 0x66, 0xaa, 0xff, 0x1c, 0x66, 0xaa, 0xff, 0x1c,
|
||||
0x66, 0xaa, 0xff, 0x1c, 0x66, 0xaa, 0xff, 0x1c, 0x66, 0xaa, 0xff, 0x1c,
|
||||
0x66, 0xaa, 0xff, 0x1c, 0x66, 0xaa, 0xff, 0x1c, 0x66, 0xaa, 0xff, 0x1c,
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
for _, d := range td {
|
||||
got := Blur(d.src, d.sigma)
|
||||
want := d.want
|
||||
if !compareNRGBA(got, want, 0) {
|
||||
t.Errorf("test [%s] failed: %#v", d.desc, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestBlurGolden(t *testing.T) {
|
||||
src, err := Open("testdata/lena_128.png")
|
||||
if err != nil {
|
||||
t.Errorf("Open: %v", err)
|
||||
}
|
||||
for name, sigma := range map[string]float64{
|
||||
"out_blur_0.5.png": 0.5,
|
||||
"out_blur_1.5.png": 1.5,
|
||||
} {
|
||||
got := Blur(src, sigma)
|
||||
want, err := Open("testdata/" + name)
|
||||
if err != nil {
|
||||
t.Errorf("Open: %v", err)
|
||||
}
|
||||
if !compareNRGBA(got, toNRGBA(want), 0) {
|
||||
t.Errorf("resulting image differs from golden: %s", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkBlur(b *testing.B) {
|
||||
b.StopTimer()
|
||||
img, err := Open("testdata/lena_512.png")
|
||||
if err != nil {
|
||||
b.Fatalf("Open: %v", err)
|
||||
}
|
||||
b.StartTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
Blur(img, 3)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSharpen(t *testing.T) {
|
||||
td := []struct {
|
||||
desc string
|
||||
src image.Image
|
||||
sigma float64
|
||||
want *image.NRGBA
|
||||
}{
|
||||
{
|
||||
"Sharpen 3x3 0",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 2, 2),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66,
|
||||
0x66, 0x66, 0x66, 0x66, 0x77, 0x77, 0x77, 0x77, 0x66, 0x66, 0x66, 0x66,
|
||||
0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66,
|
||||
},
|
||||
},
|
||||
0,
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 3, 3),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66,
|
||||
0x66, 0x66, 0x66, 0x66, 0x77, 0x77, 0x77, 0x77, 0x66, 0x66, 0x66, 0x66,
|
||||
0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
"Sharpen 3x3 0.5",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 2, 2),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66,
|
||||
0x66, 0x66, 0x66, 0x66, 0x77, 0x77, 0x77, 0x77, 0x66, 0x66, 0x66, 0x66,
|
||||
0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66,
|
||||
},
|
||||
},
|
||||
0.5,
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 3, 3),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0x66, 0x66, 0x66, 0x66, 0x64, 0x64, 0x64, 0x64, 0x66, 0x66, 0x66, 0x66,
|
||||
0x64, 0x64, 0x64, 0x64, 0x7d, 0x7d, 0x7d, 0x7e, 0x64, 0x64, 0x64, 0x64,
|
||||
0x66, 0x66, 0x66, 0x66, 0x64, 0x64, 0x64, 0x64, 0x66, 0x66, 0x66, 0x66,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
"Sharpen 3x3 100",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 2, 2),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66,
|
||||
0x66, 0x66, 0x66, 0x66, 0x77, 0x77, 0x77, 0x77, 0x66, 0x66, 0x66, 0x66,
|
||||
0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66,
|
||||
},
|
||||
},
|
||||
100,
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 3, 3),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0x64, 0x64, 0x64, 0x64, 0x64, 0x64, 0x64, 0x64, 0x64, 0x64, 0x64, 0x64,
|
||||
0x64, 0x64, 0x64, 0x64, 0x86, 0x86, 0x86, 0x86, 0x64, 0x64, 0x64, 0x64,
|
||||
0x64, 0x64, 0x64, 0x64, 0x64, 0x64, 0x64, 0x64, 0x64, 0x64, 0x64, 0x64,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
"Sharpen 3x1 10",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 2, 0),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
10,
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 3, 1),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
for _, d := range td {
|
||||
got := Sharpen(d.src, d.sigma)
|
||||
want := d.want
|
||||
if !compareNRGBA(got, want, 0) {
|
||||
t.Errorf("test [%s] failed: %#v", d.desc, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSharpenGolden(t *testing.T) {
|
||||
src, err := Open("testdata/lena_128.png")
|
||||
if err != nil {
|
||||
t.Errorf("Open: %v", err)
|
||||
}
|
||||
for name, sigma := range map[string]float64{
|
||||
"out_sharpen_0.5.png": 0.5,
|
||||
"out_sharpen_1.5.png": 1.5,
|
||||
} {
|
||||
got := Sharpen(src, sigma)
|
||||
want, err := Open("testdata/" + name)
|
||||
if err != nil {
|
||||
t.Errorf("Open: %v", err)
|
||||
}
|
||||
if !compareNRGBA(got, toNRGBA(want), 0) {
|
||||
t.Errorf("resulting image differs from golden: %s", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkSharpen(b *testing.B) {
|
||||
b.StopTimer()
|
||||
img, err := Open("testdata/lena_512.png")
|
||||
if err != nil {
|
||||
b.Fatalf("Open: %v", err)
|
||||
}
|
||||
b.StartTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
Sharpen(img, 3)
|
||||
}
|
||||
}
|
||||
58
vendor/github.com/disintegration/imaging/example_test.go
сгенерированный
поставляемый
@@ -1,58 +0,0 @@
|
||||
package imaging_test
|
||||
|
||||
import (
|
||||
"image"
|
||||
"image/color"
|
||||
"log"
|
||||
|
||||
"github.com/disintegration/imaging"
|
||||
)
|
||||
|
||||
func Example() {
|
||||
// Open the test image.
|
||||
src, err := imaging.Open("testdata/lena_512.png")
|
||||
if err != nil {
|
||||
log.Fatalf("Open failed: %v", err)
|
||||
}
|
||||
|
||||
// Crop the original image to 350x350px size using the center anchor.
|
||||
src = imaging.CropAnchor(src, 350, 350, imaging.Center)
|
||||
|
||||
// Resize the cropped image to width = 256px preserving the aspect ratio.
|
||||
src = imaging.Resize(src, 256, 0, imaging.Lanczos)
|
||||
|
||||
// Create a blurred version of the image.
|
||||
img1 := imaging.Blur(src, 2)
|
||||
|
||||
// Create a grayscale version of the image with higher contrast and sharpness.
|
||||
img2 := imaging.Grayscale(src)
|
||||
img2 = imaging.AdjustContrast(img2, 20)
|
||||
img2 = imaging.Sharpen(img2, 2)
|
||||
|
||||
// Create an inverted version of the image.
|
||||
img3 := imaging.Invert(src)
|
||||
|
||||
// Create an embossed version of the image using a convolution filter.
|
||||
img4 := imaging.Convolve3x3(
|
||||
src,
|
||||
[9]float64{
|
||||
-1, -1, 0,
|
||||
-1, 1, 1,
|
||||
0, 1, 1,
|
||||
},
|
||||
nil,
|
||||
)
|
||||
|
||||
// Create a new image and paste the four produced images into it.
|
||||
dst := imaging.New(512, 512, color.NRGBA{0, 0, 0, 0})
|
||||
dst = imaging.Paste(dst, img1, image.Pt(0, 0))
|
||||
dst = imaging.Paste(dst, img2, image.Pt(0, 256))
|
||||
dst = imaging.Paste(dst, img3, image.Pt(256, 0))
|
||||
dst = imaging.Paste(dst, img4, image.Pt(256, 256))
|
||||
|
||||
// Save the resulting image using JPEG format.
|
||||
err = imaging.Save(dst, "testdata/out_example.jpg")
|
||||
if err != nil {
|
||||
log.Fatalf("Save failed: %v", err)
|
||||
}
|
||||
}
|
||||
134
vendor/github.com/disintegration/imaging/helpers.go
сгенерированный
поставляемый
@@ -1,15 +1,10 @@
|
||||
// Package imaging provides basic image manipulation functions (resize, rotate, flip, crop, etc.).
|
||||
// This package is based on the standard Go image package and works best along with it.
|
||||
//
|
||||
// Image manipulation functions provided by the package take any image type
|
||||
// that implements `image.Image` interface as an input, and return a new image of
|
||||
// `*image.NRGBA` type (32bit RGBA colors, not premultiplied by alpha).
|
||||
package imaging
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"image"
|
||||
"image/color"
|
||||
"image/draw"
|
||||
"image/gif"
|
||||
"image/jpeg"
|
||||
"image/png"
|
||||
@@ -56,32 +51,48 @@ var (
|
||||
ErrUnsupportedFormat = errors.New("imaging: unsupported image format")
|
||||
)
|
||||
|
||||
type fileSystem interface {
|
||||
Create(string) (io.WriteCloser, error)
|
||||
Open(string) (io.ReadCloser, error)
|
||||
}
|
||||
|
||||
type localFS struct{}
|
||||
|
||||
func (localFS) Create(name string) (io.WriteCloser, error) { return os.Create(name) }
|
||||
func (localFS) Open(name string) (io.ReadCloser, error) { return os.Open(name) }
|
||||
|
||||
var fs fileSystem = localFS{}
|
||||
|
||||
// Decode reads an image from r.
|
||||
func Decode(r io.Reader) (image.Image, error) {
|
||||
img, _, err := image.Decode(r)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return toNRGBA(img), nil
|
||||
return img, err
|
||||
}
|
||||
|
||||
// Open loads an image from file
|
||||
func Open(filename string) (image.Image, error) {
|
||||
file, err := os.Open(filename)
|
||||
file, err := fs.Open(filename)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer file.Close()
|
||||
img, err := Decode(file)
|
||||
return img, err
|
||||
return Decode(file)
|
||||
}
|
||||
|
||||
type encodeConfig struct {
|
||||
jpegQuality int
|
||||
jpegQuality int
|
||||
gifNumColors int
|
||||
gifQuantizer draw.Quantizer
|
||||
gifDrawer draw.Drawer
|
||||
pngCompressionLevel png.CompressionLevel
|
||||
}
|
||||
|
||||
var defaultEncodeConfig = encodeConfig{
|
||||
jpegQuality: 95,
|
||||
jpegQuality: 95,
|
||||
gifNumColors: 256,
|
||||
gifQuantizer: nil,
|
||||
gifDrawer: nil,
|
||||
pngCompressionLevel: png.DefaultCompression,
|
||||
}
|
||||
|
||||
// EncodeOption sets an optional parameter for the Encode and Save functions.
|
||||
@@ -95,6 +106,38 @@ func JPEGQuality(quality int) EncodeOption {
|
||||
}
|
||||
}
|
||||
|
||||
// GIFNumColors returns an EncodeOption that sets the maximum number of colors
|
||||
// used in the GIF-encoded image. It ranges from 1 to 256. Default is 256.
|
||||
func GIFNumColors(numColors int) EncodeOption {
|
||||
return func(c *encodeConfig) {
|
||||
c.gifNumColors = numColors
|
||||
}
|
||||
}
|
||||
|
||||
// GIFQuantizer returns an EncodeOption that sets the quantizer that is used to produce
|
||||
// a palette of the GIF-encoded image.
|
||||
func GIFQuantizer(quantizer draw.Quantizer) EncodeOption {
|
||||
return func(c *encodeConfig) {
|
||||
c.gifQuantizer = quantizer
|
||||
}
|
||||
}
|
||||
|
||||
// GIFDrawer returns an EncodeOption that sets the drawer that is used to convert
|
||||
// the source image to the desired palette of the GIF-encoded image.
|
||||
func GIFDrawer(drawer draw.Drawer) EncodeOption {
|
||||
return func(c *encodeConfig) {
|
||||
c.gifDrawer = drawer
|
||||
}
|
||||
}
|
||||
|
||||
// PNGCompressionLevel returns an EncodeOption that sets the compression level
|
||||
// of the PNG-encoded image. Default is png.DefaultCompression.
|
||||
func PNGCompressionLevel(level png.CompressionLevel) EncodeOption {
|
||||
return func(c *encodeConfig) {
|
||||
c.pngCompressionLevel = level
|
||||
}
|
||||
}
|
||||
|
||||
// Encode writes the image img to w in the specified format (JPEG, PNG, GIF, TIFF or BMP).
|
||||
func Encode(w io.Writer, img image.Image, format Format, opts ...EncodeOption) error {
|
||||
cfg := defaultEncodeConfig
|
||||
@@ -122,13 +165,22 @@ func Encode(w io.Writer, img image.Image, format Format, opts ...EncodeOption) e
|
||||
}
|
||||
|
||||
case PNG:
|
||||
err = png.Encode(w, img)
|
||||
enc := png.Encoder{CompressionLevel: cfg.pngCompressionLevel}
|
||||
err = enc.Encode(w, img)
|
||||
|
||||
case GIF:
|
||||
err = gif.Encode(w, img, &gif.Options{NumColors: 256})
|
||||
err = gif.Encode(w, img, &gif.Options{
|
||||
NumColors: cfg.gifNumColors,
|
||||
Quantizer: cfg.gifQuantizer,
|
||||
Drawer: cfg.gifDrawer,
|
||||
})
|
||||
|
||||
case TIFF:
|
||||
err = tiff.Encode(w, img, &tiff.Options{Compression: tiff.Deflate, Predictor: true})
|
||||
|
||||
case BMP:
|
||||
err = bmp.Encode(w, img)
|
||||
|
||||
default:
|
||||
err = ErrUnsupportedFormat
|
||||
}
|
||||
@@ -163,11 +215,17 @@ func Save(img image.Image, filename string, opts ...EncodeOption) (err error) {
|
||||
return ErrUnsupportedFormat
|
||||
}
|
||||
|
||||
file, err := os.Create(filename)
|
||||
file, err := fs.Create(filename)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
defer func() {
|
||||
cerr := file.Close()
|
||||
if err == nil {
|
||||
err = cerr
|
||||
}
|
||||
}()
|
||||
|
||||
return Encode(file, img, f, opts...)
|
||||
}
|
||||
@@ -185,16 +243,38 @@ func New(width, height int, fillColor color.Color) *image.NRGBA {
|
||||
return dst
|
||||
}
|
||||
|
||||
cs := []uint8{c.R, c.G, c.B, c.A}
|
||||
|
||||
// fill the first row
|
||||
// Fill the first row.
|
||||
i := 0
|
||||
for x := 0; x < width; x++ {
|
||||
copy(dst.Pix[x*4:(x+1)*4], cs)
|
||||
}
|
||||
// copy the first row to other rows
|
||||
for y := 1; y < height; y++ {
|
||||
copy(dst.Pix[y*dst.Stride:y*dst.Stride+width*4], dst.Pix[0:width*4])
|
||||
dst.Pix[i+0] = c.R
|
||||
dst.Pix[i+1] = c.G
|
||||
dst.Pix[i+2] = c.B
|
||||
dst.Pix[i+3] = c.A
|
||||
i += 4
|
||||
}
|
||||
|
||||
// Copy the first row to other rows.
|
||||
size := width * 4
|
||||
parallel(1, height, func(ys <-chan int) {
|
||||
for y := range ys {
|
||||
i = y * dst.Stride
|
||||
copy(dst.Pix[i:i+size], dst.Pix[0:size])
|
||||
}
|
||||
})
|
||||
|
||||
return dst
|
||||
}
|
||||
|
||||
// Clone returns a copy of the given image.
|
||||
func Clone(img image.Image) *image.NRGBA {
|
||||
src := newScanner(img)
|
||||
dst := image.NewNRGBA(image.Rect(0, 0, src.w, src.h))
|
||||
size := src.w * 4
|
||||
parallel(0, src.h, func(ys <-chan int) {
|
||||
for y := range ys {
|
||||
i := y * dst.Stride
|
||||
src.scan(0, y, src.w, y+1, dst.Pix[i:i+size])
|
||||
}
|
||||
})
|
||||
return dst
|
||||
}
|
||||
|
||||
159
vendor/github.com/disintegration/imaging/helpers_test.go
сгенерированный
поставляемый
@@ -1,159 +0,0 @@
|
||||
package imaging
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"image"
|
||||
"image/color"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func compareNRGBA(img1, img2 *image.NRGBA, delta int) bool {
|
||||
if !img1.Rect.Eq(img2.Rect) {
|
||||
return false
|
||||
}
|
||||
|
||||
if len(img1.Pix) != len(img2.Pix) {
|
||||
return false
|
||||
}
|
||||
|
||||
for i := 0; i < len(img1.Pix); i++ {
|
||||
if absint(int(img1.Pix[i])-int(img2.Pix[i])) > delta {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
func TestEncodeDecode(t *testing.T) {
|
||||
imgWithAlpha := image.NewNRGBA(image.Rect(0, 0, 3, 3))
|
||||
imgWithAlpha.Pix = []uint8{
|
||||
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
|
||||
127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138,
|
||||
244, 245, 246, 247, 248, 249, 250, 252, 252, 253, 254, 255,
|
||||
}
|
||||
|
||||
imgWithoutAlpha := image.NewNRGBA(image.Rect(0, 0, 3, 3))
|
||||
imgWithoutAlpha.Pix = []uint8{
|
||||
0, 1, 2, 255, 4, 5, 6, 255, 8, 9, 10, 255,
|
||||
127, 128, 129, 255, 131, 132, 133, 255, 135, 136, 137, 255,
|
||||
244, 245, 246, 255, 248, 249, 250, 255, 252, 253, 254, 255,
|
||||
}
|
||||
|
||||
for _, format := range []Format{JPEG, PNG, GIF, BMP, TIFF} {
|
||||
img := imgWithoutAlpha
|
||||
if format == PNG {
|
||||
img = imgWithAlpha
|
||||
}
|
||||
|
||||
buf := &bytes.Buffer{}
|
||||
err := Encode(buf, img, format)
|
||||
if err != nil {
|
||||
t.Errorf("fail encoding format %s", format)
|
||||
continue
|
||||
}
|
||||
|
||||
img2, err := Decode(buf)
|
||||
if err != nil {
|
||||
t.Errorf("fail decoding format %s", format)
|
||||
continue
|
||||
}
|
||||
img2cloned := Clone(img2)
|
||||
|
||||
delta := 0
|
||||
if format == JPEG {
|
||||
delta = 3
|
||||
} else if format == GIF {
|
||||
delta = 16
|
||||
}
|
||||
|
||||
if !compareNRGBA(img, img2cloned, delta) {
|
||||
t.Errorf("test [DecodeEncode %s] failed: %#v %#v", format, img, img2cloned)
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
buf := &bytes.Buffer{}
|
||||
err := Encode(buf, imgWithAlpha, JPEG)
|
||||
if err != nil {
|
||||
t.Errorf("failed encoding alpha to JPEG format %s", err)
|
||||
}
|
||||
|
||||
buf = &bytes.Buffer{}
|
||||
err = Encode(buf, imgWithAlpha, Format(100))
|
||||
if err != ErrUnsupportedFormat {
|
||||
t.Errorf("expected ErrUnsupportedFormat")
|
||||
}
|
||||
|
||||
buf = bytes.NewBuffer([]byte("bad data"))
|
||||
_, err = Decode(buf)
|
||||
if err == nil {
|
||||
t.Errorf("decoding bad data, expected error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNew(t *testing.T) {
|
||||
td := []struct {
|
||||
desc string
|
||||
w, h int
|
||||
c color.Color
|
||||
dstBounds image.Rectangle
|
||||
dstPix []uint8
|
||||
}{
|
||||
{
|
||||
"New 1x1 black",
|
||||
1, 1,
|
||||
color.NRGBA{0, 0, 0, 0},
|
||||
image.Rect(0, 0, 1, 1),
|
||||
[]uint8{0x00, 0x00, 0x00, 0x00},
|
||||
},
|
||||
{
|
||||
"New 1x2 red",
|
||||
1, 2,
|
||||
color.NRGBA{255, 0, 0, 255},
|
||||
image.Rect(0, 0, 1, 2),
|
||||
[]uint8{0xff, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0xff},
|
||||
},
|
||||
{
|
||||
"New 2x1 white",
|
||||
2, 1,
|
||||
color.NRGBA{255, 255, 255, 255},
|
||||
image.Rect(0, 0, 2, 1),
|
||||
[]uint8{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff},
|
||||
},
|
||||
{
|
||||
"New 0x0 white",
|
||||
0, 0,
|
||||
color.NRGBA{255, 255, 255, 255},
|
||||
image.Rect(0, 0, 0, 0),
|
||||
nil,
|
||||
},
|
||||
}
|
||||
|
||||
for _, d := range td {
|
||||
got := New(d.w, d.h, d.c)
|
||||
want := image.NewNRGBA(d.dstBounds)
|
||||
want.Pix = d.dstPix
|
||||
if !compareNRGBA(got, want, 0) {
|
||||
t.Errorf("test [%s] failed: %#v", d.desc, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestFormats(t *testing.T) {
|
||||
formatNames := map[Format]string{
|
||||
JPEG: "JPEG",
|
||||
PNG: "PNG",
|
||||
GIF: "GIF",
|
||||
BMP: "BMP",
|
||||
TIFF: "TIFF",
|
||||
Format(-1): "Unsupported",
|
||||
}
|
||||
for format, name := range formatNames {
|
||||
got := format.String()
|
||||
if got != name {
|
||||
t.Errorf("test [Format names] failed: got %#v want %#v", got, name)
|
||||
continue
|
||||
}
|
||||
}
|
||||
}
|
||||
46
vendor/github.com/disintegration/imaging/histogram.go
сгенерированный
поставляемый
@@ -2,6 +2,7 @@ package imaging
|
||||
|
||||
import (
|
||||
"image"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// Histogram returns a normalized histogram of an image.
|
||||
@@ -9,35 +10,42 @@ import (
|
||||
// Resulting histogram is represented as an array of 256 floats, where
|
||||
// histogram[i] is a probability of a pixel being of a particular luminance i.
|
||||
func Histogram(img image.Image) [256]float64 {
|
||||
src := toNRGBA(img)
|
||||
width := src.Bounds().Max.X
|
||||
height := src.Bounds().Max.Y
|
||||
|
||||
var mu sync.Mutex
|
||||
var histogram [256]float64
|
||||
var total float64
|
||||
|
||||
if width == 0 || height == 0 {
|
||||
src := newScanner(img)
|
||||
if src.w == 0 || src.h == 0 {
|
||||
return histogram
|
||||
}
|
||||
|
||||
for y := 0; y < height; y++ {
|
||||
for x := 0; x < width; x++ {
|
||||
i := y*src.Stride + x*4
|
||||
|
||||
r := src.Pix[i+0]
|
||||
g := src.Pix[i+1]
|
||||
b := src.Pix[i+2]
|
||||
|
||||
y := 0.299*float32(r) + 0.587*float32(g) + 0.114*float32(b)
|
||||
|
||||
histogram[int(y+0.5)]++
|
||||
total++
|
||||
parallel(0, src.h, func(ys <-chan int) {
|
||||
var tmpHistogram [256]float64
|
||||
var tmpTotal float64
|
||||
scanLine := make([]uint8, src.w*4)
|
||||
for y := range ys {
|
||||
src.scan(0, y, src.w, y+1, scanLine)
|
||||
i := 0
|
||||
for x := 0; x < src.w; x++ {
|
||||
r := scanLine[i+0]
|
||||
g := scanLine[i+1]
|
||||
b := scanLine[i+2]
|
||||
y := 0.299*float32(r) + 0.587*float32(g) + 0.114*float32(b)
|
||||
tmpHistogram[int(y+0.5)]++
|
||||
tmpTotal++
|
||||
i += 4
|
||||
}
|
||||
}
|
||||
}
|
||||
mu.Lock()
|
||||
for i := 0; i < 256; i++ {
|
||||
histogram[i] += tmpHistogram[i]
|
||||
}
|
||||
total += tmpTotal
|
||||
mu.Unlock()
|
||||
})
|
||||
|
||||
for i := 0; i < 256; i++ {
|
||||
histogram[i] = histogram[i] / total
|
||||
}
|
||||
|
||||
return histogram
|
||||
}
|
||||
|
||||
42
vendor/github.com/disintegration/imaging/histogram_test.go
сгенерированный
поставляемый
@@ -1,42 +0,0 @@
|
||||
package imaging
|
||||
|
||||
import (
|
||||
"image"
|
||||
"image/color"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestHistogram(t *testing.T) {
|
||||
b := image.Rectangle{image.Point{0, 0}, image.Point{2, 2}}
|
||||
|
||||
i1 := image.NewRGBA(b)
|
||||
i1.Set(0, 0, image.Black)
|
||||
i1.Set(1, 0, image.White)
|
||||
i1.Set(1, 1, image.White)
|
||||
i1.Set(0, 1, color.Gray{123})
|
||||
|
||||
h := Histogram(i1)
|
||||
if h[0] != 0.25 || h[123] != 0.25 || h[255] != 0.5 {
|
||||
t.Errorf("Incorrect histogram for image i1")
|
||||
}
|
||||
|
||||
i2 := image.NewRGBA(b)
|
||||
i2.Set(0, 0, color.Gray{51})
|
||||
i2.Set(0, 1, color.Gray{14})
|
||||
i2.Set(1, 0, color.Gray{14})
|
||||
|
||||
h = Histogram(i2)
|
||||
if h[14] != 0.5 || h[51] != 0.25 || h[0] != 0.25 {
|
||||
t.Errorf("Incorrect histogram for image i2")
|
||||
}
|
||||
|
||||
b = image.Rectangle{image.Point{0, 0}, image.Point{0, 0}}
|
||||
i3 := image.NewRGBA(b)
|
||||
h = Histogram(i3)
|
||||
for _, val := range h {
|
||||
if val != 0 {
|
||||
t.Errorf("Histogram for an empty image should be a zero histogram.")
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
221
vendor/github.com/disintegration/imaging/resize.go
сгенерированный
поставляемый
@@ -24,17 +24,17 @@ func precomputeWeights(dstSize, srcSize int, filter ResampleFilter) [][]indexWei
|
||||
for v := 0; v < dstSize; v++ {
|
||||
fu := (float64(v)+0.5)*du - 0.5
|
||||
|
||||
startu := int(math.Ceil(fu - ru))
|
||||
if startu < 0 {
|
||||
startu = 0
|
||||
begin := int(math.Ceil(fu - ru))
|
||||
if begin < 0 {
|
||||
begin = 0
|
||||
}
|
||||
endu := int(math.Floor(fu + ru))
|
||||
if endu > srcSize-1 {
|
||||
endu = srcSize - 1
|
||||
end := int(math.Floor(fu + ru))
|
||||
if end > srcSize-1 {
|
||||
end = srcSize - 1
|
||||
}
|
||||
|
||||
var sum float64
|
||||
for u := startu; u <= endu; u++ {
|
||||
for u := begin; u <= end; u++ {
|
||||
w := filter.Kernel((float64(u) - fu) / scale)
|
||||
if w != 0 {
|
||||
sum += w
|
||||
@@ -67,7 +67,6 @@ func precomputeWeights(dstSize, srcSize int, filter ResampleFilter) [][]indexWei
|
||||
//
|
||||
func Resize(img image.Image, width, height int, filter ResampleFilter) *image.NRGBA {
|
||||
dstW, dstH := width, height
|
||||
|
||||
if dstW < 0 || dstH < 0 {
|
||||
return &image.NRGBA{}
|
||||
}
|
||||
@@ -75,16 +74,13 @@ func Resize(img image.Image, width, height int, filter ResampleFilter) *image.NR
|
||||
return &image.NRGBA{}
|
||||
}
|
||||
|
||||
src := toNRGBA(img)
|
||||
|
||||
srcW := src.Bounds().Max.X
|
||||
srcH := src.Bounds().Max.Y
|
||||
|
||||
srcW := img.Bounds().Dx()
|
||||
srcH := img.Bounds().Dy()
|
||||
if srcW <= 0 || srcH <= 0 {
|
||||
return &image.NRGBA{}
|
||||
}
|
||||
|
||||
// if new width or height is 0 then preserve aspect ratio, minimum 1px
|
||||
// If new width or height is 0 then preserve aspect ratio, minimum 1px.
|
||||
if dstW == 0 {
|
||||
tmpW := float64(dstH) * float64(srcW) / float64(srcH)
|
||||
dstW = int(math.Max(1.0, math.Floor(tmpW+0.5)))
|
||||
@@ -94,57 +90,45 @@ func Resize(img image.Image, width, height int, filter ResampleFilter) *image.NR
|
||||
dstH = int(math.Max(1.0, math.Floor(tmpH+0.5)))
|
||||
}
|
||||
|
||||
var dst *image.NRGBA
|
||||
|
||||
if filter.Support <= 0.0 {
|
||||
// nearest-neighbor special case
|
||||
dst = resizeNearest(src, dstW, dstH)
|
||||
|
||||
} else {
|
||||
// two-pass resize
|
||||
if srcW != dstW {
|
||||
dst = resizeHorizontal(src, dstW, filter)
|
||||
} else {
|
||||
dst = src
|
||||
}
|
||||
|
||||
if srcH != dstH {
|
||||
dst = resizeVertical(dst, dstH, filter)
|
||||
}
|
||||
if filter.Support <= 0 {
|
||||
// Nearest-neighbor special case.
|
||||
return resizeNearest(img, dstW, dstH)
|
||||
}
|
||||
|
||||
return dst
|
||||
if srcW != dstW && srcH != dstH {
|
||||
return resizeVertical(resizeHorizontal(img, dstW, filter), dstH, filter)
|
||||
}
|
||||
if srcW != dstW {
|
||||
return resizeHorizontal(img, dstW, filter)
|
||||
}
|
||||
if srcH != dstH {
|
||||
return resizeVertical(img, dstH, filter)
|
||||
}
|
||||
return Clone(img)
|
||||
}
|
||||
|
||||
func resizeHorizontal(src *image.NRGBA, width int, filter ResampleFilter) *image.NRGBA {
|
||||
srcBounds := src.Bounds()
|
||||
srcW := srcBounds.Max.X
|
||||
srcH := srcBounds.Max.Y
|
||||
|
||||
dstW := width
|
||||
dstH := srcH
|
||||
|
||||
dst := image.NewNRGBA(image.Rect(0, 0, dstW, dstH))
|
||||
|
||||
weights := precomputeWeights(dstW, srcW, filter)
|
||||
|
||||
parallel(dstH, func(partStart, partEnd int) {
|
||||
for dstY := partStart; dstY < partEnd; dstY++ {
|
||||
i0 := dstY * src.Stride
|
||||
j0 := dstY * dst.Stride
|
||||
for dstX := 0; dstX < dstW; dstX++ {
|
||||
func resizeHorizontal(img image.Image, width int, filter ResampleFilter) *image.NRGBA {
|
||||
src := newScanner(img)
|
||||
dst := image.NewNRGBA(image.Rect(0, 0, width, src.h))
|
||||
weights := precomputeWeights(width, src.w, filter)
|
||||
parallel(0, src.h, func(ys <-chan int) {
|
||||
scanLine := make([]uint8, src.w*4)
|
||||
for y := range ys {
|
||||
src.scan(0, y, src.w, y+1, scanLine)
|
||||
j0 := y * dst.Stride
|
||||
for x := 0; x < width; x++ {
|
||||
var r, g, b, a float64
|
||||
for _, w := range weights[dstX] {
|
||||
i := i0 + w.index*4
|
||||
aw := float64(src.Pix[i+3]) * w.weight
|
||||
r += float64(src.Pix[i+0]) * aw
|
||||
g += float64(src.Pix[i+1]) * aw
|
||||
b += float64(src.Pix[i+2]) * aw
|
||||
for _, w := range weights[x] {
|
||||
i := w.index * 4
|
||||
aw := float64(scanLine[i+3]) * w.weight
|
||||
r += float64(scanLine[i+0]) * aw
|
||||
g += float64(scanLine[i+1]) * aw
|
||||
b += float64(scanLine[i+2]) * aw
|
||||
a += aw
|
||||
}
|
||||
if a != 0 {
|
||||
aInv := 1 / a
|
||||
j := j0 + dstX*4
|
||||
j := j0 + x*4
|
||||
dst.Pix[j+0] = clamp(r * aInv)
|
||||
dst.Pix[j+1] = clamp(g * aInv)
|
||||
dst.Pix[j+2] = clamp(b * aInv)
|
||||
@@ -153,37 +137,30 @@ func resizeHorizontal(src *image.NRGBA, width int, filter ResampleFilter) *image
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
return dst
|
||||
}
|
||||
|
||||
func resizeVertical(src *image.NRGBA, height int, filter ResampleFilter) *image.NRGBA {
|
||||
srcBounds := src.Bounds()
|
||||
srcW := srcBounds.Max.X
|
||||
srcH := srcBounds.Max.Y
|
||||
|
||||
dstW := srcW
|
||||
dstH := height
|
||||
|
||||
dst := image.NewNRGBA(image.Rect(0, 0, dstW, dstH))
|
||||
|
||||
weights := precomputeWeights(dstH, srcH, filter)
|
||||
|
||||
parallel(dstW, func(partStart, partEnd int) {
|
||||
for dstX := partStart; dstX < partEnd; dstX++ {
|
||||
for dstY := 0; dstY < dstH; dstY++ {
|
||||
func resizeVertical(img image.Image, height int, filter ResampleFilter) *image.NRGBA {
|
||||
src := newScanner(img)
|
||||
dst := image.NewNRGBA(image.Rect(0, 0, src.w, height))
|
||||
weights := precomputeWeights(height, src.h, filter)
|
||||
parallel(0, src.w, func(xs <-chan int) {
|
||||
scanLine := make([]uint8, src.h*4)
|
||||
for x := range xs {
|
||||
src.scan(x, 0, x+1, src.h, scanLine)
|
||||
for y := 0; y < height; y++ {
|
||||
var r, g, b, a float64
|
||||
for _, w := range weights[dstY] {
|
||||
i := w.index*src.Stride + dstX*4
|
||||
aw := float64(src.Pix[i+3]) * w.weight
|
||||
r += float64(src.Pix[i+0]) * aw
|
||||
g += float64(src.Pix[i+1]) * aw
|
||||
b += float64(src.Pix[i+2]) * aw
|
||||
for _, w := range weights[y] {
|
||||
i := w.index * 4
|
||||
aw := float64(scanLine[i+3]) * w.weight
|
||||
r += float64(scanLine[i+0]) * aw
|
||||
g += float64(scanLine[i+1]) * aw
|
||||
b += float64(scanLine[i+2]) * aw
|
||||
a += aw
|
||||
}
|
||||
if a != 0 {
|
||||
aInv := 1 / a
|
||||
j := dstY*dst.Stride + dstX*4
|
||||
j := y*dst.Stride + x*4
|
||||
dst.Pix[j+0] = clamp(r * aInv)
|
||||
dst.Pix[j+1] = clamp(g * aInv)
|
||||
dst.Pix[j+2] = clamp(b * aInv)
|
||||
@@ -192,45 +169,44 @@ func resizeVertical(src *image.NRGBA, height int, filter ResampleFilter) *image.
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
return dst
|
||||
}
|
||||
|
||||
// resizeNearest is a fast nearest-neighbor resize, no filtering.
|
||||
func resizeNearest(src *image.NRGBA, width, height int) *image.NRGBA {
|
||||
dstW, dstH := width, height
|
||||
func resizeNearest(img image.Image, width, height int) *image.NRGBA {
|
||||
dst := image.NewNRGBA(image.Rect(0, 0, width, height))
|
||||
dx := float64(img.Bounds().Dx()) / float64(width)
|
||||
dy := float64(img.Bounds().Dy()) / float64(height)
|
||||
|
||||
srcBounds := src.Bounds()
|
||||
srcW := srcBounds.Max.X
|
||||
srcH := srcBounds.Max.Y
|
||||
|
||||
dst := image.NewNRGBA(image.Rect(0, 0, dstW, dstH))
|
||||
|
||||
dx := float64(srcW) / float64(dstW)
|
||||
dy := float64(srcH) / float64(dstH)
|
||||
|
||||
parallel(dstH, func(partStart, partEnd int) {
|
||||
|
||||
for dstY := partStart; dstY < partEnd; dstY++ {
|
||||
srcY := int((float64(dstY) + 0.5) * dy)
|
||||
if srcY > srcH-1 {
|
||||
srcY = srcH - 1
|
||||
}
|
||||
|
||||
for dstX := 0; dstX < dstW; dstX++ {
|
||||
srcX := int((float64(dstX) + 0.5) * dx)
|
||||
if srcX > srcW-1 {
|
||||
srcX = srcW - 1
|
||||
if dx > 1 && dy > 1 {
|
||||
src := newScanner(img)
|
||||
parallel(0, height, func(ys <-chan int) {
|
||||
for y := range ys {
|
||||
srcY := int((float64(y) + 0.5) * dy)
|
||||
dstOff := y * dst.Stride
|
||||
for x := 0; x < width; x++ {
|
||||
srcX := int((float64(x) + 0.5) * dx)
|
||||
src.scan(srcX, srcY, srcX+1, srcY+1, dst.Pix[dstOff:dstOff+4])
|
||||
dstOff += 4
|
||||
}
|
||||
|
||||
srcOff := srcY*src.Stride + srcX*4
|
||||
dstOff := dstY*dst.Stride + dstX*4
|
||||
|
||||
copy(dst.Pix[dstOff:dstOff+4], src.Pix[srcOff:srcOff+4])
|
||||
}
|
||||
}
|
||||
|
||||
})
|
||||
})
|
||||
} else {
|
||||
src := toNRGBA(img)
|
||||
parallel(0, height, func(ys <-chan int) {
|
||||
for y := range ys {
|
||||
srcY := int((float64(y) + 0.5) * dy)
|
||||
srcOff0 := srcY * src.Stride
|
||||
dstOff := y * dst.Stride
|
||||
for x := 0; x < width; x++ {
|
||||
srcX := int((float64(x) + 0.5) * dx)
|
||||
srcOff := srcOff0 + srcX*4
|
||||
copy(dst.Pix[dstOff:dstOff+4], src.Pix[srcOff:srcOff+4])
|
||||
dstOff += 4
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
return dst
|
||||
}
|
||||
@@ -344,27 +320,28 @@ func Thumbnail(img image.Image, width, height int, filter ResampleFilter) *image
|
||||
// General filter recommendations:
|
||||
//
|
||||
// - Lanczos
|
||||
// Probably the best resampling filter for photographic images yielding sharp results,
|
||||
// but it's slower than cubic filters (see below).
|
||||
// High-quality resampling filter for photographic images yielding sharp results.
|
||||
// It's slower than cubic filters (see below).
|
||||
//
|
||||
// - CatmullRom
|
||||
// A sharp cubic filter. It's a good filter for both upscaling and downscaling if sharp results are needed.
|
||||
//
|
||||
// - MitchellNetravali
|
||||
// A high quality cubic filter that produces smoother results with less ringing than CatmullRom.
|
||||
// A high quality cubic filter that produces smoother results with less ringing artifacts than CatmullRom.
|
||||
//
|
||||
// - BSpline
|
||||
// A good filter if a very smooth output is needed.
|
||||
//
|
||||
// - Linear
|
||||
// Bilinear interpolation filter, produces reasonably good, smooth output. It's faster than cubic filters.
|
||||
// Bilinear interpolation filter, produces reasonably good, smooth output.
|
||||
// It's faster than cubic filters.
|
||||
//
|
||||
// - Box
|
||||
// Simple and fast resampling filter appropriate for downscaling.
|
||||
// Simple and fast averaging filter appropriate for downscaling.
|
||||
// When upscaling it's similar to NearestNeighbor.
|
||||
//
|
||||
// - NearestNeighbor
|
||||
// Fastest resample filter, no antialiasing at all. Rarely used.
|
||||
// Fastest resampling filter, no antialiasing.
|
||||
//
|
||||
type ResampleFilter struct {
|
||||
Support float64
|
||||
@@ -417,14 +394,14 @@ var Welch ResampleFilter
|
||||
var Cosine ResampleFilter
|
||||
|
||||
func bcspline(x, b, c float64) float64 {
|
||||
var y float64
|
||||
x = math.Abs(x)
|
||||
if x < 1.0 {
|
||||
return ((12-9*b-6*c)*x*x*x + (-18+12*b+6*c)*x*x + (6 - 2*b)) / 6
|
||||
y = ((12-9*b-6*c)*x*x*x + (-18+12*b+6*c)*x*x + (6 - 2*b)) / 6
|
||||
} else if x < 2.0 {
|
||||
y = ((-b-6*c)*x*x*x + (6*b+30*c)*x*x + (-12*b-48*c)*x + (8*b + 24*c)) / 6
|
||||
}
|
||||
if x < 2.0 {
|
||||
return ((-b-6*c)*x*x*x + (6*b+30*c)*x*x + (-12*b-48*c)*x + (8*b + 24*c)) / 6
|
||||
}
|
||||
return 0
|
||||
return y
|
||||
}
|
||||
|
||||
func sinc(x float64) float64 {
|
||||
|
||||
628
vendor/github.com/disintegration/imaging/resize_test.go
сгенерированный
поставляемый
@@ -1,628 +0,0 @@
|
||||
package imaging
|
||||
|
||||
import (
|
||||
"image"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestResize(t *testing.T) {
|
||||
td := []struct {
|
||||
desc string
|
||||
src image.Image
|
||||
w, h int
|
||||
f ResampleFilter
|
||||
want *image.NRGBA
|
||||
}{
|
||||
{
|
||||
"Resize 2x2 1x1 box",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 1, 1),
|
||||
Stride: 2 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0xff,
|
||||
0x00, 0xff, 0x00, 0xff, 0x00, 0x00, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
1, 1,
|
||||
Box,
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 1, 1),
|
||||
Stride: 1 * 4,
|
||||
Pix: []uint8{0x55, 0x55, 0x55, 0xc0},
|
||||
},
|
||||
},
|
||||
{
|
||||
"Resize 2x2 2x2 box",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 1, 1),
|
||||
Stride: 2 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0xff,
|
||||
0x00, 0xff, 0x00, 0xff, 0x00, 0x00, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
2, 2,
|
||||
Box,
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 2, 2),
|
||||
Stride: 2 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0xff,
|
||||
0x00, 0xff, 0x00, 0xff, 0x00, 0x00, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
"Resize 3x1 1x1 nearest",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 2, 0),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0xff, 0x00, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0x00, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
1, 1,
|
||||
NearestNeighbor,
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 1, 1),
|
||||
Stride: 1 * 4,
|
||||
Pix: []uint8{0x00, 0xff, 0x00, 0xff},
|
||||
},
|
||||
},
|
||||
{
|
||||
"Resize 2x2 0x4 box",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 1, 1),
|
||||
Stride: 2 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0xff,
|
||||
0x00, 0xff, 0x00, 0xff, 0x00, 0x00, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
0, 4,
|
||||
Box,
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 4, 4),
|
||||
Stride: 4 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0xff,
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0xff,
|
||||
0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0xff, 0xff,
|
||||
0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
"Resize 2x2 4x0 linear",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 1, 1),
|
||||
Stride: 2 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0xff,
|
||||
0x00, 0xff, 0x00, 0xff, 0x00, 0x00, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
4, 0,
|
||||
Linear,
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 4, 4),
|
||||
Stride: 4 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0x40, 0xff, 0x00, 0x00, 0xbf, 0xff, 0x00, 0x00, 0xff,
|
||||
0x00, 0xff, 0x00, 0x40, 0x6e, 0x6d, 0x25, 0x70, 0xb0, 0x14, 0x3b, 0xcf, 0xbf, 0x00, 0x40, 0xff,
|
||||
0x00, 0xff, 0x00, 0xbf, 0x14, 0xb0, 0x3b, 0xcf, 0x33, 0x33, 0x99, 0xef, 0x40, 0x00, 0xbf, 0xff,
|
||||
0x00, 0xff, 0x00, 0xff, 0x00, 0xbf, 0x40, 0xff, 0x00, 0x40, 0xbf, 0xff, 0x00, 0x00, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
"Resize 0x0 1x1 box",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, -1, -1),
|
||||
Stride: 0,
|
||||
Pix: []uint8{},
|
||||
},
|
||||
1, 1,
|
||||
Box,
|
||||
&image.NRGBA{},
|
||||
},
|
||||
{
|
||||
"Resize 2x2 0x0 box",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 1, 1),
|
||||
Stride: 2 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0xff,
|
||||
0x00, 0xff, 0x00, 0xff, 0x00, 0x00, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
0, 0,
|
||||
Box,
|
||||
&image.NRGBA{},
|
||||
},
|
||||
{
|
||||
"Resize 2x2 -1x0 box",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 1, 1),
|
||||
Stride: 2 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0xff,
|
||||
0x00, 0xff, 0x00, 0xff, 0x00, 0x00, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
-1, 0,
|
||||
Box,
|
||||
&image.NRGBA{},
|
||||
},
|
||||
}
|
||||
for _, d := range td {
|
||||
got := Resize(d.src, d.w, d.h, d.f)
|
||||
want := d.want
|
||||
if !compareNRGBA(got, want, 0) {
|
||||
t.Errorf("test [%s] failed: %#v", d.desc, got)
|
||||
}
|
||||
}
|
||||
|
||||
for i, filter := range []ResampleFilter{
|
||||
NearestNeighbor,
|
||||
Box,
|
||||
Linear,
|
||||
Hermite,
|
||||
MitchellNetravali,
|
||||
CatmullRom,
|
||||
BSpline,
|
||||
Gaussian,
|
||||
Lanczos,
|
||||
Hann,
|
||||
Hamming,
|
||||
Blackman,
|
||||
Bartlett,
|
||||
Welch,
|
||||
Cosine,
|
||||
} {
|
||||
src := image.NewNRGBA(image.Rect(-1, -1, 2, 3))
|
||||
got := Resize(src, 5, 6, filter)
|
||||
want := image.NewNRGBA(image.Rect(0, 0, 5, 6))
|
||||
if !compareNRGBA(got, want, 0) {
|
||||
t.Errorf("test [Resize all filters #%d] failed: %#v", i, got)
|
||||
}
|
||||
|
||||
if filter.Kernel != nil {
|
||||
x := filter.Kernel(filter.Support + 0.0001)
|
||||
if x != 0 {
|
||||
t.Errorf("test [ResampleFilter edge cases #%d] failed: %f", i, x)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bcs2 := bcspline(2, 1, 0)
|
||||
if bcs2 != 0 {
|
||||
t.Errorf("test [bcspline 2] failed: %f", bcs2)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResizeGolden(t *testing.T) {
|
||||
src, err := Open("testdata/lena_512.png")
|
||||
if err != nil {
|
||||
t.Errorf("Open: %v", err)
|
||||
}
|
||||
for name, filter := range map[string]ResampleFilter{
|
||||
"out_resize_nearest.png": NearestNeighbor,
|
||||
"out_resize_linear.png": Linear,
|
||||
"out_resize_catrom.png": CatmullRom,
|
||||
"out_resize_lanczos.png": Lanczos,
|
||||
} {
|
||||
got := Resize(src, 128, 0, filter)
|
||||
want, err := Open("testdata/" + name)
|
||||
if err != nil {
|
||||
t.Errorf("Open: %v", err)
|
||||
}
|
||||
if !compareNRGBA(got, toNRGBA(want), 0) {
|
||||
t.Errorf("resulting image differs from golden: %s", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestFit(t *testing.T) {
|
||||
td := []struct {
|
||||
desc string
|
||||
src image.Image
|
||||
w, h int
|
||||
f ResampleFilter
|
||||
want *image.NRGBA
|
||||
}{
|
||||
{
|
||||
"Fit 2x2 1x10 box",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 1, 1),
|
||||
Stride: 2 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0xff,
|
||||
0x00, 0xff, 0x00, 0xff, 0x00, 0x00, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
1, 10,
|
||||
Box,
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 1, 1),
|
||||
Stride: 1 * 4,
|
||||
Pix: []uint8{0x55, 0x55, 0x55, 0xc0},
|
||||
},
|
||||
},
|
||||
{
|
||||
"Fit 2x2 10x1 box",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 1, 1),
|
||||
Stride: 2 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0xff,
|
||||
0x00, 0xff, 0x00, 0xff, 0x00, 0x00, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
10, 1,
|
||||
Box,
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 1, 1),
|
||||
Stride: 1 * 4,
|
||||
Pix: []uint8{0x55, 0x55, 0x55, 0xc0},
|
||||
},
|
||||
},
|
||||
{
|
||||
"Fit 2x2 10x10 box",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 1, 1),
|
||||
Stride: 2 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0xff,
|
||||
0x00, 0xff, 0x00, 0xff, 0x00, 0x00, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
10, 10,
|
||||
Box,
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 2, 2),
|
||||
Stride: 2 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0xff,
|
||||
0x00, 0xff, 0x00, 0xff, 0x00, 0x00, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
"Fit 0x0 1x1 box",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, -1, -1),
|
||||
Stride: 0,
|
||||
Pix: []uint8{},
|
||||
},
|
||||
1, 1,
|
||||
Box,
|
||||
&image.NRGBA{},
|
||||
},
|
||||
{
|
||||
"Fit 2x2 0x0 box",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 1, 1),
|
||||
Stride: 2 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0xff,
|
||||
0x00, 0xff, 0x00, 0xff, 0x00, 0x00, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
0, 0,
|
||||
Box,
|
||||
&image.NRGBA{},
|
||||
},
|
||||
{
|
||||
"Fit 2x2 -1x0 box",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 1, 1),
|
||||
Stride: 2 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0xff,
|
||||
0x00, 0xff, 0x00, 0xff, 0x00, 0x00, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
-1, 0,
|
||||
Box,
|
||||
&image.NRGBA{},
|
||||
},
|
||||
}
|
||||
for _, d := range td {
|
||||
got := Fit(d.src, d.w, d.h, d.f)
|
||||
want := d.want
|
||||
if !compareNRGBA(got, want, 0) {
|
||||
t.Errorf("test [%s] failed: %#v", d.desc, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestFill(t *testing.T) {
|
||||
td := []struct {
|
||||
desc string
|
||||
src image.Image
|
||||
w, h int
|
||||
a Anchor
|
||||
f ResampleFilter
|
||||
want *image.NRGBA
|
||||
}{
|
||||
{
|
||||
"Fill 4x4 2x2 Center Nearest",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 3, 3),
|
||||
Stride: 4 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
|
||||
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
|
||||
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f,
|
||||
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f,
|
||||
},
|
||||
},
|
||||
2, 2,
|
||||
Center,
|
||||
NearestNeighbor,
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 2, 2),
|
||||
Stride: 2 * 4,
|
||||
Pix: []uint8{
|
||||
0x14, 0x15, 0x16, 0x17, 0x1c, 0x1d, 0x1e, 0x1f,
|
||||
0x34, 0x35, 0x36, 0x37, 0x3c, 0x3d, 0x3e, 0x3f,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
"Fill 4x4 1x4 TopLeft Nearest",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 3, 3),
|
||||
Stride: 4 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
|
||||
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
|
||||
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f,
|
||||
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f,
|
||||
},
|
||||
},
|
||||
1, 4,
|
||||
TopLeft,
|
||||
NearestNeighbor,
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 1, 4),
|
||||
Stride: 1 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x01, 0x02, 0x03,
|
||||
0x10, 0x11, 0x12, 0x13,
|
||||
0x20, 0x21, 0x22, 0x23,
|
||||
0x30, 0x31, 0x32, 0x33,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
"Fill 4x4 8x2 Bottom Nearest",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 3, 3),
|
||||
Stride: 4 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
|
||||
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
|
||||
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f,
|
||||
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f,
|
||||
},
|
||||
},
|
||||
8, 2,
|
||||
Bottom,
|
||||
NearestNeighbor,
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 8, 2),
|
||||
Stride: 8 * 4,
|
||||
Pix: []uint8{
|
||||
0x30, 0x31, 0x32, 0x33, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x3c, 0x3d, 0x3e, 0x3f,
|
||||
0x30, 0x31, 0x32, 0x33, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x3c, 0x3d, 0x3e, 0x3f,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
"Fill 4x4 2x8 Top Nearest",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 3, 3),
|
||||
Stride: 4 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
|
||||
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
|
||||
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f,
|
||||
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f,
|
||||
},
|
||||
},
|
||||
2, 8,
|
||||
Top,
|
||||
NearestNeighbor,
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 2, 8),
|
||||
Stride: 2 * 4,
|
||||
Pix: []uint8{
|
||||
0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b,
|
||||
0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b,
|
||||
0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b,
|
||||
0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b,
|
||||
0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b,
|
||||
0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b,
|
||||
0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b,
|
||||
0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
"Fill 4x4 4x4 TopRight Box",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 3, 3),
|
||||
Stride: 4 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
|
||||
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
|
||||
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f,
|
||||
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f,
|
||||
},
|
||||
},
|
||||
4, 4,
|
||||
TopRight,
|
||||
Box,
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 4, 4),
|
||||
Stride: 4 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
|
||||
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
|
||||
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f,
|
||||
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
"Fill 4x4 0x4 Left Box",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 3, 3),
|
||||
Stride: 4 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
|
||||
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
|
||||
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f,
|
||||
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f,
|
||||
},
|
||||
},
|
||||
0, 4,
|
||||
Left,
|
||||
Box,
|
||||
&image.NRGBA{},
|
||||
},
|
||||
{
|
||||
"Fill 0x0 4x4 Right Box",
|
||||
&image.NRGBA{},
|
||||
4, 4,
|
||||
Right,
|
||||
Box,
|
||||
&image.NRGBA{},
|
||||
},
|
||||
}
|
||||
for _, d := range td {
|
||||
got := Fill(d.src, d.w, d.h, d.a, d.f)
|
||||
want := d.want
|
||||
if !compareNRGBA(got, want, 0) {
|
||||
t.Errorf("test [%s] failed: %#v", d.desc, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestThumbnail(t *testing.T) {
|
||||
td := []struct {
|
||||
desc string
|
||||
src image.Image
|
||||
w, h int
|
||||
f ResampleFilter
|
||||
want *image.NRGBA
|
||||
}{
|
||||
{
|
||||
"Thumbnail 6x2 1x1 box",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 5, 1),
|
||||
Stride: 6 * 4,
|
||||
Pix: []uint8{
|
||||
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
1, 1,
|
||||
Box,
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 1, 1),
|
||||
Stride: 1 * 4,
|
||||
Pix: []uint8{0x55, 0x55, 0x55, 0xc0},
|
||||
},
|
||||
},
|
||||
{
|
||||
"Thumbnail 2x6 1x1 box",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 1, 5),
|
||||
Stride: 2 * 4,
|
||||
Pix: []uint8{
|
||||
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0xff,
|
||||
0x00, 0xff, 0x00, 0xff, 0x00, 0x00, 0xff, 0xff,
|
||||
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
1, 1,
|
||||
Box,
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 1, 1),
|
||||
Stride: 1 * 4,
|
||||
Pix: []uint8{0x55, 0x55, 0x55, 0xc0},
|
||||
},
|
||||
},
|
||||
{
|
||||
"Thumbnail 1x3 2x2 box",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 0, 2),
|
||||
Stride: 1 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x00, 0x00, 0x00,
|
||||
0xff, 0x00, 0x00, 0xff,
|
||||
0xff, 0xff, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
2, 2,
|
||||
Box,
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 2, 2),
|
||||
Stride: 2 * 4,
|
||||
Pix: []uint8{
|
||||
0xff, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0xff,
|
||||
0xff, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0xff,
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
for _, d := range td {
|
||||
got := Thumbnail(d.src, d.w, d.h, d.f)
|
||||
want := d.want
|
||||
if !compareNRGBA(got, want, 0) {
|
||||
t.Errorf("test [%s] failed: %#v", d.desc, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkResizeLanczosUp(b *testing.B) {
|
||||
benchmarkResize(b, "testdata/lena_128.png", 512, Lanczos)
|
||||
}
|
||||
|
||||
func BenchmarkResizeLinearUp(b *testing.B) {
|
||||
benchmarkResize(b, "testdata/lena_128.png", 512, Linear)
|
||||
}
|
||||
|
||||
func BenchmarkResizeNearestNeighborUp(b *testing.B) {
|
||||
benchmarkResize(b, "testdata/lena_128.png", 512, NearestNeighbor)
|
||||
}
|
||||
|
||||
func BenchmarkResizeLanczosDown(b *testing.B) {
|
||||
benchmarkResize(b, "testdata/lena_512.png", 128, Lanczos)
|
||||
}
|
||||
|
||||
func BenchmarkResizeLinearDown(b *testing.B) {
|
||||
benchmarkResize(b, "testdata/lena_512.png", 128, Linear)
|
||||
}
|
||||
|
||||
func BenchmarkResizeNearestNeighborDown(b *testing.B) {
|
||||
benchmarkResize(b, "testdata/lena_512.png", 128, NearestNeighbor)
|
||||
}
|
||||
|
||||
func benchmarkResize(b *testing.B, filename string, size int, f ResampleFilter) {
|
||||
b.StopTimer()
|
||||
img, err := Open(filename)
|
||||
if err != nil {
|
||||
b.Fatalf("Open: %v", err)
|
||||
}
|
||||
b.StartTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
Resize(img, size, size, f)
|
||||
}
|
||||
}
|
||||
250
vendor/github.com/disintegration/imaging/scanner.go
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,250 @@
|
||||
package imaging
|
||||
|
||||
import (
|
||||
"image"
|
||||
"image/color"
|
||||
)
|
||||
|
||||
type scanner struct {
|
||||
image image.Image
|
||||
w, h int
|
||||
palette []color.NRGBA
|
||||
}
|
||||
|
||||
func newScanner(img image.Image) *scanner {
|
||||
s := &scanner{
|
||||
image: img,
|
||||
w: img.Bounds().Dx(),
|
||||
h: img.Bounds().Dy(),
|
||||
}
|
||||
if img, ok := img.(*image.Paletted); ok {
|
||||
s.palette = make([]color.NRGBA, len(img.Palette))
|
||||
for i := 0; i < len(img.Palette); i++ {
|
||||
s.palette[i] = color.NRGBAModel.Convert(img.Palette[i]).(color.NRGBA)
|
||||
}
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// scan scans the given rectangular region of the image into dst.
|
||||
func (s *scanner) scan(x1, y1, x2, y2 int, dst []uint8) {
|
||||
switch img := s.image.(type) {
|
||||
case *image.NRGBA:
|
||||
size := (x2 - x1) * 4
|
||||
j := 0
|
||||
i := y1*img.Stride + x1*4
|
||||
for y := y1; y < y2; y++ {
|
||||
copy(dst[j:j+size], img.Pix[i:i+size])
|
||||
j += size
|
||||
i += img.Stride
|
||||
}
|
||||
|
||||
case *image.NRGBA64:
|
||||
j := 0
|
||||
for y := y1; y < y2; y++ {
|
||||
i := y*img.Stride + x1*8
|
||||
for x := x1; x < x2; x++ {
|
||||
dst[j+0] = img.Pix[i+0]
|
||||
dst[j+1] = img.Pix[i+2]
|
||||
dst[j+2] = img.Pix[i+4]
|
||||
dst[j+3] = img.Pix[i+6]
|
||||
j += 4
|
||||
i += 8
|
||||
}
|
||||
}
|
||||
|
||||
case *image.RGBA:
|
||||
j := 0
|
||||
for y := y1; y < y2; y++ {
|
||||
i := y*img.Stride + x1*4
|
||||
for x := x1; x < x2; x++ {
|
||||
a := img.Pix[i+3]
|
||||
switch a {
|
||||
case 0:
|
||||
dst[j+0] = 0
|
||||
dst[j+1] = 0
|
||||
dst[j+2] = 0
|
||||
case 0xff:
|
||||
dst[j+0] = img.Pix[i+0]
|
||||
dst[j+1] = img.Pix[i+1]
|
||||
dst[j+2] = img.Pix[i+2]
|
||||
default:
|
||||
r16 := uint16(img.Pix[i+0])
|
||||
g16 := uint16(img.Pix[i+1])
|
||||
b16 := uint16(img.Pix[i+2])
|
||||
a16 := uint16(a)
|
||||
dst[j+0] = uint8(r16 * 0xff / a16)
|
||||
dst[j+1] = uint8(g16 * 0xff / a16)
|
||||
dst[j+2] = uint8(b16 * 0xff / a16)
|
||||
}
|
||||
dst[j+3] = a
|
||||
j += 4
|
||||
i += 4
|
||||
}
|
||||
}
|
||||
|
||||
case *image.RGBA64:
|
||||
j := 0
|
||||
for y := y1; y < y2; y++ {
|
||||
i := y*img.Stride + x1*8
|
||||
for x := x1; x < x2; x++ {
|
||||
a := img.Pix[i+6]
|
||||
switch a {
|
||||
case 0:
|
||||
dst[j+0] = 0
|
||||
dst[j+1] = 0
|
||||
dst[j+2] = 0
|
||||
case 0xff:
|
||||
dst[j+0] = img.Pix[i+0]
|
||||
dst[j+1] = img.Pix[i+2]
|
||||
dst[j+2] = img.Pix[i+4]
|
||||
default:
|
||||
r32 := uint32(img.Pix[i+0])<<8 | uint32(img.Pix[i+1])
|
||||
g32 := uint32(img.Pix[i+2])<<8 | uint32(img.Pix[i+3])
|
||||
b32 := uint32(img.Pix[i+4])<<8 | uint32(img.Pix[i+5])
|
||||
a32 := uint32(img.Pix[i+6])<<8 | uint32(img.Pix[i+7])
|
||||
dst[j+0] = uint8((r32 * 0xffff / a32) >> 8)
|
||||
dst[j+1] = uint8((g32 * 0xffff / a32) >> 8)
|
||||
dst[j+2] = uint8((b32 * 0xffff / a32) >> 8)
|
||||
}
|
||||
dst[j+3] = a
|
||||
j += 4
|
||||
i += 8
|
||||
}
|
||||
}
|
||||
|
||||
case *image.Gray:
|
||||
j := 0
|
||||
for y := y1; y < y2; y++ {
|
||||
i := y*img.Stride + x1
|
||||
for x := x1; x < x2; x++ {
|
||||
c := img.Pix[i]
|
||||
dst[j+0] = c
|
||||
dst[j+1] = c
|
||||
dst[j+2] = c
|
||||
dst[j+3] = 0xff
|
||||
j += 4
|
||||
i++
|
||||
}
|
||||
}
|
||||
|
||||
case *image.Gray16:
|
||||
j := 0
|
||||
for y := y1; y < y2; y++ {
|
||||
i := y*img.Stride + x1*2
|
||||
for x := x1; x < x2; x++ {
|
||||
c := img.Pix[i]
|
||||
dst[j+0] = c
|
||||
dst[j+1] = c
|
||||
dst[j+2] = c
|
||||
dst[j+3] = 0xff
|
||||
j += 4
|
||||
i += 2
|
||||
}
|
||||
}
|
||||
|
||||
case *image.YCbCr:
|
||||
j := 0
|
||||
x1 += img.Rect.Min.X
|
||||
x2 += img.Rect.Min.X
|
||||
y1 += img.Rect.Min.Y
|
||||
y2 += img.Rect.Min.Y
|
||||
for y := y1; y < y2; y++ {
|
||||
iy := (y-img.Rect.Min.Y)*img.YStride + (x1 - img.Rect.Min.X)
|
||||
for x := x1; x < x2; x++ {
|
||||
var ic int
|
||||
switch img.SubsampleRatio {
|
||||
case image.YCbCrSubsampleRatio444:
|
||||
ic = (y-img.Rect.Min.Y)*img.CStride + (x - img.Rect.Min.X)
|
||||
case image.YCbCrSubsampleRatio422:
|
||||
ic = (y-img.Rect.Min.Y)*img.CStride + (x/2 - img.Rect.Min.X/2)
|
||||
case image.YCbCrSubsampleRatio420:
|
||||
ic = (y/2-img.Rect.Min.Y/2)*img.CStride + (x/2 - img.Rect.Min.X/2)
|
||||
case image.YCbCrSubsampleRatio440:
|
||||
ic = (y/2-img.Rect.Min.Y/2)*img.CStride + (x - img.Rect.Min.X)
|
||||
default:
|
||||
ic = img.COffset(x, y)
|
||||
}
|
||||
|
||||
yy := int(img.Y[iy])
|
||||
cb := int(img.Cb[ic]) - 128
|
||||
cr := int(img.Cr[ic]) - 128
|
||||
|
||||
r := (yy<<16 + 91881*cr + 1<<15) >> 16
|
||||
if r > 0xff {
|
||||
r = 0xff
|
||||
} else if r < 0 {
|
||||
r = 0
|
||||
}
|
||||
|
||||
g := (yy<<16 - 22554*cb - 46802*cr + 1<<15) >> 16
|
||||
if g > 0xff {
|
||||
g = 0xff
|
||||
} else if g < 0 {
|
||||
g = 0
|
||||
}
|
||||
|
||||
b := (yy<<16 + 116130*cb + 1<<15) >> 16
|
||||
if b > 0xff {
|
||||
b = 0xff
|
||||
} else if b < 0 {
|
||||
b = 0
|
||||
}
|
||||
|
||||
dst[j+0] = uint8(r)
|
||||
dst[j+1] = uint8(g)
|
||||
dst[j+2] = uint8(b)
|
||||
dst[j+3] = 0xff
|
||||
|
||||
iy++
|
||||
j += 4
|
||||
}
|
||||
}
|
||||
|
||||
case *image.Paletted:
|
||||
j := 0
|
||||
for y := y1; y < y2; y++ {
|
||||
i := y*img.Stride + x1
|
||||
for x := x1; x < x2; x++ {
|
||||
c := s.palette[img.Pix[i]]
|
||||
dst[j+0] = c.R
|
||||
dst[j+1] = c.G
|
||||
dst[j+2] = c.B
|
||||
dst[j+3] = c.A
|
||||
j += 4
|
||||
i++
|
||||
}
|
||||
}
|
||||
|
||||
default:
|
||||
j := 0
|
||||
b := s.image.Bounds()
|
||||
x1 += b.Min.X
|
||||
x2 += b.Min.X
|
||||
y1 += b.Min.Y
|
||||
y2 += b.Min.Y
|
||||
for y := y1; y < y2; y++ {
|
||||
for x := x1; x < x2; x++ {
|
||||
r16, g16, b16, a16 := s.image.At(x, y).RGBA()
|
||||
switch a16 {
|
||||
case 0xffff:
|
||||
dst[j+0] = uint8(r16 >> 8)
|
||||
dst[j+1] = uint8(g16 >> 8)
|
||||
dst[j+2] = uint8(b16 >> 8)
|
||||
dst[j+3] = 0xff
|
||||
case 0:
|
||||
dst[j+0] = 0
|
||||
dst[j+1] = 0
|
||||
dst[j+2] = 0
|
||||
dst[j+3] = 0
|
||||
default:
|
||||
dst[j+0] = uint8(((r16 * 0xffff) / a16) >> 8)
|
||||
dst[j+1] = uint8(((g16 * 0xffff) / a16) >> 8)
|
||||
dst[j+2] = uint8(((b16 * 0xffff) / a16) >> 8)
|
||||
dst[j+3] = uint8(a16 >> 8)
|
||||
}
|
||||
j += 4
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Двоичные данные
vendor/github.com/disintegration/imaging/testdata/lena_128.png
сгенерированный
поставляемый
|
До Ширина: | Высота: | Размер: 49 KiB |
Двоичные данные
vendor/github.com/disintegration/imaging/testdata/lena_512.png
сгенерированный
поставляемый
|
До Ширина: | Высота: | Размер: 465 KiB |
Двоичные данные
vendor/github.com/disintegration/imaging/testdata/out_blur_0.5.png
сгенерированный
поставляемый
|
До Ширина: | Высота: | Размер: 28 KiB |
Двоичные данные
vendor/github.com/disintegration/imaging/testdata/out_blur_1.5.png
сгенерированный
поставляемый
|
До Ширина: | Высота: | Размер: 21 KiB |
Двоичные данные
vendor/github.com/disintegration/imaging/testdata/out_brightness_m10.png
сгенерированный
поставляемый
|
До Ширина: | Высота: | Размер: 31 KiB |
Двоичные данные
vendor/github.com/disintegration/imaging/testdata/out_brightness_p10.png
сгенерированный
поставляемый
|
До Ширина: | Высота: | Размер: 31 KiB |
Двоичные данные
vendor/github.com/disintegration/imaging/testdata/out_contrast_m10.png
сгенерированный
поставляемый
|
До Ширина: | Высота: | Размер: 30 KiB |
Двоичные данные
vendor/github.com/disintegration/imaging/testdata/out_contrast_p10.png
сгенерированный
поставляемый
|
До Ширина: | Высота: | Размер: 32 KiB |
Двоичные данные
vendor/github.com/disintegration/imaging/testdata/out_example.jpg
сгенерированный
поставляемый
|
До Ширина: | Высота: | Размер: 134 KiB |
Двоичные данные
vendor/github.com/disintegration/imaging/testdata/out_gamma_0.75.png
сгенерированный
поставляемый
|
До Ширина: | Высота: | Размер: 31 KiB |