pax_global_header00006660000000000000000000000064143770761040014523gustar00rootroot0000000000000052 comment=05d62251ba45cd4a07c67691cffcee05022e8d62 golang-iij-dpf-0.9.1/000077500000000000000000000000001437707610400143215ustar00rootroot00000000000000golang-iij-dpf-0.9.1/.github/000077500000000000000000000000001437707610400156615ustar00rootroot00000000000000golang-iij-dpf-0.9.1/.github/workflows/000077500000000000000000000000001437707610400177165ustar00rootroot00000000000000golang-iij-dpf-0.9.1/.github/workflows/ci.yaml000066400000000000000000000012531437707610400211760ustar00rootroot00000000000000name: ci on: push: branches: - main pull_request: branches: - main workflow_dispatch: branches: - "*" jobs: test: name: Test runs-on: ubuntu-latest steps: - name: Check out code into the Go module directory uses: actions/checkout@v2 - name: Set up Go 1.19 uses: actions/setup-go@v2 with: go-version: 1.19 - name: Get dependencies run: | go get -v -t -d ./... - name: Test run: go test -race -coverprofile="coverage.txt" -covermode=atomic ./... - name: upload coverage uses: codecov/codecov-action@v1 with: token: ${{ secrets.CODECOV_TOKEN }} golang-iij-dpf-0.9.1/.gitignore000066400000000000000000000004601437707610400163110ustar00rootroot00000000000000# Binaries for programs and plugins *.exe *.exe~ *.dll *.so *.dylib # Test binary, built with `go test -c` *.test # Output of the go coverage tool, specifically when used with LiteIDE *.out # Dependency directories (remove the comment below to include it) # vendor/ bin/ .vscode cover.html cover.out golang-iij-dpf-0.9.1/.golangci.yaml000066400000000000000000000066721437707610400170610ustar00rootroot00000000000000# Options for analysis running. run: # The default concurrency value is the number of available CPU. concurrency: 4 # Timeout for analysise.g. 30s5m. # Default: 1m timeout: 5m # Exit code when at least one issue was found. # Default: 1 issues-exit-code: 2 # Include test files or not. # Default: true tests: false # List of build tagsall linters use it. # Default: []. build-tags: - mytag # Which dirs to skip: issues from them won't be reported. # Can use regexp here: `generated.*`regexp is applied on full path. # Default value is empty list, # but default dirs are skipped independently of this option's value (see skip-dirs-use-default). # "/" will be replaced by current OS file path separator to properly work on Windows. skip-dirs: [] # Enables skipping of directories: # - vendor$third_party$testdata$examples$Godeps$builtin$ # Default: true skip-dirs-use-default: false # Which files to skip: they will be analyzedbut issues from them won't be reported. # Default value is empty list, # but there is no need to include all autogenerated files, # we confidently recognize autogenerated files. # If it's not please let us know. # "/" will be replaced by current OS file path separator to properly work on Windows. skip-files: - "_test.go$" # If set we pass it to "go list -mod={option}". From "go help modules": # If invoked with -mod=readonlythe go command is disallowed from the implicit # automatic updating of go.mod described above. Insteadit fails when any changes # to go.mod are needed. This setting is most useful to check that go.mod does # not need updatessuch as in a continuous integration and testing system. # If invoked with -mod=vendorthe go command assumes that the vendor # directory holds the correct copies of dependencies and ignores # the dependency descriptions in go.mod. # # Allowed values: readonly|vendor|mod # By defaultit isn't set. modules-download-mode: readonly # Allow multiple parallel golangci-lint instances running. # If false (default) - golangci-lint acquires file lock on start. allow-parallel-runners: false # Define the Go version limit. # Mainly related to generics support in go1.18. # Default: use Go version from the go.mod filefallback on the env var `GOVERSION`fallback on 1.17 go: '1.18' linters: enable-all: true # Disable specific linter # https://golangci-lint.run/usage/linters/#disabled-by-default-linters--e--enable disable: - exhaustivestruct - errname - exhaustive - gochecknoinits - golint - goconst - interfacer - maligned - scopelint - golint - cyclop - lll - gosec - dupl - prealloc - bodyclose - gomnd - testpackage - tparallel - wrapcheck - ireturn - goerr113 - wsl - varnamelen - nlreturn - godot - revive - exhaustruct - interfacebloat - varcheck - ifshort - nosnakecase - deadcode - structcheck - rowserrcheck - wastedassign issues: exclude-rules: - path: pkg/api/json.go|pkg/schema/schema.go linters: - gochecknoglobals - path: pkg/testtool/spec.go linters: - "stylecheck" - path: pkg/testtool/spec.go linters: - gci - path: pkg/apis/dpf/v1/lb_domains/monitoring.go linters: - musttag linters-settings: stylecheck: checks: ["all", "-ST1000", "-ST1003", "-ST1016", "-ST1020", "-ST1021", "-ST1022"] golang-iij-dpf-0.9.1/LICENSE000066400000000000000000000020561437707610400153310ustar00rootroot00000000000000MIT License Copyright (c) 2021 Manabu Sonoda 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. golang-iij-dpf-0.9.1/Makefile000066400000000000000000000054021437707610400157620ustar00rootroot00000000000000PROJECT_DIR := $(shell dirname $(abspath $(lastword $(MAKEFILE_LIST)))) types_go_files = $(wildcard ./pkg/types/*.go) v1_core_go_files = $(wildcard ./pkg/apis/dpf/v1/core/*.go) v1_contracts_go_files = $(wildcard ./pkg/apis/dpf/v1/contracts/*.go) v1_common_configs_go_files = $(wildcard ./pkg/apis/dpf/v1/common_configs/*.go) v1_zones_go_files = $(wildcard ./pkg/apis/dpf/v1/zones/*.go) v1_lb_domains_go_files = $(wildcard ./pkg/apis/dpf/v1/lb_domains/*.go) deep_copy_files = pkg/types/ZZ_deepcopy_generated.go \ pkg/apis/dpf/v1/core/ZZ_deepcopy_generated.go \ pkg/apis/dpf/v1/contracts/ZZ_deepcopy_generated.go \ pkg/apis/dpf/v1/zones/ZZ_deepcopy_generated.go \ pkg/apis/dpf/v1/common_configs/ZZ_deepcopy_generated.go \ pkg/apis/dpf/v1/lb_domains/ZZ_deepcopy_generated.go all: deepcopy fmt checks test checks: golangci-lint $(GOLANGCI_LINT) run test: go test -coverprofile="cover.out" ./... go tool cover -html=cover.out -o cover.html fmt: gofumpt $(GOFUMPT) -l -w . deepcopy: $(deep_copy_files) pkg/types/ZZ_deepcopy_generated.go: deepcopy-gen $(types_go_files) $(DEEPCOPY_GEN) -O ZZ_deepcopy_generated -h boilerplate.go.txt -i ./pkg/types pkg/apis/dpf/v1/core/ZZ_deepcopy_generated.go: deepcopy-gen $(v1_core_go_files) $(DEEPCOPY_GEN) -O ZZ_deepcopy_generated -h boilerplate.go.txt -i ./pkg/apis/dpf/v1/core pkg/apis/dpf/v1/contracts/ZZ_deepcopy_generated.go: deepcopy-gen $(v1_contracts_go_files) $(DEEPCOPY_GEN) -O ZZ_deepcopy_generated -h boilerplate.go.txt -i ./pkg/apis/dpf/v1/contracts pkg/apis/dpf/v1/zones/ZZ_deepcopy_generated.go: deepcopy-gen $(v1_common_configs_go_files) $(DEEPCOPY_GEN) -O ZZ_deepcopy_generated -h boilerplate.go.txt -i ./pkg/apis/dpf/v1/zones pkg/apis/dpf/v1/common_configs/ZZ_deepcopy_generated.go: deepcopy-gen $(v1_zones_go_files) $(DEEPCOPY_GEN) -O ZZ_deepcopy_generated -h boilerplate.go.txt -i ./pkg/apis/dpf/v1/common_configs pkg/apis/dpf/v1/lb_domains/ZZ_deepcopy_generated.go: deepcopy-gen $(v1_lb_domains_go_files) $(DEEPCOPY_GEN) -O ZZ_deepcopy_generated -h boilerplate.go.txt -i ./pkg/apis/dpf/v1/lb_domains DEEPCOPY_GEN = $(PROJECT_DIR)/bin/deepcopy-gen deepcopy-gen: ## Download deepcopy-gen locally if necessary. mkdir -p $(PROJECT_DIR)/bin $(call go-get-tool,$(DEEPCOPY_GEN),k8s.io/code-generator/cmd/deepcopy-gen@latest) GOFUMPT = $(PROJECT_DIR)/bin/gofumpt gofumpt: mkdir -p $(PROJECT_DIR)/bin $(call go-get-tool,$(GOFUMPT),mvdan.cc/gofumpt@latest) GOLANGCI_LINT = $(PROJECT_DIR)/bin/golangci-lint golangci-lint: mkdir -p $(PROJECT_DIR)/bin $(call go-get-tool,$(GOLANGCI_LINT),github.com/golangci/golangci-lint/cmd/golangci-lint@master) # go-get-tool will 'go get' any package $2 and install it to $1. define go-get-tool @[ -f $(1) ] || { \ set -e ;\ echo "Downloading $(2)" ;\ GOBIN=$(PROJECT_DIR)/bin go install $(2) ;\ } endef golang-iij-dpf-0.9.1/README.md000066400000000000000000000015261437707610400156040ustar00rootroot00000000000000# IIJ DNS Platform Service API for Go [![codecov](https://codecov.io/gh/mimuret/golang-iij-dpf/branch/main/graph/badge.svg?token=CTIBL2M5YD)](https://codecov.io/gh/mimuret/golang-iij-dpf) - API Library for [IIJ DNS Platform Service](https://www.iij.ad.jp/en/biz/dns-pfm/). - This is not an official IIJ software. ## Usage ``` package main import ( "fmt" "os" "github.com/mimuret/golang-iij-dpf/pkg/api" "github.com/mimuret/golang-iij-dpf/pkg/apis/dpf/v1/core" ) func main() { token := os.Getenv("DPF_TOKEN") cl := api.NewClient(token, "", nil) zoneList := &core.ZoneList{} searchParam := &core.ZoneListSearchKeywords{Name: api.KeywordsString{"example.jp"}} req, err := cl.ListAll(zoneList, searchParam) if err != nil { panic(err) } fmt.Printf("RequestID: %s\n", req) for _, item := range zoneList.Items { fmt.Println(item) } } ```golang-iij-dpf-0.9.1/boilerplate.go.txt000066400000000000000000000020641437707610400177720ustar00rootroot00000000000000/* MIT License Copyright (c) 2021 Manabu Sonoda 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. */ golang-iij-dpf-0.9.1/codecov.yml000066400000000000000000000000521437707610400164630ustar00rootroot00000000000000ignore: - "**/ZZ_deepcopy_generated.go" golang-iij-dpf-0.9.1/go.mod000066400000000000000000000020721437707610400154300ustar00rootroot00000000000000module github.com/mimuret/golang-iij-dpf go 1.16 require ( github.com/google/go-querystring v1.1.0 github.com/google/uuid v1.3.0 github.com/jarcoal/httpmock v1.0.8 github.com/json-iterator/go v1.1.12 github.com/miekg/dns v1.1.47 github.com/onsi/ginkgo v1.16.4 github.com/onsi/gomega v1.18.1 ) require ( github.com/fsnotify/fsnotify v1.5.1 // indirect github.com/google/go-cmp v0.5.7 // indirect github.com/kr/text v0.2.0 // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e // indirect github.com/onsi/ginkgo/v2 v2.1.3 // indirect github.com/stretchr/testify v1.7.1 // indirect golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2 // indirect golang.org/x/sys v0.0.0-20220209214540-3681064d5158 // indirect golang.org/x/text v0.3.7 // indirect golang.org/x/time v0.3.0 // indirect google.golang.org/protobuf v1.27.1 // indirect gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f // indirect gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b // indirect ) golang-iij-dpf-0.9.1/go.sum000066400000000000000000000356051437707610400154650ustar00rootroot00000000000000github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI= github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI= github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU= github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= github.com/fsnotify/fsnotify v1.5.1 h1:mZcQUHVQUQWoPXXtuf9yuEXKudkV2sx1E06UadKWpgI= github.com/fsnotify/fsnotify v1.5.1/go.mod h1:T3375wBYaZdLLcVNkcVbzGHY7f1l/uK5T5Ai1i3InKU= github.com/go-task/slim-sprig v0.0.0-20210107165309-348f09dbbbc0/go.mod h1:fyg7847qk6SyHyPtNmDHnmrv/HOrqktSC+C9fM+CJOE= github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= github.com/golang/protobuf v1.5.2 h1:ROPKBNFfQgOUMifHyP+KYbvpjbdoFNs+aK7DXlji0Tw= github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.7 h1:81/ik6ipDQS2aGcBfIN5dHDB36BwrStyeAQquSYCV4o= github.com/google/go-cmp v0.5.7/go.mod h1:n+brtR0CgQNWTVd5ZUFpTBC8YFBDLK/h/bpaJ8/DtOE= github.com/google/go-querystring v1.1.0 h1:AnCroh3fv4ZBgVIf1Iwtovgjaw/GiKJo8M8yD/fhyJ8= github.com/google/go-querystring v1.1.0/go.mod h1:Kcdr2DB4koayq7X8pmAG4sNG59So17icRSOU623lUBU= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/pprof v0.0.0-20210407192527-94a9f03dee38/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I= github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= github.com/jarcoal/httpmock v1.0.8 h1:8kI16SoO6LQKgPE7PvQuV+YuD/inwHd7fOOe2zMbo4k= github.com/jarcoal/httpmock v1.0.8/go.mod h1:ATjnClrvW/3tijVmpL/va5Z3aAyGvqU3gCT8nX0Txik= github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/miekg/dns v1.1.47 h1:J9bWiXbqMbnZPcY8Qi2E3EWIBsIm6MZzzJB9VRg5gL8= github.com/miekg/dns v1.1.47/go.mod h1:e3IlAVfNqAllflbibAZEWOXOQ+Ynzk/dDozDxY7XnME= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs= github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A= github.com/nxadm/tail v1.4.8 h1:nPr65rt6Y5JFSKQO7qToXr7pePgD6Gwiw05lkbyAQTE= github.com/nxadm/tail v1.4.8/go.mod h1:+ncqLTQzXmGhMZNUePPaPqPvBxHAIsmXswZKocGu+AU= github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108oapk= github.com/onsi/ginkgo v1.16.4 h1:29JGrr5oVBm5ulCWet69zQkzWipVXIol6ygQUe/EzNc= github.com/onsi/ginkgo v1.16.4/go.mod h1:dX+/inL/fNMqNlz0e9LfyB9TswhZpCVdJM/Z6Vvnwo0= github.com/onsi/ginkgo/v2 v2.0.0/go.mod h1:vw5CSIxN1JObi/U8gcbwft7ZxR2dgaR70JSE3/PpL4c= github.com/onsi/ginkgo/v2 v2.1.3 h1:e/3Cwtogj0HA+25nMP1jCMDIf8RtRYbGwGGuBIFztkc= github.com/onsi/ginkgo/v2 v2.1.3/go.mod h1:vw5CSIxN1JObi/U8gcbwft7ZxR2dgaR70JSE3/PpL4c= github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY= github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo= github.com/onsi/gomega v1.17.0/go.mod h1:HnhC7FXeEQY45zxNK3PPoIUhzk/80Xly9PcubAlGdZY= github.com/onsi/gomega v1.18.1 h1:M1GfJqGRrBrrGGsbxzV5dqM2U2ApXefZCQpkukxYRLE= github.com/onsi/gomega v1.18.1/go.mod h1:0q+aL8jAiMXy9hbwj2mr5GziHiwhAIQpFmmtT5hitRs= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= github.com/stretchr/testify v1.7.1 h1:5TQK59W5E3v0r2duFAb7P95B6hEeOyEnHRa8MjYSMTY= github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.4.2 h1:Gz96sIWK3OalVv/I/qNygP42zyoKp3xptRVCWRFEBvo= golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200520004742-59133d7f0dd7/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM= golang.org/x/net v0.0.0-20210428140749-89ef3d95e781/go.mod h1:OJAsFXCWl8Ukc7SiCT/9KSuxbyM7479/AVlXFRxuMCk= golang.org/x/net v0.0.0-20210726213435-c6fcb2dbf985/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2 h1:CIJ76btIcR3eFI5EgSo6k1qKw9KJexJuRLI9G7Hp5wE= golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20210220032951-036812b2e83c h1:5KslGYwFpkhGh+Q16bwMP3cOontH8FOep7tGV86Y7SQ= golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190904154756-749cb33beabd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191204072324-ce4227a45e2e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210112080510-489259a85091/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220209214540-3681064d5158 h1:rm+CHSpPEEW2IsXUib1ThaHIjuBVZjxNgSKmBLFfD4c= golang.org/x/sys v0.0.0-20220209214540-3681064d5158/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7 h1:olpwvP2KacW1ZWvsR7uQhoyTYvKAupfQrRGBFM352Gk= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/time v0.3.0 h1:rg5rLMjNzMS1RkNLzCG38eapWhnYLFYXDXj2gOlr8j4= golang.org/x/time v0.3.0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20201224043029-2b0845dc783e/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.1.6-0.20210726203631-07bc1bf47fb2 h1:BonxutuHCTL0rBDnZlKjpGIQFTjyUVTexFOdWkB6Fg0= golang.org/x/tools v0.1.6-0.20210726203631-07bc1bf47fb2/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= google.golang.org/protobuf v1.27.1 h1:SnqbnDw1V7RiZcXPx5MEeqPv2s79L9i7BJUlG/+RurQ= google.golang.org/protobuf v1.27.1/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f h1:BLraFXnmrev5lT+xlilqcH8XK9/i0At2xKjWk4p6zsU= gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b h1:h8qDotaEPuJATrMmW04NCwg7v22aHH28wwpauUhK9Oo= gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= golang-iij-dpf-0.9.1/pkg/000077500000000000000000000000001437707610400151025ustar00rootroot00000000000000golang-iij-dpf-0.9.1/pkg/api/000077500000000000000000000000001437707610400156535ustar00rootroot00000000000000golang-iij-dpf-0.9.1/pkg/api/action.go000066400000000000000000000016121437707610400174570ustar00rootroot00000000000000package api import "net/http" type Action string const ( ActionCreate Action = "Create" ActionRead Action = "Read" ActionList Action = "List" ActionUpdate Action = "Update" ActionDelete Action = "Delete" ActionCount Action = "Count" ActionCancel Action = "Cancel" ActionApply Action = "Apply" ) func Actions() []Action { return []Action{ ActionCreate, ActionRead, ActionList, ActionUpdate, ActionDelete, ActionCount, ActionCancel, ActionApply, } } func (a Action) ToMethod() string { switch a { case ActionCreate: return http.MethodPost case ActionRead: return http.MethodGet case ActionList: return http.MethodGet case ActionUpdate: return http.MethodPatch case ActionDelete: return http.MethodDelete case ActionCount: return http.MethodGet case ActionCancel: return http.MethodDelete case ActionApply: return http.MethodPatch } return "" } golang-iij-dpf-0.9.1/pkg/api/action_test.go000066400000000000000000000032021437707610400205130ustar00rootroot00000000000000package api_test import ( "net/http" "github.com/mimuret/golang-iij-dpf/pkg/api" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("Action", func() { Context("Actions", func() { It("returns actions", func() { Expect(api.Actions()).NotTo(BeEmpty()) }) }) Context("ToMethod", func() { When("ActionCreate", func() { It("returns http.MethodPost", func() { Expect(api.ActionCreate.ToMethod()).To(Equal(http.MethodPost)) }) }) When("ActionRead", func() { It("returns http.MethodGet", func() { Expect(api.ActionRead.ToMethod()).To(Equal(http.MethodGet)) }) }) When("ActionCreate", func() { It("returns http.MethodGet", func() { Expect(api.ActionList.ToMethod()).To(Equal(http.MethodGet)) }) }) When("ActionUpdate", func() { It("returns http.MethodPatch", func() { Expect(api.ActionUpdate.ToMethod()).To(Equal(http.MethodPatch)) }) }) When("ActionDelete", func() { It("returns http.MethodDelete", func() { Expect(api.ActionDelete.ToMethod()).To(Equal(http.MethodDelete)) }) }) When("ActionCount", func() { It("returns http.MethodGet", func() { Expect(api.ActionCount.ToMethod()).To(Equal(http.MethodGet)) }) }) When("ActionCancel", func() { It("returns http.MethodDelete", func() { Expect(api.ActionCancel.ToMethod()).To(Equal(http.MethodDelete)) }) }) When("ActionApply", func() { It("returns http.MethodPatch", func() { Expect(api.ActionApply.ToMethod()).To(Equal(http.MethodPatch)) }) }) When("OTHER", func() { It("returns empty", func() { Expect(api.Action("hoge").ToMethod()).To(Equal("")) }) }) }) }) golang-iij-dpf-0.9.1/pkg/api/client.go000066400000000000000000000254471437707610400174740ustar00rootroot00000000000000package api import ( "bytes" "context" "fmt" "io" "io/ioutil" "net/http" "os" "reflect" "time" "golang.org/x/time/rate" ) const DefaultEndpoint = "https://api.dns-platform.jp/dpf/v1" type ClientInterface interface { SetRoundTripper(rt http.RoundTripper) Read(ctx context.Context, s Spec) (string, error) List(ctx context.Context, s ListSpec, keywords SearchParams) (string, error) ListAll(ctx context.Context, s CountableListSpec, keywords SearchParams) (string, error) Count(ctx context.Context, s CountableListSpec, keywords SearchParams) (string, error) Update(ctx context.Context, s Spec, body interface{}) (string, error) Create(ctx context.Context, s Spec, body interface{}) (string, error) Apply(ctx context.Context, s Spec, body interface{}) (string, error) Delete(ctx context.Context, s Spec) (string, error) Cancel(ctx context.Context, s Spec) (string, error) WatchRead(ctx context.Context, interval time.Duration, s Spec) error WatchList(ctx context.Context, interval time.Duration, s ListSpec, keyword SearchParams) error WatchListAll(ctx context.Context, interval time.Duration, s CountableListSpec, keyword SearchParams) error } var _ ClientInterface = &Client{} type Client struct { Endpoint string Token string logger Logger client *http.Client LastRequest *RequestInfo LastResponse *ResponseInfo } type RequestInfo struct { Method string URL string Body []byte } type ResponseInfo struct { Response *http.Response Body []byte } type RateRoundTripper struct { RroundTripper http.RoundTripper Limiter *rate.Limiter } func NewRateRoundTripper(rt http.RoundTripper, limiter *rate.Limiter) *RateRoundTripper { return &RateRoundTripper{ RroundTripper: rt, Limiter: limiter, } } func (r *RateRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) { if r.Limiter == nil { r.Limiter = rate.NewLimiter(rate.Limit(1.0), 5) } if r.RroundTripper == nil { r.RroundTripper = http.DefaultTransport } if err := r.Limiter.Wait(req.Context()); err != nil { return nil, fmt.Errorf("request rate-limit by client side: %w", err) } return r.RroundTripper.RoundTrip(req) } func NewClient(token string, endpoint string, logger Logger) *Client { if endpoint == "" { endpoint = DefaultEndpoint } if logger == nil { logger = NewStdLogger(os.Stderr, "dpf-client", 0, 4) } return &Client{Endpoint: endpoint, Token: token, logger: logger, client: &http.Client{Transport: NewRateRoundTripper(nil, nil)}} } func (c *Client) SetRoundTripper(rt http.RoundTripper) { c.client.Transport = rt } func (c *Client) marshalJSON(action Action, body interface{}) ([]byte, error) { var ( jsonBody []byte err error ) switch action { case ActionCreate: jsonBody, err = JSON.MarshalCreate(body) case ActionUpdate: jsonBody, err = JSON.MarshalUpdate(body) case ActionApply: jsonBody, err = JSON.MarshalApply(body) default: return nil, fmt.Errorf("not support action `%s` with body request", action) } if err != nil { return nil, fmt.Errorf("failed to encode body to json: %w", err) } return jsonBody, nil } func (c *Client) doSetup(ctx context.Context, spec Spec, action Action, body interface{}, params SearchParams) (*http.Request, error) { var r io.Reader if action == ActionCount { _, ok := spec.(CountableListSpec) if !ok { return nil, fmt.Errorf("spec is not CountableListSpec") } } c.LastRequest = &RequestInfo{} c.LastResponse = nil // create URL method, path := spec.GetPathMethod(action) if path == "" { return nil, fmt.Errorf("not support action %s", action) } c.LastRequest.Method = method url := c.Endpoint + path if params != nil { p, err := params.GetValues() if err != nil { return nil, fmt.Errorf("failed to get search params: %w", err) } url += "?" + p.Encode() } c.LastRequest.URL = url c.logger.Debugf("method: %s request-url: %s", method, url) // make request body if body != nil { jsonBody, err := c.marshalJSON(action, body) if err != nil { return nil, err } c.logger.Tracef("request-body: `%s`", string(jsonBody)) c.LastRequest.Body = jsonBody r = bytes.NewBuffer(jsonBody) } // make request req, err := http.NewRequest(method, url, r) if err != nil { return nil, fmt.Errorf("failed to create http request: %w", err) } // authorized req.Header.Add("Authorization", "Bearer "+c.Token) req.Header.Add("Content-Type", "application/json") return req.WithContext(ctx), nil } func (c *Client) Do(ctx context.Context, spec Spec, action Action, body interface{}, params SearchParams) (string, error) { req, err := c.doSetup(ctx, spec, action, body, params) if err != nil { return "", err } // request resp, err := c.client.Do(req) if err != nil { return "", fmt.Errorf("failed to get http response: %w", err) } defer resp.Body.Close() c.LastResponse = &ResponseInfo{ Response: resp, } // get body bs, err := ioutil.ReadAll(resp.Body) if err != nil { return "", fmt.Errorf("failed to get http response body: %w", err) } c.LastResponse.Body = bs c.logger.Debugf("status-code: `%d`", resp.StatusCode) c.logger.Tracef("response-body: `%s`", string(bs)) // if statiscode is error, response body type is BadResponse or Plantext if resp.StatusCode >= http.StatusBadRequest { badRequest := &BadResponse{StatusCode: resp.StatusCode} if err := UnmarshalRead(bs, badRequest); err != nil { return "", fmt.Errorf("failed to request: status code: %d body: %s err: %w", resp.StatusCode, string(bs), err) } return badRequest.RequestID, badRequest } // parse raw response rawResponse := &RawResponse{} if err := UnmarshalRead(bs, rawResponse); err != nil { // maybe not executed return "", fmt.Errorf("failed to parse get response: %w", err) } if req.Method == http.MethodGet { if err := c.doReadResponse(action, spec, bs, rawResponse); err != nil { return rawResponse.RequestID, err } } // initialize process if d, ok := spec.(Initializer); ok { d.Init() } return rawResponse.RequestID, nil } func (c *Client) doReadResponse(action Action, spec Spec, bs []byte, rawResponse *RawResponse) error { switch { case action == ActionCount: // ActionCount count := &Count{} if err := UnmarshalRead(rawResponse.Result, count); err != nil { return fmt.Errorf("failed to parse count response result: %w", err) } if cl, ok := spec.(CountableListSpec); ok { cl.SetCount(count.Count) } case rawResponse.Result != nil: // ActionRead if err := UnmarshalRead(rawResponse.Result, spec); err != nil { return fmt.Errorf("failed to parse response result: %w", err) } case rawResponse.Results != nil: // ActionList listSpec, ok := spec.(ListSpec) if !ok { return fmt.Errorf("not support ListSpec %s", spec.GetName()) } items := listSpec.GetItems() if err := UnmarshalRead(rawResponse.Results, items); err != nil { return fmt.Errorf("failed to parse list response results: %w", err) } default: if err := UnmarshalRead(bs, spec); err != nil { return fmt.Errorf("failed to parse response result: %w", err) } } return nil } func (c *Client) Read(ctx context.Context, s Spec) (string, error) { return c.Do(ctx, s, ActionRead, nil, nil) } func (c *Client) List(ctx context.Context, s ListSpec, keywords SearchParams) (string, error) { return c.Do(ctx, s, ActionList, nil, keywords) } func (c *Client) ListAll(ctx context.Context, s CountableListSpec, keywords SearchParams) (string, error) { req, err := c.Count(ctx, s, keywords) if err != nil { return req, err } if keywords == nil { keywords = &CommonSearchParams{} keywords.SetLimit(s.GetMaxLimit()) } count := s.GetCount() cList := DeepCopyCountableListSpec(s) for offset := int32(0); offset < count; offset += keywords.GetLimit() { keywords.SetOffset(offset) req, err = c.List(ctx, cList, keywords) if err != nil { return req, err } for i := 0; i < cList.Len(); i++ { s.AddItem(cList.Index(i)) } } return req, nil } func (c *Client) Count(ctx context.Context, s CountableListSpec, keywords SearchParams) (string, error) { return c.Do(ctx, s, ActionCount, nil, keywords) } func (c *Client) Update(ctx context.Context, s Spec, body interface{}) (string, error) { if body == nil { body = s } return c.Do(ctx, s, ActionUpdate, body, nil) } func (c *Client) Create(ctx context.Context, s Spec, body interface{}) (string, error) { if body == nil { body = s } return c.Do(ctx, s, ActionCreate, body, nil) } func (c *Client) Apply(ctx context.Context, s Spec, body interface{}) (string, error) { if body == nil { body = s } return c.Do(ctx, s, ActionApply, body, nil) } func (c *Client) Delete(ctx context.Context, s Spec) (string, error) { return c.Do(ctx, s, ActionDelete, nil, nil) } func (c *Client) Cancel(ctx context.Context, s Spec) (string, error) { return c.Do(ctx, s, ActionCancel, nil, nil) } func (c *Client) watch(ctx context.Context, interval time.Duration, f func(context.Context) (keep bool, err error)) error { if interval < time.Second { return fmt.Errorf("interval must greater than equals to 1s") } ticker := time.NewTicker(interval) defer ticker.Stop() LOOP: for { select { case <-ticker.C: loopBreak, err := f(ctx) if err != nil { return err } if loopBreak { break LOOP } case <-ctx.Done(): break LOOP } } return ctx.Err() } // ctx should set Deadline or Timeout // interval must be grater than equals to 1s // s is Readable Spec. func (c *Client) WatchRead(ctx context.Context, interval time.Duration, s Spec) error { org := DeepCopySpec(s) return c.watch(ctx, interval, func(cctx context.Context) (bool, error) { _, err := c.Read(cctx, s) if err != nil { return true, err } if reflect.DeepEqual(s, org) { return false, nil } return true, nil }) } // ctx should set Deadline or Timeout // interval must be grater than equals to 1s // s is ListAble Spec. func (c *Client) WatchList(ctx context.Context, interval time.Duration, s ListSpec, keyword SearchParams) error { org := DeepCopyListSpec(s) return c.watch(ctx, interval, func(cctx context.Context) (bool, error) { _, err := c.List(cctx, s, keyword) if err != nil { return true, err } if reflect.DeepEqual(s, org) { return false, nil } return true, nil }) } // ctx should set Deadline or Timeout // interval must be grater than equals to 1s // s is CountableListSpec Spec. func (c *Client) WatchListAll(ctx context.Context, interval time.Duration, s CountableListSpec, keyword SearchParams) error { copySpec := DeepCopyCountableListSpec(s) copySpec.ClearItems() err := c.watch(ctx, interval, func(cctx context.Context) (bool, error) { _, err := c.ListAll(cctx, copySpec, keyword) if err != nil { return true, err } if reflect.DeepEqual(s, copySpec) { return false, nil } return true, nil }) if err != nil { return err } s.ClearItems() for i := 0; i < copySpec.Len(); i++ { s.AddItem(copySpec.Index(i)) } s.SetCount(int32(copySpec.Len())) return nil } golang-iij-dpf-0.9.1/pkg/api/client_test.go000066400000000000000000001113511437707610400205210ustar00rootroot00000000000000package api_test import ( "context" "encoding/json" "fmt" "io" "net/http" "net/url" "testing/iotest" "time" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "golang.org/x/time/rate" "github.com/jarcoal/httpmock" "github.com/mimuret/golang-iij-dpf/pkg/api" . "github.com/mimuret/golang-iij-dpf/pkg/testtool" ) var _ api.SearchParams = &TestParams{} type TestParams struct { Values url.Values Err error } func (t *TestParams) GetValues() (url.Values, error) { return t.Values, t.Err } func (t *TestParams) GetOffset() int32 { return 0 } func (t *TestParams) SetOffset(int32) { } func (t *TestParams) GetLimit() int32 { return 100 } func (t *TestParams) SetLimit(int32) { } type ErrSpec struct { TestSpec ErrMarshalJSON error ErrUnmarshalJSON error } func (t *ErrSpec) MarshalJSON() ([]byte, error) { if t.ErrMarshalJSON != nil { return nil, t.ErrMarshalJSON } return json.Marshal(t.TestSpec) } func (t *ErrSpec) UnmarshalJSON(bs []byte) error { if t.ErrUnmarshalJSON != nil { return t.ErrUnmarshalJSON } return json.Unmarshal(bs, &t.TestSpec) } var _ = Describe("Client", func() { var ( testSpec *TestSpec errSpec *ErrSpec listTestSpec *TestSpecList countableList *TestSpecCountableList c *api.Client reqId string err error ) BeforeEach(func() { testSpec = &TestSpec{} errSpec = &ErrSpec{} listTestSpec = &TestSpecList{} countableList = &TestSpecCountableList{} c = api.NewClient("token", "http://localhost", nil) httpmock.RegisterNoResponder(httpmock.NewBytesResponder(404, []byte(`{ "request_id": "F96C25C6B13E49E59F0093BCD8D731AB", "error_type": "NotFound", "error_message": "Specified resource not found." }`))) c.SetRoundTripper(api.NewRateRoundTripper(nil, rate.NewLimiter(rate.Inf, 0))) }) Context("NewClient", func() { BeforeEach(func() { c = api.NewClient("", "", nil) }) It("Endpoint = DefaultEndpoint", func() { Expect(c.Endpoint).To(Equal(api.DefaultEndpoint)) }) }) Context("Do", func() { BeforeEach(func() { httpmock.RegisterResponder(http.MethodGet, "http://localhost/tests/F2246BD8617444329A40470AEC7B00B9", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "0CAC3AEFB6334ECCA7B70AF76D73508B", "result": { "id": "F2246BD8617444329A40470AEC7B00B9", "name": "test1", "number": 1 } }`))) }) AfterEach(func() { httpmock.Reset() }) When("the API succesfully", func() { BeforeEach(func() { testSpec.ID = "F2246BD8617444329A40470AEC7B00B9" reqId, err = c.Do(context.Background(), testSpec, api.ActionRead, nil, nil) }) It("reqId is not empty", func() { Expect(reqId).Should(Equal("0CAC3AEFB6334ECCA7B70AF76D73508B")) }) It("err is empty", func() { Expect(err).To(Succeed()) }) }) When("action is ActionCount", func() { When("spec is not CountableListSpec", func() { BeforeEach(func() { reqId, err = c.Do(context.Background(), listTestSpec, api.ActionCount, nil, nil) }) It("reqId is empty", func() { Expect(reqId).Should(Equal("")) }) It("err is not empty", func() { Expect(err).To(HaveOccurred()) Expect(err.Error()).To(MatchRegexp("spec is not CountableListSpec")) }) }) }) When("spec.GetPathMethod is empty", func() { BeforeEach(func() { reqId, err = c.Do(context.Background(), listTestSpec, api.ActionApply, nil, nil) }) It("reqId is empty", func() { Expect(reqId).Should(Equal("")) }) It("err is not empty", func() { Expect(err).To(HaveOccurred()) Expect(err.Error()).To(MatchRegexp("not support action")) }) }) When("SearchParams.GetValues() is error", func() { BeforeEach(func() { param := &TestParams{Err: fmt.Errorf("err")} reqId, err = c.Do(context.Background(), testSpec, api.ActionApply, nil, param) }) It("reqId is empty", func() { Expect(reqId).Should(Equal("")) }) It("err is not empty", func() { Expect(err).To(HaveOccurred()) Expect(err.Error()).To(MatchRegexp("failed to get search params:")) }) }) When("body is not nil, but action is not any of ActionCreate, ActionUpdate and ActionApply.", func() { BeforeEach(func() { reqId, err = c.Do(context.Background(), testSpec, api.ActionRead, testSpec, nil) }) It("reqId is empty", func() { Expect(reqId).Should(Equal("")) }) It("err is not empty", func() { Expect(err).To(HaveOccurred()) Expect(err.Error()).To(MatchRegexp("not support action")) }) }) When("action is ActionCreate. body is not nil,but failed to encode to json", func() { BeforeEach(func() { errSpec.ErrMarshalJSON = fmt.Errorf("fail") reqId, err = c.Do(context.Background(), errSpec, api.ActionCreate, errSpec, nil) }) It("reqId is empty", func() { Expect(reqId).Should(Equal("")) }) It("err is not empty", func() { Expect(err).To(HaveOccurred()) Expect(err.Error()).To(MatchRegexp("failed to encode body to json")) }) }) When("action is ActionUpdate. body is not nil. but but failed to encode to json", func() { BeforeEach(func() { errSpec.ErrMarshalJSON = fmt.Errorf("fail") reqId, err = c.Do(context.Background(), errSpec, api.ActionUpdate, errSpec, nil) }) It("reqId is empty", func() { Expect(reqId).Should(Equal("")) }) It("err is not empty", func() { Expect(err).To(HaveOccurred()) Expect(err.Error()).To(MatchRegexp("failed to encode body to json")) }) }) When("action ActionApply. body is not nil. but failed to encode to json", func() { BeforeEach(func() { errSpec.ErrMarshalJSON = fmt.Errorf("fail") reqId, err = c.Do(context.Background(), errSpec, api.ActionApply, errSpec, nil) }) It("reqId is empty", func() { Expect(reqId).Should(Equal("")) }) It("err is not empty", func() { Expect(err).To(HaveOccurred()) Expect(err.Error()).To(MatchRegexp("failed to encode body to json")) }) }) When("endpoint url is invalid", func() { BeforeEach(func() { cl := api.NewClient("", "", nil) cl.Endpoint = "\n" reqId, err = cl.Do(context.Background(), errSpec, api.ActionRead, nil, nil) }) It("reqId is empty", func() { Expect(reqId).Should(Equal("")) }) It("err is not empty", func() { Expect(err).To(HaveOccurred()) Expect(err.Error()).To(MatchRegexp("failed to create http request")) }) }) When("failed to get http response", func() { BeforeEach(func() { httpmock.Reset() cl := api.NewClient("", "https://localhost/hoge", nil) reqId, err = cl.Do(context.Background(), errSpec, api.ActionRead, nil, nil) }) It("reqId is empty", func() { Expect(reqId).Should(Equal("")) }) It("err is not empty", func() { Expect(err).To(HaveOccurred()) Expect(err.Error()).To(MatchRegexp("failed to get http response")) }) }) When("failed to get http response body", func() { BeforeEach(func() { httpmock.Reset() httpmock.RegisterResponder(http.MethodGet, "https://localhost/hoge/tests/fuga", func(r *http.Request) (*http.Response, error) { return &http.Response{StatusCode: 200, Body: io.NopCloser(iotest.ErrReader(fmt.Errorf("error")))}, nil }) errSpec.ID = "fuga" cl := api.NewClient("", "https://localhost/hoge", nil) reqId, err = cl.Do(context.Background(), errSpec, api.ActionRead, nil, nil) }) It("reqId is empty", func() { Expect(reqId).Should(Equal("")) }) It("err is not empty", func() { Expect(err).To(HaveOccurred()) Expect(err.Error()).To(MatchRegexp("failed to get http response body:")) }) }) Context("status code >= 400", func() { When("recv body is not json format", func() { BeforeEach(func() { httpmock.RegisterResponder(http.MethodGet, "http://localhost/tests/Unavailable", httpmock.NewBytesResponder(503, []byte(`Service Unavailable`))) testSpec.ID = "Unavailable" reqId, err = c.Do(context.Background(), testSpec, api.ActionRead, nil, nil) }) It("reqId is empty", func() { Expect(reqId).Should(Equal("")) }) It("err is not empty", func() { Expect(err).To(HaveOccurred()) Expect(err.Error()).To(MatchRegexp("failed to request: status code")) }) }) When("recv body is json format", func() { BeforeEach(func() { httpmock.RegisterResponder(http.MethodGet, "http://localhost/tests/ERROR-BAD_REQUEST", httpmock.NewBytesResponder(400, []byte(`{ "request_id": "F96C25C6B13E49E59F0093BCD8D731AB", "error_type": "fail", "error_message": "error message" }`))) testSpec.ID = "ERROR-BAD_REQUEST" reqId, err = c.Do(context.Background(), testSpec, api.ActionRead, nil, nil) }) It("reqId is not empty", func() { Expect(reqId).Should(Equal("F96C25C6B13E49E59F0093BCD8D731AB")) }) It("err is not empty", func() { Expect(err).To(HaveOccurred()) Expect(err.Error()).To(MatchRegexp("ErrorType: fail Message: error message")) }) }) }) }) Context("Read", func() { BeforeEach(func() { httpmock.RegisterResponder(http.MethodGet, "http://localhost/tests/F2246BD8617444329A40470AEC7B00B9", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "0CAC3AEFB6334ECCA7B70AF76D73508B", "result": { "id": "F2246BD8617444329A40470AEC7B00B9", "name": "test1", "number": 1 } }`))) httpmock.RegisterResponder(http.MethodGet, "http://localhost/tests/86E5EB52E2294614B35F01943AB7239A", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "86E5EB52E2294614B35F01943AB7239A", "result": { "id": "86E5EB52E2294614B35F01943AB7239A", "name": "failed", "number": "1" } }`))) httpmock.RegisterResponder(http.MethodGet, "http://localhost/tests/NOTFOUND", httpmock.NewBytesResponder(404, []byte(`{ "request_id": "F96C25C6B13E49E59F0093BCD8D731AB", "error_type": "NotFound", "error_message": "Specified resource not found." }`))) httpmock.RegisterResponder(http.MethodGet, "http://localhost/tests/41874381FD914D88B24A759155B5F0F8", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "41874381FD914D88B24A759155B5F0F8", "results": [ { "id": "86E5EB52E2294614B35F01943AB7239A", "name": "failed", "number": "1" } ] }`))) httpmock.RegisterResponder(http.MethodGet, "http://localhost/tests/83870F11B3F24AE89888C86F497EF697", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "83870F11B3F24AE89888C86F497EF697", "id": "83870F11B3F24AE89888C86F497EF697", "name": "failed", "number": 1 }`))) httpmock.RegisterResponder(http.MethodGet, "http://localhost/tests/72AA019055524D09A4C367DD96DCE0F9", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "72AA019055524D09A4C367DD96DCE0F9", "id": "72AA019055524D09A4C367DD96DCE0F9", "name": "failed", "number": "1" }`))) httpmock.RegisterResponder(http.MethodGet, "http://localhost/tests/NOT_JSON", httpmock.NewBytesResponder(200, []byte(`{1}`))) httpmock.RegisterResponder(http.MethodGet, "http://localhost/tests/TIMEOUT", func(r *http.Request) (*http.Response, error) { time.Sleep(2 * time.Second) return httpmock.NewStringResponse(500, "ERROR"), nil }) }) AfterEach(func() { httpmock.Reset() }) When("response timeout", func() { BeforeEach(func() { testSpec.ID = "TIMEOUT" ctx, cancel := context.WithTimeout(context.Background(), time.Second) defer cancel() _, err = c.Read(ctx, testSpec) }) It("is timeout", func() { Expect(err).To(HaveOccurred()) Expect(err).To(MatchError(context.DeadlineExceeded)) }) }) When("cancel", func() { BeforeEach(func() { testSpec.ID = "TIMEOUT" ctx, cancel := context.WithTimeout(context.Background(), time.Second) cancel() _, err = c.Read(ctx, testSpec) }) It("is timeout", func() { Expect(err).To(HaveOccurred()) Expect(err).To(MatchError(context.Canceled)) }) }) When("resource is exist", func() { BeforeEach(func() { testSpec.ID = "F2246BD8617444329A40470AEC7B00B9" reqId, err = c.Read(context.Background(), testSpec) }) It("reqId is not empty", func() { Expect(reqId).Should(Equal("0CAC3AEFB6334ECCA7B70AF76D73508B")) }) It("err is empty", func() { Expect(err).To(Succeed()) }) It("can get values", func() { Expect(testSpec.ID).To(Equal("F2246BD8617444329A40470AEC7B00B9")) Expect(testSpec.Name).To(Equal("test1")) Expect(testSpec.Number).To(Equal(int64(1))) }) }) When("resource is exist, but schema error", func() { BeforeEach(func() { testSpec.ID = "86E5EB52E2294614B35F01943AB7239A" reqId, err = c.Read(context.Background(), testSpec) }) It("reqId is not empty", func() { Expect(reqId).Should(Equal("86E5EB52E2294614B35F01943AB7239A")) }) It("err is not empty", func() { Expect(err).To(HaveOccurred()) Expect(err.Error()).To(MatchRegexp("failed to parse response result")) }) }) When("resource is exist, but response is list format", func() { BeforeEach(func() { testSpec.ID = "41874381FD914D88B24A759155B5F0F8" reqId, err = c.Read(context.Background(), testSpec) }) It("reqId is not empty", func() { Expect(reqId).Should(Equal("41874381FD914D88B24A759155B5F0F8")) }) It("err is not empty", func() { Expect(err).To(HaveOccurred()) Expect(err.Error()).To(MatchRegexp("not support ListSpec")) }) }) When("response is no frame format", func() { BeforeEach(func() { testSpec.ID = "83870F11B3F24AE89888C86F497EF697" reqId, err = c.Read(context.Background(), testSpec) }) It("reqId is not empty", func() { Expect(reqId).Should(Equal("83870F11B3F24AE89888C86F497EF697")) }) It("err is not empty", func() { Expect(testSpec.ID).To(Equal("83870F11B3F24AE89888C86F497EF697")) Expect(testSpec.Name).To(Equal("failed")) Expect(testSpec.Number).To(Equal(int64(1))) }) }) When("response is no frame format, but invalid schema", func() { BeforeEach(func() { testSpec.ID = "72AA019055524D09A4C367DD96DCE0F9" reqId, err = c.Read(context.Background(), testSpec) }) It("reqId is not empty", func() { Expect(reqId).Should(Equal("72AA019055524D09A4C367DD96DCE0F9")) }) It("err is not empty", func() { Expect(err).To(HaveOccurred()) Expect(err.Error()).To(MatchRegexp("failed to parse response result")) }) }) When("resource is not exist", func() { BeforeEach(func() { testSpec.ID = "NOTFOUND" reqId, err = c.Read(context.Background(), testSpec) }) It("reqId is not empty", func() { Expect(reqId).Should(Equal("F96C25C6B13E49E59F0093BCD8D731AB")) }) It("err is not empty", func() { Expect(err).To(HaveOccurred()) Expect(err.Error()).To(MatchRegexp("ErrorType: NotFound")) }) }) When("response is not json", func() { BeforeEach(func() { testSpec.ID = "NOT_JSON" reqId, err = c.Read(context.Background(), testSpec) }) It("err is not empty", func() { Expect(err).To(HaveOccurred()) Expect(err.Error()).To(MatchRegexp("failed to parse get response")) }) }) }) Context("List", func() { When("resource exist", func() { BeforeEach(func() { httpmock.RegisterResponder(http.MethodGet, "http://localhost/tests", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "0CAC3AEFB6334ECCA7B70AF76D73508B", "results": [ { "id": "F2246BD8617444329A40470AEC7B00B9", "name": "test1", "number": 1 }, { "id": "C79CE3B1C87B47FA9BC618E6C40C3BD1", "name": "test2", "number": 2 } ] }`))) reqId, err = c.List(context.Background(), listTestSpec, nil) }) AfterEach(func() { httpmock.Reset() }) It("reqId is not empty", func() { Expect(reqId).Should(Equal("0CAC3AEFB6334ECCA7B70AF76D73508B")) }) It("err is empty", func() { Expect(err).To(Succeed()) }) It("can get values", func() { Expect(*listTestSpec).To(Equal(TestSpecList{ Items: []TestSpec{ { ID: "F2246BD8617444329A40470AEC7B00B9", Name: "test1", Number: 1, }, { ID: "C79CE3B1C87B47FA9BC618E6C40C3BD1", Name: "test2", Number: 2, }, }, })) }) }) When("resource exist, but schema invalid", func() { BeforeEach(func() { httpmock.RegisterResponder(http.MethodGet, "http://localhost/tests", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "0CAC3AEFB6334ECCA7B70AF76D73508B", "results": [ { "id": "F2246BD8617444329A40470AEC7B00B9", "name": "test1", "number": "1" }, { "id": "C79CE3B1C87B47FA9BC618E6C40C3BD1", "name": "test2", "number": "2" } ] }`))) reqId, err = c.List(context.Background(), listTestSpec, nil) }) AfterEach(func() { httpmock.Reset() }) It("reqId is not empty", func() { Expect(reqId).Should(Equal("0CAC3AEFB6334ECCA7B70AF76D73508B")) }) It("err is not empty", func() { Expect(err).To(HaveOccurred()) Expect(err.Error()).To(MatchRegexp("failed to parse list response results")) }) }) When("resource not exist", func() { BeforeEach(func() { httpmock.RegisterResponder(http.MethodGet, "http://localhost/tests", httpmock.NewBytesResponder(404, []byte(`{ "request_id": "F96C25C6B13E49E59F0093BCD8D731AB", "error_type": "NotFound", "error_message": "Specified resource not found." }`))) reqId, err = c.List(context.Background(), listTestSpec, nil) }) AfterEach(func() { httpmock.Reset() }) It("reqId is not empty", func() { Expect(reqId).Should(Equal("F96C25C6B13E49E59F0093BCD8D731AB")) }) It("err is not empty", func() { Expect(err).To(HaveOccurred()) Expect(err.Error()).To(MatchRegexp("ErrorType: NotFound")) }) }) }) Context("ListAll", func() { BeforeEach(func() { httpmock.RegisterResponder(http.MethodGet, "http://localhost/tests?limit=1", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "B7B871E6357E453287E2D7A9590D195D", "results": [ { "id": "F2246BD8617444329A40470AEC7B00B9", "name": "test1", "number": 1 } ] }`))) httpmock.RegisterResponder(http.MethodGet, "http://localhost/tests?limit=1&offset=1", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "5F234DDF1D8E47D1BB26745D13FAE459", "results": [ { "id": "C79CE3B1C87B47FA9BC618E6C40C3BD1", "name": "test2", "number": 2 } ] }`))) httpmock.RegisterResponder(http.MethodGet, "http://localhost/tests/count", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "E5173B43AE7F4F8AB71168CDBEC75605", "result": { "count": 2 } }`))) }) AfterEach(func() { httpmock.Reset() }) When("resource exist", func() { BeforeEach(func() { reqId, err = c.ListAll(context.Background(), countableList, &api.CommonSearchParams{Limit: 1}) }) It("reqId is not empty", func() { Expect(reqId).Should(Equal("5F234DDF1D8E47D1BB26745D13FAE459")) }) It("err is empty", func() { Expect(err).To(Succeed()) }) It("can get values", func() { Expect(*countableList).To(Equal(TestSpecCountableList{ Count: api.Count{Count: 2}, TestSpecList: TestSpecList{ Items: []TestSpec{ { ID: "F2246BD8617444329A40470AEC7B00B9", Name: "test1", Number: 1, }, { ID: "C79CE3B1C87B47FA9BC618E6C40C3BD1", Name: "test2", Number: 2, }, }, }, })) }) }) When("resource not exist", func() { BeforeEach(func() { httpmock.RegisterResponder(http.MethodGet, "http://localhost/tests", httpmock.NewBytesResponder(404, []byte(`{ "request_id": "F96C25C6B13E49E59F0093BCD8D731AB", "error_type": "NotFound", "error_message": "Specified resource not found." }`))) reqId, err = c.ListAll(context.Background(), countableList, nil) }) It("reqId is not empty", func() { Expect(reqId).Should(Equal("F96C25C6B13E49E59F0093BCD8D731AB")) }) It("err is not empty", func() { Expect(err).To(HaveOccurred()) Expect(err.Error()).To(MatchRegexp("ErrorType: NotFound")) }) }) When("count value is invalid", func() { BeforeEach(func() { httpmock.RegisterResponder(http.MethodGet, "http://localhost/tests/count", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "E5173B43AE7F4F8AB71168CDBEC75605", "result": { "count": "2" } }`))) reqId, err = c.ListAll(context.Background(), countableList, nil) }) It("reqId is not empty", func() { Expect(reqId).Should(Equal("E5173B43AE7F4F8AB71168CDBEC75605")) }) It("err is not empty", func() { Expect(err).To(HaveOccurred()) }) }) }) Context("Count", func() { When("resource exist", func() { BeforeEach(func() { httpmock.RegisterResponder(http.MethodGet, "http://localhost/tests/count?limit=1", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "0CAC3AEFB6334ECCA7B70AF76D73508B", "result": { "count": 4 } }`))) reqId, err = c.Count(context.Background(), countableList, &api.CommonSearchParams{Limit: 1}) }) AfterEach(func() { httpmock.Reset() }) It("reqId is not empty", func() { Expect(reqId).Should(Equal("0CAC3AEFB6334ECCA7B70AF76D73508B")) }) It("err is empty", func() { Expect(err).To(Succeed()) }) It("can get values", func() { Expect(countableList.Count.Count).To(Equal(int32(4))) }) }) When("resource exist, but count format invalid", func() { BeforeEach(func() { httpmock.RegisterResponder(http.MethodGet, "http://localhost/tests/count?limit=1", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "0CAC3AEFB6334ECCA7B70AF76D73508B", "result": { "count": "4" } }`))) reqId, err = c.Count(context.Background(), countableList, &api.CommonSearchParams{Limit: 1}) }) AfterEach(func() { httpmock.Reset() }) It("reqId is not empty", func() { Expect(reqId).Should(Equal("0CAC3AEFB6334ECCA7B70AF76D73508B")) }) It("err is not empty", func() { Expect(err).To(HaveOccurred()) Expect(err.Error()).To(MatchRegexp("failed to parse count response result")) }) }) When("resource not exist", func() { BeforeEach(func() { reqId, err = c.Count(context.Background(), countableList, nil) }) It("reqId is not empty", func() { Expect(reqId).Should(Equal("F96C25C6B13E49E59F0093BCD8D731AB")) }) It("err is not empty", func() { Expect(err).To(HaveOccurred()) Expect(err.Error()).To(MatchRegexp("ErrorType: NotFound")) }) }) }) Context("Create", func() { AfterEach(func() { httpmock.Reset() }) When("request is successful", func() { BeforeEach(func() { httpmock.RegisterResponder(http.MethodPost, "http://localhost/tests", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "8C246D4DF69F4473AD9F90ADE0D4DAF2", "jobs_url": "https://dpi.dns-platform.jp/v1/jobs/8C246D4DF69F4473AD9F90ADE0D4DAF2" }`))) reqId, err = c.Create(context.Background(), testSpec, nil) }) AfterEach(func() { httpmock.Reset() }) It("reqId is not empty", func() { Expect(reqId).Should(Equal("8C246D4DF69F4473AD9F90ADE0D4DAF2")) }) It("err is empty", func() { Expect(err).To(Succeed()) }) }) When("request is failed", func() { BeforeEach(func() { httpmock.RegisterResponder(http.MethodPost, "http://localhost/tests", httpmock.NewBytesResponder(400, []byte(`{ "request_id": "61AC452CA8164E768D69BD878D2E0479", "error_type": "ParamaterError", "error_message": "There are invalid parameters.", "error_details": [ { "code": "invalid", "attribute": "schema" } ] }`))) reqId, err = c.Create(context.Background(), testSpec, nil) }) AfterEach(func() { httpmock.Reset() }) It("reqId is not empty", func() { Expect(reqId).Should(Equal("61AC452CA8164E768D69BD878D2E0479")) }) It("err is not empty", func() { Expect(err).To(HaveOccurred()) Expect(err.Error()).To(MatchRegexp("ErrorType: ParamaterError")) }) }) }) Context("Update", func() { AfterEach(func() { httpmock.Reset() }) BeforeEach(func() { testSpec.ID = "F2BF2DCC-D94C-4436-B199-7C7377184D06" }) When("request is successful", func() { BeforeEach(func() { httpmock.RegisterResponder(http.MethodPatch, "http://localhost/tests/F2BF2DCC-D94C-4436-B199-7C7377184D06", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "70F6B7C158BE4D31AB5201CEB9175185", "jobs_url": "https://dpi.dns-platform.jp/v1/jobs/70F6B7C158BE4D31AB5201CEB9175185" }`))) reqId, err = c.Update(context.Background(), testSpec, nil) }) AfterEach(func() { httpmock.Reset() }) It("reqId is not empty", func() { Expect(reqId).Should(Equal("70F6B7C158BE4D31AB5201CEB9175185")) }) It("err is empty", func() { Expect(err).To(Succeed()) }) }) When("request is failed", func() { BeforeEach(func() { httpmock.RegisterResponder(http.MethodPatch, "http://localhost/tests/F2BF2DCC-D94C-4436-B199-7C7377184D06", httpmock.NewBytesResponder(400, []byte(`{ "request_id": "9732ACCB6C09406AB7961AAC7241DA8F", "error_type": "ParamaterError", "error_message": "There are invalid parameters.", "error_details": [ { "code": "invalid", "attribute": "schema" } ] }`))) reqId, err = c.Update(context.Background(), testSpec, nil) }) AfterEach(func() { httpmock.Reset() }) It("reqId is not empty", func() { Expect(reqId).Should(Equal("9732ACCB6C09406AB7961AAC7241DA8F")) }) It("err is not empty", func() { Expect(err).To(HaveOccurred()) Expect(err.Error()).To(MatchRegexp("ErrorType: ParamaterError")) }) }) }) Context("Delete", func() { AfterEach(func() { httpmock.Reset() }) BeforeEach(func() { testSpec.ID = "665DB8DD-0280-44B6-B4C6-FEAFCDD90E8B" }) When("request is successful", func() { BeforeEach(func() { httpmock.RegisterResponder(http.MethodDelete, "http://localhost/tests/665DB8DD-0280-44B6-B4C6-FEAFCDD90E8B", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "64D5485D09F2440C880609406F2257DE", "jobs_url": "https://dpi.dns-platform.jp/v1/jobs/64D5485D09F2440C880609406F2257DE" }`))) reqId, err = c.Delete(context.Background(), testSpec) }) AfterEach(func() { httpmock.Reset() }) It("reqId is not empty", func() { Expect(reqId).Should(Equal("64D5485D09F2440C880609406F2257DE")) }) It("err is empty", func() { Expect(err).To(Succeed()) }) }) When("request is failed", func() { BeforeEach(func() { httpmock.RegisterResponder(http.MethodDelete, "http://localhost/tests/665DB8DD-0280-44B6-B4C6-FEAFCDD90E8B", httpmock.NewBytesResponder(400, []byte(`{ "request_id": "C33C12FCF7B3466EBA729981630A09E5", "error_type": "ParamaterError", "error_message": "There are invalid parameters.", "error_details": [ { "code": "invalid", "attribute": "schema" } ] }`))) reqId, err = c.Delete(context.Background(), testSpec) }) AfterEach(func() { httpmock.Reset() }) It("reqId is not empty", func() { Expect(reqId).Should(Equal("C33C12FCF7B3466EBA729981630A09E5")) }) It("err is not empty", func() { Expect(err).To(HaveOccurred()) Expect(err.Error()).To(MatchRegexp("ErrorType: ParamaterError")) }) }) }) Context("Cancel", func() { AfterEach(func() { httpmock.Reset() }) BeforeEach(func() { testSpec.ID = "BD1BC291-5763-408B-9D2E-A70434E4A810" }) When("request is successful", func() { BeforeEach(func() { httpmock.RegisterResponder(http.MethodDelete, "http://localhost/tests/BD1BC291-5763-408B-9D2E-A70434E4A810/cancel", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "EE891520C5894EC2B75B6002F01AA76F", "jobs_url": "https://dpi.dns-platform.jp/v1/jobs/EE891520C5894EC2B75B6002F01AA76F" }`))) reqId, err = c.Cancel(context.Background(), testSpec) }) AfterEach(func() { httpmock.Reset() }) It("reqId is not empty", func() { Expect(reqId).Should(Equal("EE891520C5894EC2B75B6002F01AA76F")) }) It("err is empty", func() { Expect(err).To(Succeed()) }) }) When("request is failed", func() { BeforeEach(func() { httpmock.RegisterResponder(http.MethodDelete, "http://localhost/tests/BD1BC291-5763-408B-9D2E-A70434E4A810/cancel", httpmock.NewBytesResponder(400, []byte(`{ "request_id": "86D4FEC9B34A4C1F9DE3E48285C860DB", "error_type": "ParamaterError", "error_message": "There are invalid parameters.", "error_details": [ { "code": "invalid", "attribute": "schema" } ] }`))) reqId, err = c.Cancel(context.Background(), testSpec) }) AfterEach(func() { httpmock.Reset() }) It("reqId is not empty", func() { Expect(reqId).Should(Equal("86D4FEC9B34A4C1F9DE3E48285C860DB")) }) It("err is not empty", func() { Expect(err).To(HaveOccurred()) Expect(err.Error()).To(MatchRegexp("ErrorType: ParamaterError")) }) }) }) Context("Apply", func() { AfterEach(func() { httpmock.Reset() }) BeforeEach(func() { testSpec.ID = "BD1BC291-5763-408B-9D2E-A70434E4A810" }) When("request is successful", func() { BeforeEach(func() { httpmock.RegisterResponder(http.MethodPatch, "http://localhost/tests/BD1BC291-5763-408B-9D2E-A70434E4A810/apply", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "EE891520C5894EC2B75B6002F01AA76F", "jobs_url": "https://dpi.dns-platform.jp/v1/jobs/EE891520C5894EC2B75B6002F01AA76F" }`))) reqId, err = c.Apply(context.Background(), testSpec, nil) }) AfterEach(func() { httpmock.Reset() }) It("reqId is not empty", func() { Expect(reqId).Should(Equal("EE891520C5894EC2B75B6002F01AA76F")) }) It("err is empty", func() { Expect(err).To(Succeed()) }) }) When("request is failed", func() { BeforeEach(func() { httpmock.RegisterResponder(http.MethodPatch, "http://localhost/tests/BD1BC291-5763-408B-9D2E-A70434E4A810/apply", httpmock.NewBytesResponder(400, []byte(`{ "request_id": "86D4FEC9B34A4C1F9DE3E48285C860DB", "error_type": "ParamaterError", "error_message": "There are invalid parameters.", "error_details": [ { "code": "invalid", "attribute": "schema" } ] }`))) reqId, err = c.Apply(context.Background(), testSpec, nil) }) AfterEach(func() { httpmock.Reset() }) It("reqId is not empty", func() { Expect(reqId).Should(Equal("86D4FEC9B34A4C1F9DE3E48285C860DB")) }) It("err is not empty", func() { Expect(err).To(HaveOccurred()) Expect(err.Error()).To(MatchRegexp("ErrorType: ParamaterError")) }) }) }) Context("WatchRead", func() { BeforeEach(func() { httpmock.RegisterResponder(http.MethodGet, "http://localhost/tests/F2246BD8617444329A40470AEC7B00B9", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "0CAC3AEFB6334ECCA7B70AF76D73508B", "result": { "id": "F2246BD8617444329A40470AEC7B00B9", "name": "test1", "number": 1 } }`))) testSpec.ID = "F2246BD8617444329A40470AEC7B00B9" }) AfterEach(func() { httpmock.Reset() }) When("change value", func() { BeforeEach(func() { err = c.WatchRead(context.Background(), time.Second, testSpec) }) It("get change value", func() { Expect(err).To(Succeed()) Expect(*testSpec).To(Equal(TestSpec{ ID: "F2246BD8617444329A40470AEC7B00B9", Name: "test1", Number: 1, })) }) }) When("timeout", func() { BeforeEach(func() { _, err = c.Read(context.Background(), testSpec) Expect(err).To(Succeed()) ctx, cancel := context.WithTimeout(context.Background(), time.Second*2) defer cancel() err = c.WatchRead(ctx, time.Second, testSpec) }) It("is timeout", func() { Expect(err).To(HaveOccurred()) Expect(err).To(MatchError(context.DeadlineExceeded)) }) }) When("interval less than 1s", func() { BeforeEach(func() { err = c.WatchRead(context.Background(), time.Microsecond, testSpec) }) It("returns error", func() { Expect(err).To(HaveOccurred()) Expect(err.Error()).To(MatchRegexp("interval must greater than equals to 1s")) }) }) When("read error", func() { BeforeEach(func() { testSpec.ID = "NOT_FOUND" err = c.WatchRead(context.Background(), time.Second, testSpec) }) It("return err", func() { Expect(err).To(HaveOccurred()) Expect(err.Error()).To(MatchRegexp("ErrorType: NotFound")) }) }) }) Context("WatchList", func() { BeforeEach(func() { httpmock.RegisterResponder(http.MethodGet, "http://localhost/tests", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "0CAC3AEFB6334ECCA7B70AF76D73508B", "results": [ { "id": "F2246BD8617444329A40470AEC7B00B9", "name": "test1", "number": 1 }, { "id": "C79CE3B1C87B47FA9BC618E6C40C3BD1", "name": "test2", "number": 2 } ] }`))) }) AfterEach(func() { httpmock.Reset() }) When("change value", func() { BeforeEach(func() { err = c.WatchList(context.Background(), time.Second, listTestSpec, nil) }) It("get change value", func() { Expect(err).To(Succeed()) Expect(*listTestSpec).To(Equal(TestSpecList{ Items: []TestSpec{ { ID: "F2246BD8617444329A40470AEC7B00B9", Name: "test1", Number: 1, }, { ID: "C79CE3B1C87B47FA9BC618E6C40C3BD1", Name: "test2", Number: 2, }, }, })) }) }) When("timeout", func() { BeforeEach(func() { _, err = c.List(context.Background(), listTestSpec, nil) Expect(err).To(Succeed()) ctx, cancel := context.WithTimeout(context.Background(), time.Second*2) defer cancel() err = c.WatchList(ctx, time.Second, listTestSpec, nil) }) It("is timeout", func() { Expect(err).To(HaveOccurred()) Expect(err).To(MatchError(context.DeadlineExceeded)) }) }) When("read error", func() { BeforeEach(func() { httpmock.RegisterResponder(http.MethodGet, "http://localhost/tests", httpmock.NewBytesResponder(404, []byte(`{ "request_id": "F96C25C6B13E49E59F0093BCD8D731AB", "error_type": "NotFound", "error_message": "Specified resource not found." }`))) err = c.WatchList(context.Background(), time.Second, listTestSpec, nil) }) It("return err", func() { Expect(err).To(HaveOccurred()) Expect(err.Error()).To(MatchRegexp("ErrorType: NotFound")) }) }) }) Context("WatchListAll", func() { BeforeEach(func() { httpmock.RegisterResponder(http.MethodGet, "http://localhost/tests?limit=1", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "B7B871E6357E453287E2D7A9590D195D", "results": [ { "id": "F2246BD8617444329A40470AEC7B00B9", "name": "test1", "number": 1 } ] }`))) httpmock.RegisterResponder(http.MethodGet, "http://localhost/tests?limit=1&offset=1", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "5F234DDF1D8E47D1BB26745D13FAE459", "results": [ { "id": "C79CE3B1C87B47FA9BC618E6C40C3BD1", "name": "test2", "number": 2 } ] }`))) httpmock.RegisterResponder(http.MethodGet, "http://localhost/tests/count", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "E5173B43AE7F4F8AB71168CDBEC75605", "result": { "count": 2 } }`))) }) AfterEach(func() { httpmock.Reset() }) When("change value", func() { BeforeEach(func() { err = c.WatchListAll(context.Background(), time.Second, countableList, &api.CommonSearchParams{Limit: 1}) }) It("get change value", func() { Expect(err).To(Succeed()) Expect(*countableList).To(Equal(TestSpecCountableList{ Count: api.Count{Count: 2}, TestSpecList: TestSpecList{ Items: []TestSpec{ { ID: "F2246BD8617444329A40470AEC7B00B9", Name: "test1", Number: 1, }, { ID: "C79CE3B1C87B47FA9BC618E6C40C3BD1", Name: "test2", Number: 2, }, }, }, })) }) }) When("timeout", func() { BeforeEach(func() { _, err = c.ListAll(context.Background(), countableList, &api.CommonSearchParams{Limit: 1}) Expect(err).To(Succeed()) ctx, cancel := context.WithTimeout(context.Background(), time.Second*2) defer cancel() err = c.WatchListAll(ctx, time.Second, countableList, &api.CommonSearchParams{Limit: 1}) }) It("is timeout", func() { Expect(err).To(HaveOccurred()) Expect(err).To(MatchError(context.DeadlineExceeded)) }) }) When("read error", func() { BeforeEach(func() { httpmock.RegisterResponder(http.MethodGet, "http://localhost/tests?limit=1&offset=1", httpmock.NewBytesResponder(404, []byte(`{ "request_id": "F96C25C6B13E49E59F0093BCD8D731AB", "error_type": "NotFound", "error_message": "Specified resource not found." }`))) err = c.WatchListAll(context.Background(), time.Second, countableList, &api.CommonSearchParams{Limit: 1}) }) It("return err", func() { Expect(err).To(HaveOccurred()) Expect(err.Error()).To(MatchRegexp("ErrorType: NotFound")) }) }) }) }) golang-iij-dpf-0.9.1/pkg/api/errors.go000066400000000000000000000041161437707610400175200ustar00rootroot00000000000000package api import "errors" func IsBadResponse(err error, f func(b *BadResponse) bool) bool { bad := &BadResponse{} if !errors.As(err, &bad) { return false } if f == nil { return true } return f(bad) } func IsStatusCode(err error, code int) bool { return IsBadResponse(err, func(bad *BadResponse) bool { return bad.IsStatusCode(code) }) } func IsErrType(err error, name string) bool { return IsBadResponse(err, func(bad *BadResponse) bool { return bad.IsErrType(name) }) } func IsErrMsg(err error, msg string) bool { return IsBadResponse(err, func(bad *BadResponse) bool { return bad.IsErrMsg(msg) }) } func IsErrorCode(err error, code string) (bool, string) { var ( res bool attribute string ) IsBadResponse(err, func(bad *BadResponse) bool { res, attribute = bad.IsErrorCode(code) return res }) return res, attribute } func IsErrorCodeAttribute(err error, code string, attribute string) bool { return IsBadResponse(err, func(bad *BadResponse) bool { return bad.IsErrorCodeAttribute(code, attribute) }) } func IsAuthError(err error) bool { return IsBadResponse(err, func(bad *BadResponse) bool { return bad.IsAuthError() }) } func IsRequestFormatError(err error) bool { return IsBadResponse(err, func(bad *BadResponse) bool { return bad.IsRequestFormatError() }) } func IsParameterError(err error) bool { return IsBadResponse(err, func(bad *BadResponse) bool { return bad.IsParameterError() }) } func IsNotFound(err error) bool { return IsBadResponse(err, func(bad *BadResponse) bool { return bad.IsNotFound() }) } func IsTooManyRequests(err error) bool { return IsBadResponse(err, func(bad *BadResponse) bool { return bad.IsTooManyRequests() }) } func IsSystemError(err error) bool { return IsBadResponse(err, func(bad *BadResponse) bool { return bad.IsSystemError() }) } func IsGatewayTimeout(err error) bool { return IsBadResponse(err, func(bad *BadResponse) bool { return bad.IsGatewayTimeout() }) } func IsInvalidSchema(err error) bool { return IsBadResponse(err, func(bad *BadResponse) bool { return bad.IsInvalidSchema() }) } golang-iij-dpf-0.9.1/pkg/api/errors_test.go000066400000000000000000000221561437707610400205630ustar00rootroot00000000000000package api_test import ( "errors" "fmt" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/mimuret/golang-iij-dpf/pkg/api" ) var _ = Describe("errors.go", func() { Context("IsStatusCode", func() { When("err is not BadResponse", func() { It("returns false", func() { Expect(api.IsStatusCode(errors.New(""), 400)).To(BeFalse()) }) }) When("err not BadResponse, not match value", func() { It("returns false", func() { Expect(api.IsStatusCode(&api.BadResponse{StatusCode: 200}, 400)).To(BeFalse()) }) }) When("err not BadResponse, match value", func() { It("returns true", func() { Expect(api.IsStatusCode(&api.BadResponse{StatusCode: 200}, 200)).To(BeTrue()) }) }) }) Context("IsErrType", func() { When("err is not BadResponse", func() { It("returns false", func() { Expect(api.IsErrType(errors.New(""), "hoge")).To(BeFalse()) }) }) When("err not BadResponse, not match value", func() { It("returns false", func() { Expect(api.IsErrType(&api.BadResponse{ErrorType: "book"}, "hoge")).To(BeFalse()) }) }) When("err not BadResponse, match value", func() { It("returns true", func() { Expect(api.IsErrType(&api.BadResponse{ErrorType: "hoge"}, "hoge")).To(BeTrue()) }) }) }) Context("IsErrMsg", func() { When("err is not BadResponse", func() { It("returns false", func() { Expect(api.IsErrMsg(errors.New(""), "hoge")).To(BeFalse()) }) }) When("err not BadResponse, not match value", func() { It("returns false", func() { Expect(api.IsErrMsg(&api.BadResponse{ErrorMessage: "book"}, "hoge")).To(BeFalse()) }) }) When("err not BadResponse, match value", func() { It("returns true", func() { Expect(api.IsErrMsg(&api.BadResponse{ErrorMessage: "hoge"}, "hoge")).To(BeTrue()) }) }) }) Context("IsErrorCode", func() { When("err is not BadResponse", func() { It("returns false", func() { Expect(api.IsErrorCode(errors.New(""), "hoge")).To(BeFalse()) }) }) When("err not BadResponse, not match value", func() { It("returns false", func() { ok, _ := api.IsErrorCode(&api.BadResponse{ErrorDetails: api.ErrorDetails{{Code: "code", Attribute: "ruby"}}}, "hoge") Expect(ok).To(BeFalse()) }) }) When("err not BadResponse, match value", func() { It("returns true", func() { ok, attr := api.IsErrorCode(&api.BadResponse{ErrorDetails: api.ErrorDetails{{Code: "code", Attribute: "ruby"}}}, "code") Expect(ok).To(BeTrue()) Expect(attr).To(Equal("ruby")) }) }) }) Context("IsErrorCodeAttribute", func() { When("err is not BadResponse", func() { It("returns false", func() { Expect(api.IsErrorCodeAttribute(errors.New(""), "code", "attribute")).To(BeFalse()) }) }) When("err not BadResponse, not match details", func() { It("returns false", func() { Expect(api.IsErrorCodeAttribute(&api.BadResponse{ErrorDetails: api.ErrorDetails{{Code: "code", Attribute: "ruby"}}}, "code", "attribute")).To(BeFalse()) }) }) When("err not BadResponse, include details", func() { It("returns true", func() { Expect(api.IsErrorCodeAttribute(&api.BadResponse{ErrorDetails: api.ErrorDetails{{Code: "book", Attribute: "one"}, {Code: "code", Attribute: "attribute"}}}, "code", "attribute")).To(BeTrue()) }) }) }) Context("Bad", func() { When("err is not BadResponse", func() { It("return false", func() { ok := api.IsBadResponse(fmt.Errorf("failed"), nil) Expect(ok).To(BeFalse()) }) }) When("err is BadResponse, func not set", func() { It("return true", func() { ok := api.IsBadResponse(&api.BadResponse{}, nil) Expect(ok).To(BeTrue()) }) }) When("err is BadResponse, func set", func() { It("return func result", func() { ok := api.IsBadResponse(&api.BadResponse{}, func(b *api.BadResponse) bool { return true }) Expect(ok).To(BeTrue()) ok = api.IsBadResponse(&api.BadResponse{}, func(b *api.BadResponse) bool { return false }) Expect(ok).To(BeFalse()) }) }) }) Context("IsAuthError", func() { When("status code is 400, ErrType is ParameterError, ErrorDtail include invalid=access_token", func() { It("return true", func() { Expect(api.IsAuthError(&api.BadResponse{ StatusCode: 400, ErrorType: "ParameterError", ErrorDetails: api.ErrorDetails{{Code: "invalid", Attribute: "access_token"}}, })).To(BeTrue()) }) }) When("other", func() { It("return false", func() { Expect(api.IsAuthError(&api.BadResponse{ StatusCode: 200, ErrorType: "ParameterError", ErrorDetails: api.ErrorDetails{{Code: "invalid", Attribute: "access_token"}}, })).To(BeFalse()) Expect(api.IsAuthError(&api.BadResponse{ StatusCode: 400, ErrorType: "NotFound", ErrorDetails: api.ErrorDetails{{Code: "invalid", Attribute: "access_token"}}, })).To(BeFalse()) Expect(api.IsAuthError(&api.BadResponse{ StatusCode: 400, ErrorType: "ParameterError", ErrorDetails: api.ErrorDetails{{Code: "invalid", Attribute: "schema"}}, })).To(BeFalse()) }) }) }) Context("IsRequestFormatError", func() { When("status code is 400, ErrType is ParameterError, ErrMsg `JSON parse error occurred`", func() { It("return true", func() { Expect(api.IsRequestFormatError(&api.BadResponse{ StatusCode: 400, ErrorType: "ParameterError", ErrorMessage: "JSON parse error occurred.", })).To(BeTrue()) }) }) When("other", func() { It("return false", func() { Expect(api.IsRequestFormatError(&api.BadResponse{ StatusCode: 200, ErrorType: "ParameterError", ErrorMessage: "JSON parse error occurred.", })).To(BeFalse()) Expect(api.IsRequestFormatError(&api.BadResponse{ StatusCode: 400, ErrorType: "NotFound", ErrorMessage: "JSON parse error occurred.", })).To(BeFalse()) Expect(api.IsRequestFormatError(&api.BadResponse{ StatusCode: 400, ErrorType: "ParameterError", })).To(BeFalse()) }) }) }) Context("IsParameterError", func() { When("status code is 400, ErrType ParameterError, NotAuthError, NotRequestFormatError", func() { It("return true", func() { Expect(api.IsParameterError(&api.BadResponse{ StatusCode: 400, ErrorType: "ParameterError", })).To(BeTrue()) }) }) When("other", func() { It("return false", func() { Expect(api.IsParameterError(&api.BadResponse{ StatusCode: 200, ErrorType: "ParameterError", })).To(BeFalse()) Expect(api.IsParameterError(&api.BadResponse{ StatusCode: 400, ErrorType: "NotFound", })).To(BeFalse()) Expect(api.IsParameterError(&api.BadResponse{ StatusCode: 400, ErrorType: "ParameterError", ErrorMessage: "JSON parse error occurred.", })).To(BeFalse()) Expect(api.IsParameterError(&api.BadResponse{ StatusCode: 400, ErrorType: "ParameterError", ErrorDetails: api.ErrorDetails{{Code: "invalid", Attribute: "access_token"}}, })).To(BeFalse()) }) }) }) Context("IsNotFound", func() { When("status code is 404", func() { It("return true", func() { Expect(api.IsNotFound(&api.BadResponse{ StatusCode: 404, })).To(BeTrue()) }) }) When("other", func() { It("return false", func() { Expect(api.IsNotFound(&api.BadResponse{ StatusCode: 200, })).To(BeFalse()) }) }) }) Context("IsTooManyRequests", func() { When("status code is 429", func() { It("return true", func() { Expect(api.IsTooManyRequests(&api.BadResponse{ StatusCode: 429, })).To(BeTrue()) }) }) When("other", func() { It("return false", func() { Expect(api.IsTooManyRequests(&api.BadResponse{ StatusCode: 200, })).To(BeFalse()) }) }) }) Context("IsSystemError", func() { When("status code is 500", func() { It("return true", func() { Expect(api.IsSystemError(&api.BadResponse{ StatusCode: 500, })).To(BeTrue()) }) }) When("other", func() { It("return false", func() { Expect(api.IsSystemError(&api.BadResponse{ StatusCode: 200, })).To(BeFalse()) }) }) }) Context("IsGatewayTimeout", func() { When("status code is 504", func() { It("return true", func() { Expect(api.IsGatewayTimeout(&api.BadResponse{ StatusCode: 504, })).To(BeTrue()) }) }) When("other", func() { It("return false", func() { Expect(api.IsGatewayTimeout(&api.BadResponse{ StatusCode: 200, })).To(BeFalse()) }) }) }) Context("IsInvalidSchema", func() { When("IsInvalidSchema and ErrorDtail include invalid=schema", func() { It("return true", func() { Expect(api.IsInvalidSchema(&api.BadResponse{ StatusCode: 400, ErrorType: "ParameterError", ErrorDetails: api.ErrorDetails{{Code: "invalid", Attribute: "schema"}}, })).To(BeTrue()) }) }) When("other", func() { It("return false", func() { Expect(api.IsInvalidSchema(&api.BadResponse{ StatusCode: 400, ErrorType: "ParameterError", })).To(BeFalse()) Expect(api.IsInvalidSchema(&api.BadResponse{ StatusCode: 404, ErrorType: "ParameterError", ErrorDetails: api.ErrorDetails{{Code: "invalid", Attribute: "schema"}}, })).To(BeFalse()) }) }) }) }) golang-iij-dpf-0.9.1/pkg/api/ginkgo_test.go000066400000000000000000000006141437707610400205200ustar00rootroot00000000000000package api_test import ( "testing" "github.com/jarcoal/httpmock" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) func TestGinkgo(t *testing.T) { RegisterFailHandler(Fail) RunSpecs(t, "api package test suite") } var _ = BeforeSuite(func() { httpmock.Activate() }) var _ = BeforeEach(func() { httpmock.Reset() }) var _ = AfterSuite(func() { httpmock.DeactivateAndReset() }) golang-iij-dpf-0.9.1/pkg/api/json.go000066400000000000000000000066041437707610400171610ustar00rootroot00000000000000package api import ( "reflect" jsoniter "github.com/json-iterator/go" "github.com/mimuret/golang-iij-dpf/pkg/meta" ) var JSON = NewJSONAPIAdapter() func UnmarshalRead(bs []byte, o interface{}) error { return JSON.UnmarshalRead(bs, o) } func MarshalCreate(body interface{}) ([]byte, error) { return JSON.MarshalCreate(body) } func MarshalUpdate(body interface{}) ([]byte, error) { return JSON.MarshalUpdate(body) } func MarshalApply(body interface{}) ([]byte, error) { return JSON.MarshalApply(body) } func MarshalOutput(spec Spec) ([]byte, error) { return JSON.MarshalOutput(spec) } func UnMarshalInput(bs []byte, obj Object) error { return JSON.UnMarshalInput(bs, obj) } type JSONAPIInterface interface { UnmarshalRead(bs []byte, o interface{}) error MarshalCreate(body interface{}) ([]byte, error) MarshalUpdate(body interface{}) ([]byte, error) MarshalApply(body interface{}) ([]byte, error) } type JSONFileInterface interface { MarshalOutput(spec Spec) ([]byte, error) UnMarshalInput(bs []byte, obj Object) error } type JSONAPIAdapter struct { Read jsoniter.API Update jsoniter.API Create jsoniter.API Apply jsoniter.API JSON jsoniter.API } func NewJSONAPIAdapter() *JSONAPIAdapter { return &JSONAPIAdapter{ Read: jsoniter.Config{ EscapeHTML: true, SortMapKeys: false, ValidateJsonRawMessage: true, OnlyTaggedField: true, TagKey: "read", }.Froze(), Create: jsoniter.Config{ EscapeHTML: true, SortMapKeys: true, ValidateJsonRawMessage: true, OnlyTaggedField: true, TagKey: "create", }.Froze(), Update: jsoniter.Config{ EscapeHTML: true, SortMapKeys: true, ValidateJsonRawMessage: true, OnlyTaggedField: true, TagKey: "update", }.Froze(), Apply: jsoniter.Config{ EscapeHTML: true, SortMapKeys: true, ValidateJsonRawMessage: true, OnlyTaggedField: true, TagKey: "apply", }.Froze(), JSON: jsoniter.Config{ EscapeHTML: true, SortMapKeys: true, ValidateJsonRawMessage: true, OnlyTaggedField: false, TagKey: "json", }.Froze(), } } // Unmarshal api response. func (j *JSONAPIAdapter) UnmarshalRead(bs []byte, o interface{}) error { return j.Read.Unmarshal(bs, o) } // Marshal for create request. func (j *JSONAPIAdapter) MarshalCreate(body interface{}) ([]byte, error) { return j.Create.Marshal(body) } // Marshal for update request. func (j *JSONAPIAdapter) MarshalUpdate(body interface{}) ([]byte, error) { return j.Update.Marshal(body) } // Marshal for apply request. func (j *JSONAPIAdapter) MarshalApply(body interface{}) ([]byte, error) { return j.Apply.Marshal(body) } // file format frame. type OutputFrame struct { meta.KindVersion `json:",inline"` Resource Object `json:"resource"` } // Marshal for file format. func (j *JSONAPIAdapter) MarshalOutput(spec Spec) ([]byte, error) { t := reflect.TypeOf(spec) t = t.Elem() out := &OutputFrame{ KindVersion: meta.KindVersion{ Kind: t.Name(), APIVersion: spec.GetGroup(), }, Resource: spec, } return j.JSON.Marshal(out) } // UnMarshal for file format. func (j *JSONAPIAdapter) UnMarshalInput(bs []byte, obj Object) error { out := &OutputFrame{ Resource: obj, } return j.JSON.Unmarshal(bs, out) } golang-iij-dpf-0.9.1/pkg/api/json_test.go000066400000000000000000000047541437707610400202240ustar00rootroot00000000000000package api_test import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/mimuret/golang-iij-dpf/pkg/api" ) var _ api.Spec = &JsonTest{} type JsonTest struct { Name string `json:"name" read:"read_name" create:"create_name" update:"update_name" apply:"apply_name"` } func (j *JsonTest) DeepCopyObject() api.Object { return &JsonTest{Name: j.Name} } func (JsonTest) GetName() string { return "jsontests" } func (JsonTest) GetGroup() string { return "tests" } func (JsonTest) GetPathMethod(a api.Action) (string, string) { return a.ToMethod(), "/tests/jsontests" } var _ = Describe("json", func() { var ( bs []byte err error value JsonTest ) BeforeEach(func() { value = JsonTest{Name: "hogehoge"} }) Describe("for API", func() { Context("UnmarshalRead(tag name is `read`)", func() { BeforeEach(func() { err = api.UnmarshalRead([]byte(`{"read_name": "book"}`), &value) }) It("can read `name`", func() { Expect(err).To(Succeed()) Expect(value.Name).To(Equal("book")) }) }) Context("MarshalCreate(tag name is `create`)", func() { BeforeEach(func() { bs, err = api.MarshalCreate(&value) }) It("can read `name`", func() { Expect(err).To(Succeed()) Expect(string(bs)).To(Equal(`{"create_name":"hogehoge"}`)) }) }) Context("MarshalUpdate(tag name is `update`)", func() { BeforeEach(func() { bs, err = api.MarshalUpdate(&value) }) It("can read `name`", func() { Expect(err).To(Succeed()) Expect(string(bs)).To(Equal(`{"update_name":"hogehoge"}`)) }) }) Context("MarshalApply (tag name is `apply`)", func() { BeforeEach(func() { bs, err = api.MarshalApply(&value) }) It("can read `name`", func() { Expect(err).To(Succeed()) Expect(string(bs)).To(Equal(`{"apply_name":"hogehoge"}`)) }) }) }) Describe("for file", func() { Context("MarshalOutput(tag name is `json`)", func() { BeforeEach(func() { bs, err = api.MarshalOutput(&value) }) It("can read `name`", func() { Expect(err).To(Succeed()) Expect(string(bs)).To(MatchJSON(`{"kind":"JsonTest","apiVersion":"tests","resource":{"name":"hogehoge"}}`)) }) }) Context("UnMarshalInput(tag name is `json`)", func() { BeforeEach(func() { err = api.UnMarshalInput([]byte(`{"kind": "JsonTest", "apiVersion": "tests", "resource": {"name": "book"}}`), &value) }) It("can read `name`", func() { Expect(err).To(Succeed()) Expect(value.Name).To(Equal("book")) }) }) }) }) golang-iij-dpf-0.9.1/pkg/api/logger.go000066400000000000000000000021611437707610400174610ustar00rootroot00000000000000package api import ( "io" "log" "os" ) // logger interface. type Logger interface { Tracef(format string, args ...interface{}) Debugf(format string, args ...interface{}) Infof(format string, args ...interface{}) Errorf(format string, args ...interface{}) } var _ Logger = &StdLogger{} // simple logger // change better logger as you like. type StdLogger struct { *log.Logger LogLevel int } func NewStdLogger(out io.Writer, prefix string, flag int, level int) *StdLogger { if out == nil { out = os.Stderr } if prefix == "" { prefix = "dpf-client" } return &StdLogger{ Logger: log.New(out, prefix, flag), LogLevel: level, } } func (s *StdLogger) Tracef(format string, args ...interface{}) { if s.LogLevel <= 0 { s.Printf(format, args...) } } func (s *StdLogger) Debugf(format string, args ...interface{}) { if s.LogLevel <= 1 { s.Printf(format, args...) } } func (s *StdLogger) Infof(format string, args ...interface{}) { if s.LogLevel <= 2 { s.Printf(format, args...) } } func (s *StdLogger) Errorf(format string, args ...interface{}) { if s.LogLevel <= 4 { s.Printf(format, args...) } } golang-iij-dpf-0.9.1/pkg/api/logger_test.go000066400000000000000000000074631437707610400205320ustar00rootroot00000000000000package api_test import ( "bytes" "log" "os" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/mimuret/golang-iij-dpf/pkg/api" ) var _ = Describe("logger", func() { Context("StdLogger", func() { var ( logger *api.StdLogger buf *bytes.Buffer ) BeforeEach(func() { buf = bytes.NewBuffer(nil) logger = api.NewStdLogger(buf, "test", 0, 0) }) Context("NewStdLogger", func() { When("default value", func() { BeforeEach(func() { logger = api.NewStdLogger(nil, "", 0, 0) }) It("io.Writer is os.Stderr", func() { Expect(logger.Logger).To(Equal(log.New(os.Stderr, "dpf-client", 0))) }) }) }) Context("Tracef", func() { When("level 0", func() { It("is out message", func() { logger.LogLevel = 0 logger.Tracef("trace message") Expect(string(buf.String())).To(MatchRegexp("trace message")) }) }) When("level >= 1", func() { It("is not out message", func() { logger.LogLevel = 1 logger.Tracef("trace message") Expect(string(buf.String())).NotTo(MatchRegexp("trace message")) }) It("is not out message", func() { logger.LogLevel = 2 logger.Tracef("trace message") Expect(string(buf.String())).NotTo(MatchRegexp("trace message")) }) }) }) Context("Debugf", func() { When("level <= 1", func() { It("is out message (level 0)", func() { logger.LogLevel = 0 logger.Debugf("debug message") Expect(string(buf.String())).To(MatchRegexp("debug message")) }) It("is out message (level 1)", func() { logger.LogLevel = 1 logger.Debugf("debug message") Expect(string(buf.String())).To(MatchRegexp("debug message")) }) }) When("level > 1", func() { It("is not out message", func() { logger.LogLevel = 2 logger.Debugf("debug message") Expect(string(buf.String())).NotTo(MatchRegexp("debug message")) }) It("is not out message", func() { logger.LogLevel = 3 logger.Debugf("debug message") Expect(string(buf.String())).NotTo(MatchRegexp("debug message")) }) }) }) Context("Infof", func() { When("level <= 2", func() { It("is out message (level 0)", func() { logger.LogLevel = 0 logger.Infof("info message") Expect(string(buf.String())).To(MatchRegexp("info message")) }) It("is out message (level 1)", func() { logger.LogLevel = 1 logger.Infof("info message") Expect(string(buf.String())).To(MatchRegexp("info message")) }) It("is out message (level 2)", func() { logger.LogLevel = 2 logger.Infof("info message") Expect(string(buf.String())).To(MatchRegexp("info message")) }) }) When("level > 2", func() { It("is not out message", func() { logger.LogLevel = 3 logger.Infof("info message") Expect(string(buf.String())).NotTo(MatchRegexp("info message")) }) }) }) Context("Errorf", func() { When("level <= 4", func() { It("is out message (level 0)", func() { logger.LogLevel = 0 logger.Errorf("error message") Expect(string(buf.String())).To(MatchRegexp("error message")) }) It("is out message (level 1)", func() { logger.LogLevel = 1 logger.Errorf("error message") Expect(string(buf.String())).To(MatchRegexp("error message")) }) It("is out message (level 2)", func() { logger.LogLevel = 2 logger.Errorf("error message") Expect(string(buf.String())).To(MatchRegexp("error message")) }) It("is out message (level 3)", func() { logger.LogLevel = 3 logger.Errorf("error message") Expect(string(buf.String())).To(MatchRegexp("error message")) }) It("is out message (level 4)", func() { logger.LogLevel = 4 logger.Errorf("error message") Expect(string(buf.String())).To(MatchRegexp("error message")) }) }) }) }) }) golang-iij-dpf-0.9.1/pkg/api/response.go000066400000000000000000000066561437707610400200550ustar00rootroot00000000000000package api import ( "encoding/json" "strings" ) type ResponseCommon struct { RequestID string `read:"request_id"` } type RawResponse struct { ResponseCommon `read:",inline"` Result json.RawMessage `read:"result,omitempty"` Results json.RawMessage `read:"results,omitempty"` } const ( ErrorTypeParamaterError string = "ParameterError" ErrorTypeNotFound string = "NotFound" ErrorTypeTooManyRequests string = "TooManyRequests" ErrorTypeSystemError string = "SystemError" ErrorTypeGatewayTimeout string = "GatewayTimeout" ) type BadResponse struct { ResponseCommon `read:",inline"` StatusCode int `read:"-"` ErrorType string `read:"error_type"` ErrorMessage string `read:"error_message"` ErrorDetails ErrorDetails `read:"error_details"` } func (r *BadResponse) Error() string { if r.ErrorType == ErrorTypeParamaterError { if r.IsAuthError() { return "Auth error" } } errorDetail := "" if len(r.ErrorDetails) > 0 { errorDetail = " Detail: " + r.ErrorDetails.Error() } return "ErrorType: " + r.ErrorType + " Message: " + r.ErrorMessage + errorDetail } func (r *BadResponse) IsStatusCode(code int) bool { return r.StatusCode == code } func (r *BadResponse) IsErrType(name string) bool { return r.ErrorType == name } func (r *BadResponse) IsErrMsg(msg string) bool { return r.ErrorMessage == msg } func (r *BadResponse) IsErrorCode(code string) (bool, string) { for _, errDetail := range r.ErrorDetails { if errDetail.Code == code { return true, errDetail.Attribute } } return false, "" } func (r *BadResponse) IsErrorCodeAttribute(code string, attribute string) bool { for _, errDetail := range r.ErrorDetails { if errDetail.Code == code && errDetail.Attribute == attribute { return true } } return false } func (r *BadResponse) IsAuthError() bool { if r.IsStatusCode(400) && r.IsErrType(ErrorTypeParamaterError) && r.IsErrorCodeAttribute("invalid", "access_token") { return true } return false } func (r *BadResponse) IsRequestFormatError() bool { if r.IsStatusCode(400) && r.IsErrType(ErrorTypeParamaterError) && r.IsErrMsg("JSON parse error occurred.") { return true } return false } func (r *BadResponse) IsParameterError() bool { if r.IsStatusCode(400) && r.IsErrType(ErrorTypeParamaterError) && !r.IsAuthError() && !r.IsRequestFormatError() { return true } return false } func (r *BadResponse) IsNotFound() bool { return r.IsStatusCode(404) } func (r *BadResponse) IsTooManyRequests() bool { return r.IsStatusCode(429) } func (r *BadResponse) IsSystemError() bool { return r.IsStatusCode(500) } func (r *BadResponse) IsGatewayTimeout() bool { return r.IsStatusCode(504) } func (r *BadResponse) IsInvalidSchema() bool { return r.IsParameterError() && r.IsErrorCodeAttribute("invalid", "schema") } type ErrorDetails []ErrorDetail func (e ErrorDetails) Error() string { res := []string{} for _, detail := range e { res = append(res, detail.Error()) } return strings.Join(res, ", ") } type ErrorDetail struct { Code string `read:"code"` Attribute string `read:"attribute"` } func (e ErrorDetail) Error() string { return e.Code + "=" + e.Attribute } type Count struct { Count int32 `read:"count" json:"-"` } func (c *Count) SetCount(v int32) { c.Count = v } func (c *Count) GetCount() int32 { return c.Count } type AsyncResponse struct { ResponseCommon `read:",inline"` JobsURL string `read:"jobs_url"` } golang-iij-dpf-0.9.1/pkg/api/response_test.go000066400000000000000000000062401437707610400211010ustar00rootroot00000000000000package api_test import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/mimuret/golang-iij-dpf/pkg/api" ) var _ = Describe("response", func() { Context("BadResponse", func() { var bad *api.BadResponse Context("Error", func() { When("Auth error", func() { BeforeEach(func() { bad = &api.BadResponse{ StatusCode: 400, ErrorType: api.ErrorTypeParamaterError, ErrorMessage: "There are invalid parameters.", ErrorDetails: api.ErrorDetails{ {Code: "invalid", Attribute: "access_token"}, }, } }) It("return `Auth error`", func() { Expect(bad.Error()).Should(MatchRegexp("Auth error")) }) }) When("request format error", func() { BeforeEach(func() { bad = &api.BadResponse{ StatusCode: 400, ErrorType: api.ErrorTypeParamaterError, ErrorMessage: "JSON parse error occurred.", } }) It("return `Invalid request format`", func() { Expect(bad.Error()).Should(MatchRegexp("ErrorType: ParameterError Message: JSON parse error occurred.")) }) }) When("invalid paramaters.", func() { BeforeEach(func() { bad = &api.BadResponse{ StatusCode: 400, ErrorType: api.ErrorTypeParamaterError, ErrorMessage: "There are invalid parameters.", ErrorDetails: api.ErrorDetails{ {Code: "invalid", Attribute: "name"}, {Code: "notfound", Attribute: "system_id"}, }, } }) It("return `ErrorType: ParameterError with Details`", func() { Expect(bad.Error()).Should(MatchRegexp("ErrorType: ParameterError Message: There are invalid parameters. Detail: invalid=name, notfound=system_id")) }) }) When("NotFound", func() { BeforeEach(func() { bad = &api.BadResponse{ StatusCode: 404, ErrorType: api.ErrorTypeNotFound, ErrorMessage: "Specified resource not found.", } }) It("return `ErrorType: NotFound`", func() { Expect(bad.Error()).Should(MatchRegexp("ErrorType: NotFound Message: Specified resource not found.")) }) }) When("TooManyRequests", func() { BeforeEach(func() { bad = &api.BadResponse{ StatusCode: 429, ErrorType: api.ErrorTypeTooManyRequests, ErrorMessage: "Too many requests.", } }) It("return `TooManyRequests`", func() { Expect(bad.Error()).Should(MatchRegexp("ErrorType: TooManyRequests Message: Too many requests.")) }) }) When("SystemError", func() { BeforeEach(func() { bad = &api.BadResponse{ StatusCode: 500, ErrorType: api.ErrorTypeSystemError, ErrorMessage: "System error occurred.", } }) It("return `SystemError`", func() { Expect(bad.Error()).Should(MatchRegexp("ErrorType: SystemError Message: System error occurred.")) }) }) When("GatewayTimeout", func() { BeforeEach(func() { bad = &api.BadResponse{ StatusCode: 504, ErrorType: api.ErrorTypeGatewayTimeout, ErrorMessage: "Gateway timeout.", } }) It("return `GatewayTimeout`", func() { Expect(bad.Error()).Should(MatchRegexp("ErrorType: GatewayTimeout Message: Gateway timeout.")) }) }) }) }) }) golang-iij-dpf-0.9.1/pkg/api/search_params.go000066400000000000000000000100671437707610400210160ustar00rootroot00000000000000package api import ( "net/url" "strconv" "time" "github.com/google/go-querystring/query" "github.com/mimuret/golang-iij-dpf/pkg/types" ) type SearchParams interface { GetValues() (url.Values, error) GetOffset() int32 SetOffset(int32) GetLimit() int32 SetLimit(int32) } type RowSearchParams struct { url.Values } func NewRowSearchParams(queryString string) (*RowSearchParams, error) { values, err := url.ParseQuery(queryString) if err != nil { return nil, err } return &RowSearchParams{values}, nil } func (r RowSearchParams) GetOffset() int32 { v := r.Values.Get("offset") if v == "" { return 0 } i, err := strconv.ParseInt(v, 10, 32) if err != nil { return 0 } return int32(i) } func (r RowSearchParams) SetOffset(offset int32) { str := strconv.FormatInt(int64(offset), 10) r.Set("offset", str) } func (r RowSearchParams) GetLimit() int32 { v := r.Values.Get("limit") if v == "" { return 100 } i, err := strconv.ParseInt(v, 10, 32) if err != nil { return 100 } return int32(i) } func (r RowSearchParams) SetLimit(limit int32) { str := strconv.FormatInt(int64(limit), 10) r.Set("limit", str) } func (r *RowSearchParams) GetValues() (url.Values, error) { return r.Values, nil } type CommonSearchParams struct { Type SearchType `url:"type,omitempty"` Offset int32 `url:"offset,omitempty"` Limit int32 `url:"limit,omitempty"` } func (s *CommonSearchParams) GetValues() (url.Values, error) { return query.Values(s) } func (k *CommonSearchParams) GetType() SearchType { return k.Type } func (k *CommonSearchParams) SetType(t SearchType) { k.Type = t } func (k *CommonSearchParams) GetOffset() int32 { return k.Offset } func (k *CommonSearchParams) SetOffset(offset int32) { k.Offset = offset } func (k *CommonSearchParams) GetLimit() int32 { if k.Limit == 0 { return 100 } return k.Limit } func (k *CommonSearchParams) SetLimit(limit int32) { k.Limit = limit } // +k8s:deepcopy-gen=false type SearchType string const ( SearchTypeAND SearchType = "AND" SearchTypeOR SearchType = "OR" ) func (s SearchType) Validate() bool { switch s { case SearchTypeAND, SearchTypeOR: default: return false } return true } // +k8s:deepcopy-gen=false type SearchOffset int32 func (s SearchOffset) Validate() bool { if s < 0 || s > 10000000 { return false } return true } // +k8s:deepcopy-gen=false type SearchLimit int32 func (s SearchLimit) Validate() bool { if s < 1 || s > 10000 { return false } return true } // +k8s:deepcopy-gen=false type SearchDate time.Time // +k8s:deepcopy-gen=false type SearchOrder string const ( SearchOrderASC SearchOrder = "ASC" SearchOrderDESC SearchOrder = "DESC" ) func (s SearchOrder) Validate() bool { switch s { case SearchOrderASC, SearchOrderDESC: default: return false } return true } // +k8s:deepcopy-gen=false type KeywordsString []string func (s KeywordsString) Validate() bool { for _, v := range s { if len(v) > 255 { return false } } return true } // +k8s:deepcopy-gen=false type KeywordsID []int64 func (s KeywordsID) Validate() bool { for _, v := range s { if v < 0 { return false } } return true } // +k8s:deepcopy-gen=false type KeywordsBoolean []types.Boolean func (c KeywordsBoolean) EncodeValues(key string, v *url.Values) error { for _, plan := range c { v.Add(key, strconv.Itoa(int(plan))) } return nil } // +k8s:deepcopy-gen=false type KeywordsState []types.State func (c KeywordsState) EncodeValues(key string, v *url.Values) error { for _, plan := range c { v.Add(key, strconv.Itoa(int(plan))) } return nil } // +k8s:deepcopy-gen=false type KeywordsFavorite []types.Favorite func (c KeywordsFavorite) EncodeValues(key string, v *url.Values) error { for _, plan := range c { v.Add(key, strconv.Itoa(int(plan))) } return nil } // +k8s:deepcopy-gen=false type KeywordsLabels []Label func (c KeywordsLabels) EncodeValues(key string, v *url.Values) error { for _, plan := range c { v.Add(key, plan.String()) } return nil } type Label struct { Key string Value string } func (l Label) String() string { return l.Key + "=" + l.Value } golang-iij-dpf-0.9.1/pkg/api/search_params_test.go000066400000000000000000000232531437707610400220560ustar00rootroot00000000000000package api_test import ( "net/url" "github.com/google/go-querystring/query" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/mimuret/golang-iij-dpf/pkg/api" "github.com/mimuret/golang-iij-dpf/pkg/types" ) var _ = Describe("search_params", func() { Context("RowSearchParams", func() { var ( err error params *api.RowSearchParams ) Context("NewRowSearchParams", func() { When("query string parse error", func() { BeforeEach(func() { params, err = api.NewRowSearchParams("%1") }) It("returns error", func() { Expect(err).To(HaveOccurred()) Expect(params).To(BeNil()) }) }) When("valid query string", func() { BeforeEach(func() { params, err = api.NewRowSearchParams("hogehoge=1&offset=0&limit=100") }) It("returns RowSearchParams", func() { Expect(err).To(Succeed()) Expect(params).NotTo(BeNil()) }) }) }) Context("GetOffset", func() { When("limit not set", func() { BeforeEach(func() { params, err = api.NewRowSearchParams("") Expect(err).To(Succeed()) }) It("returns 0", func() { Expect(params.GetOffset()).To(Equal(int32(0))) }) }) When("offset is set, not integer value", func() { BeforeEach(func() { params, err = api.NewRowSearchParams("offset=AAA") Expect(err).To(Succeed()) }) It("returns 0", func() { Expect(params.GetOffset()).To(Equal(int32(0))) }) }) When("limit is set, integer value", func() { BeforeEach(func() { params, err = api.NewRowSearchParams("offset=10") Expect(err).To(Succeed()) }) It("returns int value", func() { Expect(params.GetOffset()).To(Equal(int32(10))) }) }) }) Context("SetOffset", func() { When("offset set to 1", func() { BeforeEach(func() { params, err = api.NewRowSearchParams("") Expect(err).To(Succeed()) params.SetOffset(1) }) It("returns 1", func() { Expect(params.GetOffset()).To(Equal(int32(1))) }) }) }) Context("GetLimit", func() { When("limit not set", func() { BeforeEach(func() { params, err = api.NewRowSearchParams("") Expect(err).To(Succeed()) }) It("returns 100", func() { Expect(params.GetLimit()).To(Equal(int32(100))) }) }) When("limit is set, but not integer", func() { BeforeEach(func() { params, err = api.NewRowSearchParams("limit=ABC") Expect(err).To(Succeed()) }) It("returns 100", func() { Expect(params.GetLimit()).To(Equal(int32(100))) }) }) When("limit is set, integer value", func() { BeforeEach(func() { params, err = api.NewRowSearchParams("limit=10") Expect(err).To(Succeed()) }) It("returns int value", func() { Expect(params.GetLimit()).To(Equal(int32(10))) }) }) }) Context("SetLimit", func() { When("limit set to 50", func() { BeforeEach(func() { params, err = api.NewRowSearchParams("") Expect(err).To(Succeed()) params.SetLimit(50) }) It("returns 50", func() { Expect(params.GetLimit()).To(Equal(int32(50))) }) }) }) Context("GetValues", func() { BeforeEach(func() { params, err = api.NewRowSearchParams("limit=1&offset=3") Expect(err).To(Succeed()) }) It("returns url.Values", func() { v := url.Values{ "limit": []string{"1"}, "offset": []string{"3"}, } Expect(params.GetValues()).To(Equal(v)) }) }) }) Context("CommonSearchParams", func() { var params *api.CommonSearchParams BeforeEach(func() { params = &api.CommonSearchParams{ Type: api.SearchTypeAND, Offset: 1, Limit: 50, } }) Context("GetType", func() { It("returns type", func() { Expect(params.GetType()).To(Equal(api.SearchTypeAND)) }) }) Context("SetType", func() { It("can set type", func() { params.SetType(api.SearchTypeOR) Expect(params.GetType()).To(Equal(api.SearchTypeOR)) }) }) Context("GetOffset", func() { It("returns offset", func() { Expect(params.GetOffset()).To(Equal(int32(1))) }) }) Context("SetOffset", func() { It("can set offset", func() { params.SetOffset(2) Expect(params.GetOffset()).To(Equal(int32(2))) }) }) Context("GetLimit", func() { When("if limit not set", func() { It("returns 100", func() { params.SetLimit(0) Expect(params.GetLimit()).To(Equal(int32(100))) }) }) It("returns limit", func() { Expect(params.GetLimit()).To(Equal(int32(50))) }) }) Context("SetLimit", func() { It("can set offset", func() { params.SetLimit(100) Expect(params.GetLimit()).To(Equal(int32(100))) }) }) }) Context("SearchType.Validate", func() { When("SearchType is not `AND` or `OR`", func() { It("returns false", func() { Expect(api.SearchType("and").Validate()).To(BeFalse()) Expect(api.SearchType("or").Validate()).To(BeFalse()) Expect(api.SearchType("NOT").Validate()).To(BeFalse()) }) }) When("SearchType is `AND` or `OR`", func() { It("returns true", func() { Expect(api.SearchType("AND").Validate()).To(BeTrue()) Expect(api.SearchType("OR").Validate()).To(BeTrue()) }) }) }) Context("SearchOrder.Validate", func() { When("SearchOrder is not `ASC` or `DESC`", func() { It("returns false", func() { Expect(api.SearchOrder("asc").Validate()).To(BeFalse()) Expect(api.SearchOrder("desc").Validate()).To(BeFalse()) Expect(api.SearchOrder("hoge").Validate()).To(BeFalse()) }) }) When("SearchOrder is `ASC` or `DESC`", func() { It("returns true", func() { Expect(api.SearchOrder("ASC").Validate()).To(BeTrue()) Expect(api.SearchOrder("DESC").Validate()).To(BeTrue()) }) }) }) Context("SearchOffset.Validate", func() { When("SearchOffset is not in range 0 to 10000000", func() { It("returns false", func() { Expect(api.SearchOffset(-2).Validate()).To(BeFalse()) Expect(api.SearchOffset(-1).Validate()).To(BeFalse()) Expect(api.SearchOffset(10000001).Validate()).To(BeFalse()) Expect(api.SearchOffset(10000002).Validate()).To(BeFalse()) }) }) When("SearchOffset is in range 0 to 10000000", func() { It("returns true", func() { Expect(api.SearchOffset(0).Validate()).To(BeTrue()) Expect(api.SearchOffset(1).Validate()).To(BeTrue()) Expect(api.SearchOffset(10000000).Validate()).To(BeTrue()) Expect(api.SearchOffset(9999999).Validate()).To(BeTrue()) }) }) }) Context("SearchLimit.Validate", func() { When("SearchLimit is not in range 1 to 10000", func() { It("returns false", func() { Expect(api.SearchLimit(-1).Validate()).To(BeFalse()) Expect(api.SearchLimit(0).Validate()).To(BeFalse()) Expect(api.SearchLimit(10001).Validate()).To(BeFalse()) Expect(api.SearchLimit(10002).Validate()).To(BeFalse()) }) }) When("SearchLimit is in range 1 to 10000", func() { It("returns true", func() { Expect(api.SearchLimit(1).Validate()).To(BeTrue()) Expect(api.SearchLimit(2).Validate()).To(BeTrue()) Expect(api.SearchLimit(10000).Validate()).To(BeTrue()) Expect(api.SearchLimit(9999).Validate()).To(BeTrue()) }) }) }) Context("KeywordsString.Validate", func() { When("KeywordsString length grather than 255", func() { It("returns false", func() { s := "" for i := 0; i < 256; i++ { s += "A" } Expect(api.KeywordsString{s}.Validate()).To(BeFalse()) Expect(api.KeywordsString{"", s}.Validate()).To(BeFalse()) Expect(api.KeywordsString{"", "b", s}.Validate()).To(BeFalse()) }) }) When("SearchLimit is not include length grather than 255", func() { It("returns true", func() { s := "" for i := 0; i < 255; i++ { s += "A" } Expect(api.KeywordsString{"", "b", s}.Validate()).To(BeTrue()) Expect(api.KeywordsString{""}.Validate()).To(BeTrue()) }) }) }) Context("KeywordsID.Validate", func() { When("KeywordsID is include minus value", func() { It("returns false", func() { Expect(api.KeywordsID{-1}.Validate()).To(BeFalse()) Expect(api.KeywordsID{1, -1}.Validate()).To(BeFalse()) }) }) When("KeywordsID is not include minus value", func() { It("returns false", func() { Expect(api.KeywordsID{0}.Validate()).To(BeTrue()) Expect(api.KeywordsID{0, 1}.Validate()).To(BeTrue()) Expect(api.KeywordsID{0, 1, 2}.Validate()).To(BeTrue()) }) }) }) Context("KeywordsBoolean.EncodeValues", func() { var ( value url.Values err error keywords struct { Tests api.KeywordsBoolean `url:"tests"` } ) BeforeEach(func() { keywords.Tests = api.KeywordsBoolean{ types.Enabled, types.Disabled, } value, err = query.Values(keywords) }) It("can encode url.Vale", func() { Expect(err).To(Succeed()) v := url.Values{ "tests": []string{"1", "0"}, } Expect(value).To(Equal(v)) }) }) Context("KeywordsState.EncodeValues", func() { var ( value url.Values err error keywords struct { Tests api.KeywordsState `url:"tests"` } ) BeforeEach(func() { keywords.Tests = api.KeywordsState{ types.StateBeforeStart, types.StateRunning, } value, err = query.Values(keywords) }) It("can encode url.Vale", func() { Expect(err).To(Succeed()) v := url.Values{ "tests": []string{"1", "2"}, } Expect(value).To(Equal(v)) }) }) Context("KeywordsState.KeywordsFavorite", func() { var ( value url.Values err error keywords struct { Tests api.KeywordsFavorite `url:"tests"` } ) BeforeEach(func() { keywords.Tests = api.KeywordsFavorite{ types.FavoriteHighPriority, types.FavoriteLowPriority, } value, err = query.Values(keywords) }) It("can encode url.Vale", func() { Expect(err).To(Succeed()) v := url.Values{ "tests": []string{"1", "2"}, } Expect(value).To(Equal(v)) }) }) }) golang-iij-dpf-0.9.1/pkg/api/spec.go000066400000000000000000000021511437707610400171330ustar00rootroot00000000000000package api import ( "reflect" ) type Object interface { DeepCopyObject() Object } type Spec interface { Object GetName() string GetGroup() string GetPathMethod(Action) (string, string) } type ListSpec interface { Spec Initializer GetItems() interface{} Len() int Index(int) interface{} } type CountableListSpec interface { ListSpec SetCount(int32) GetCount() int32 GetMaxLimit() int32 AddItem(interface{}) bool ClearItems() } type Initializer interface { Init() } func DeepCopySpec(s Spec) Spec { if s == nil || reflect.ValueOf(s).IsNil() { return nil } ret, ok := s.DeepCopyObject().(Spec) if !ok { panic("s is not Spec") } return ret } func DeepCopyListSpec(s ListSpec) ListSpec { if s == nil || reflect.ValueOf(s).IsNil() { return nil } ret, ok := s.DeepCopyObject().(ListSpec) if !ok { panic("s is not ListSpec") } return ret } func DeepCopyCountableListSpec(s CountableListSpec) CountableListSpec { if s == nil || reflect.ValueOf(s).IsNil() { return nil } ret, ok := s.DeepCopyObject().(CountableListSpec) if !ok { panic("s is not CountableListSpec") } return ret } golang-iij-dpf-0.9.1/pkg/api/spec_test.go000066400000000000000000000055531437707610400202030ustar00rootroot00000000000000package api_test import ( "github.com/mimuret/golang-iij-dpf/pkg/api" "github.com/mimuret/golang-iij-dpf/pkg/testtool" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) type countableListErr testtool.TestSpecCountableList func (c *countableListErr) DeepCopyObject() api.Object { return &dummyObject{} } type dummyObject struct{} func (c *dummyObject) DeepCopyObject() api.Object { return &dummyObject{} } var _ = Describe("spec.go", func() { Describe("DeepCopySpec", func() { var ( spec *testtool.TestSpec ret api.Spec ) When("param is nil value", func() { BeforeEach(func() { ret = api.DeepCopySpec(nil) }) It("retruns nil", func() { Expect(ret).To(BeNil()) }) }) When("param is nil", func() { BeforeEach(func() { ret = api.DeepCopySpec(spec) }) It("retruns nil", func() { Expect(ret).To(BeNil()) }) }) When("DeepCopyObject returns invalid", func() { It("raise panic", func() { Expect(func() { _ = api.DeepCopySpec(&countableListErr{}) }).To(Panic()) }) }) When("param is not nil", func() { BeforeEach(func() { ret = api.DeepCopySpec(&testtool.TestSpec{}) }) It("returns ret", func() { Expect(ret).NotTo(BeNil()) }) }) }) Describe("DeepCopyListSpec", func() { var ( spec *testtool.TestSpecList ret api.Spec ) When("param is nil svalue", func() { BeforeEach(func() { ret = api.DeepCopyListSpec(nil) }) It("retruns nil", func() { Expect(ret).To(BeNil()) }) }) When("param is nil", func() { BeforeEach(func() { ret = api.DeepCopyListSpec(spec) }) It("retruns nil", func() { Expect(ret).To(BeNil()) }) }) When("DeepCopyObject returns invalid", func() { It("raise panic", func() { Expect(func() { _ = api.DeepCopyListSpec(&countableListErr{}) }).To(Panic()) }) }) When("param is not nil", func() { BeforeEach(func() { ret = api.DeepCopyListSpec(&testtool.TestSpecList{}) }) It("returns ret", func() { Expect(ret).NotTo(BeNil()) }) }) }) Describe("DeepCopyCountableListSpec", func() { var ( spec *testtool.TestSpecCountableList ret api.Spec ) When("param is nil value", func() { BeforeEach(func() { ret = api.DeepCopyCountableListSpec(nil) }) It("retruns nil", func() { Expect(ret).To(BeNil()) }) }) When("param is nil", func() { BeforeEach(func() { ret = api.DeepCopyCountableListSpec(spec) }) It("retruns nil", func() { Expect(ret).To(BeNil()) }) }) When("DeepCopyObject returns invalid", func() { It("raise panic", func() { Expect(func() { _ = api.DeepCopyCountableListSpec(&countableListErr{}) }).To(Panic()) }) }) When("param is not nil", func() { BeforeEach(func() { ret = api.DeepCopyCountableListSpec(&testtool.TestSpecCountableList{}) }) It("returns ret", func() { Expect(ret).NotTo(BeNil()) }) }) }) }) golang-iij-dpf-0.9.1/pkg/apis/000077500000000000000000000000001437707610400160365ustar00rootroot00000000000000golang-iij-dpf-0.9.1/pkg/apis/.DS_Store000066400000000000000000000140041437707610400175200ustar00rootroot00000000000000Bud1 on_concommon_configsbwspblobÉbplist00×  ]ShowStatusBar[ShowPathbar[ShowToolbar[ShowTabView_ContainerShowSidebar\WindowBounds[ShowSidebar  _{{436, 494}, {920, 436}} %1=I`myz{|}~™šcommon_configsvSrnlong  @€ @€ @€ @ E DSDB `€ @€ @€ @golang-iij-dpf-0.9.1/pkg/apis/common.go000066400000000000000000000020461437707610400176570ustar00rootroot00000000000000package apis import ( "fmt" "github.com/mimuret/golang-iij-dpf/pkg/api" "github.com/mimuret/golang-iij-dpf/pkg/utils" ) type Params interface { SetPathParams(...interface{}) error } // for ctl. func SetPathParams(args []interface{}, ids ...interface{}) error { if len(args) == 0 { return nil } if len(args) != len(ids) { return fmt.Errorf("SetPathParams: args need %d items, but args len is %d", len(ids), len(args)) } for i := range ids { switch v := ids[i].(type) { case *int64: val, err := utils.ToInt64(args[i]) if err != nil { return fmt.Errorf("failed to cast to int64 `%s`: %w", args[i], err) } *v = val case *string: val, err := utils.ToString(args[i]) if err != nil { return fmt.Errorf("failed to cast to string `%s`: %w", args[i], err) } *v = val default: panic(fmt.Sprintf("ids[%d] is not int64 or string", i)) } } return nil } type Spec interface { api.Spec Params } type ListSpec interface { api.ListSpec Spec } type CountableListSpec interface { api.CountableListSpec Spec } golang-iij-dpf-0.9.1/pkg/apis/common_test.go000066400000000000000000000036561437707610400207260ustar00rootroot00000000000000package apis_test import ( "testing" "github.com/mimuret/golang-iij-dpf/pkg/apis" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) func TestAPIS(t *testing.T) { RegisterFailHandler(Fail) RunSpecs(t, "apis Suite") } var _ = Describe("apis", func() { Context("SetPathParams", func() { var ( err error strValue string int64Value int64 ) BeforeEach(func() { int64Value = 0 strValue = "" }) When("args is nothing", func() { BeforeEach(func() { err = apis.SetPathParams(nil, &strValue, &int64Value) }) It("nothing to do", func() { Expect(err).To(Succeed()) }) }) When("args len not equals to ids", func() { BeforeEach(func() { err = apis.SetPathParams([]interface{}{"string"}, &strValue, &int64Value) }) It("return err", func() { Expect(err).To(HaveOccurred()) Expect(err.Error()).To(MatchRegexp("SetPathParams: args need 2 items")) }) }) When("failed to cast int64", func() { BeforeEach(func() { err = apis.SetPathParams([]interface{}{"string"}, &int64Value) }) It("return err", func() { Expect(err).To(HaveOccurred()) Expect(err.Error()).To(MatchRegexp("failed to cast to int64")) }) }) When("failed to cast string", func() { BeforeEach(func() { err = apis.SetPathParams([]interface{}{10}, &strValue) }) It("return err", func() { Expect(err).To(HaveOccurred()) Expect(err.Error()).To(MatchRegexp("failed to cast to string")) }) }) When("ids is not *int64 or *string", func() { var v int32 It("raise panic", func() { Expect(func() { _ = apis.SetPathParams([]interface{}{10}, &v) }).To(Panic()) }) }) When("success", func() { BeforeEach(func() { err = apis.SetPathParams([]interface{}{10, "hoge"}, &int64Value, &strValue) }) It("return err", func() { Expect(err).To(Succeed()) Expect(int64Value).To(Equal(int64(10))) Expect(strValue).To(Equal("hoge")) }) }) }) }) golang-iij-dpf-0.9.1/pkg/apis/dpf/000077500000000000000000000000001437707610400166075ustar00rootroot00000000000000golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/000077500000000000000000000000001437707610400171355ustar00rootroot00000000000000golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/common_configs/000077500000000000000000000000001437707610400221355ustar00rootroot00000000000000golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/common_configs/ZZ_deepcopy_generated.go000066400000000000000000000227211437707610400267410ustar00rootroot00000000000000//go:build !ignore_autogenerated // +build !ignore_autogenerated /* MIT License Copyright (c) 2021 Manabu Sonoda 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. */ // Code generated by deepcopy-gen. DO NOT EDIT. package common_configs import ( net "net" api "github.com/mimuret/golang-iij-dpf/pkg/api" ) // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *AttributeMeta) DeepCopyInto(out *AttributeMeta) { *out = *in return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AttributeMeta. func (in *AttributeMeta) DeepCopy() *AttributeMeta { if in == nil { return nil } out := new(AttributeMeta) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *CcNoticeAccount) DeepCopyInto(out *CcNoticeAccount) { *out = *in out.AttributeMeta = in.AttributeMeta in.Props.DeepCopyInto(&out.Props) return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CcNoticeAccount. func (in *CcNoticeAccount) DeepCopy() *CcNoticeAccount { if in == nil { return nil } out := new(CcNoticeAccount) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new api.Object. func (in *CcNoticeAccount) DeepCopyObject() api.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *CcNoticeAccountList) DeepCopyInto(out *CcNoticeAccountList) { *out = *in out.AttributeMeta = in.AttributeMeta if in.Items != nil { in, out := &in.Items, &out.Items *out = make([]CcNoticeAccount, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CcNoticeAccountList. func (in *CcNoticeAccountList) DeepCopy() *CcNoticeAccountList { if in == nil { return nil } out := new(CcNoticeAccountList) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new api.Object. func (in *CcNoticeAccountList) DeepCopyObject() api.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *CcNoticePhone) DeepCopyInto(out *CcNoticePhone) { *out = *in return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CcNoticePhone. func (in *CcNoticePhone) DeepCopy() *CcNoticePhone { if in == nil { return nil } out := new(CcNoticePhone) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *CcNoticeProps) DeepCopyInto(out *CcNoticeProps) { *out = *in if in.Phone != nil { in, out := &in.Phone, &out.Phone *out = new(CcNoticePhone) **out = **in } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CcNoticeProps. func (in *CcNoticeProps) DeepCopy() *CcNoticeProps { if in == nil { return nil } out := new(CcNoticeProps) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *CcPrimary) DeepCopyInto(out *CcPrimary) { *out = *in out.AttributeMeta = in.AttributeMeta if in.Address != nil { in, out := &in.Address, &out.Address *out = make(net.IP, len(*in)) copy(*out, *in) } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CcPrimary. func (in *CcPrimary) DeepCopy() *CcPrimary { if in == nil { return nil } out := new(CcPrimary) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new api.Object. func (in *CcPrimary) DeepCopyObject() api.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *CcPrimaryList) DeepCopyInto(out *CcPrimaryList) { *out = *in out.AttributeMeta = in.AttributeMeta if in.Items != nil { in, out := &in.Items, &out.Items *out = make([]CcPrimary, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CcPrimaryList. func (in *CcPrimaryList) DeepCopy() *CcPrimaryList { if in == nil { return nil } out := new(CcPrimaryList) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new api.Object. func (in *CcPrimaryList) DeepCopyObject() api.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *CcSecNotifiedServer) DeepCopyInto(out *CcSecNotifiedServer) { *out = *in out.AttributeMeta = in.AttributeMeta if in.Address != nil { in, out := &in.Address, &out.Address *out = make(net.IP, len(*in)) copy(*out, *in) } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CcSecNotifiedServer. func (in *CcSecNotifiedServer) DeepCopy() *CcSecNotifiedServer { if in == nil { return nil } out := new(CcSecNotifiedServer) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new api.Object. func (in *CcSecNotifiedServer) DeepCopyObject() api.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *CcSecNotifiedServerList) DeepCopyInto(out *CcSecNotifiedServerList) { *out = *in out.AttributeMeta = in.AttributeMeta if in.Items != nil { in, out := &in.Items, &out.Items *out = make([]CcSecNotifiedServer, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CcSecNotifiedServerList. func (in *CcSecNotifiedServerList) DeepCopy() *CcSecNotifiedServerList { if in == nil { return nil } out := new(CcSecNotifiedServerList) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new api.Object. func (in *CcSecNotifiedServerList) DeepCopyObject() api.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *CcSecTransferAcl) DeepCopyInto(out *CcSecTransferAcl) { *out = *in out.AttributeMeta = in.AttributeMeta if in.Network != nil { in, out := &in.Network, &out.Network *out = (*in).DeepCopy() } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CcSecTransferAcl. func (in *CcSecTransferAcl) DeepCopy() *CcSecTransferAcl { if in == nil { return nil } out := new(CcSecTransferAcl) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new api.Object. func (in *CcSecTransferAcl) DeepCopyObject() api.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *CcSecTransferAclList) DeepCopyInto(out *CcSecTransferAclList) { *out = *in out.AttributeMeta = in.AttributeMeta if in.Items != nil { in, out := &in.Items, &out.Items *out = make([]CcSecTransferAcl, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CcSecTransferAclList. func (in *CcSecTransferAclList) DeepCopy() *CcSecTransferAclList { if in == nil { return nil } out := new(CcSecTransferAclList) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new api.Object. func (in *CcSecTransferAclList) DeepCopyObject() api.Object { if c := in.DeepCopy(); c != nil { return c } return nil } golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/common_configs/cc_notice_accounts.go000066400000000000000000000053121437707610400263120ustar00rootroot00000000000000package common_configs import ( "fmt" "github.com/mimuret/golang-iij-dpf/pkg/api" "github.com/mimuret/golang-iij-dpf/pkg/apis" ) type CcNoticeLang string const ( CcNoticeLangJA CcNoticeLang = "ja" CcNoticeLangENUS CcNoticeLang = "en_US" ) type CcNoticePhone struct { CountryCode string `read:"country_code" create:"country_code" update:"country_code"` Number string `read:"number" create:"number" update:"number"` } type CcNoticeProps struct { Mail string `read:"mail" create:"mail,omitempty" update:"mail,omitempty"` Phone *CcNoticePhone `read:"phone" create:"phone,omitempty" update:"phone,omitempty"` } // for IDE. var _ Spec = &CcNoticeAccount{} // +k8s:deepcopy-gen:interfaces=github.com/mimuret/golang-iij-dpf/pkg/api.Object type CcNoticeAccount struct { AttributeMeta ResourceName string `read:"resource_name,omitempty" create:"resource_name,omitempty" id:"2,required"` Name string `read:"name" create:"name" update:"name"` Lang CcNoticeLang `read:"lang" create:"lang" update:"lang"` Props CcNoticeProps `read:"props" create:"props" update:"props"` } func (c *CcNoticeAccount) SetPathParams(args ...interface{}) error { return apis.SetPathParams(args, &c.CommonConfigID, &c.ResourceName) } func (c *CcNoticeAccount) GetName() string { return "cc_notice_accounts" } func (c *CcNoticeAccount) GetPathMethod(action api.Action) (string, string) { switch action { case api.ActionCreate: return action.ToMethod(), fmt.Sprintf("/common_configs/%d/cc_notice_accounts", c.GetCommonConfigID()) case api.ActionRead, api.ActionUpdate, api.ActionDelete: return action.ToMethod(), fmt.Sprintf("/common_configs/%d/cc_notice_accounts/%s", c.GetCommonConfigID(), c.ResourceName) } return "", "" } // for IDE. var _ ListSpec = &CcNoticeAccountList{} // +k8s:deepcopy-gen:interfaces=github.com/mimuret/golang-iij-dpf/pkg/api.Object type CcNoticeAccountList struct { AttributeMeta Items []CcNoticeAccount `read:"items"` } func (c *CcNoticeAccountList) SetPathParams(args ...interface{}) error { return apis.SetPathParams(args, &c.CommonConfigID) } func (c *CcNoticeAccountList) GetPathMethod(action api.Action) (string, string) { return GetPathMethodForListSpec(action, c) } func (c *CcNoticeAccountList) GetName() string { return "cc_notice_accounts" } func (c *CcNoticeAccountList) GetItems() interface{} { return &c.Items } func (c *CcNoticeAccountList) Len() int { return len(c.Items) } func (c *CcNoticeAccountList) Index(i int) interface{} { return c.Items[i] } func (c *CcNoticeAccountList) Init() { for i := range c.Items { c.Items[i].AttributeMeta = c.AttributeMeta } } func init() { register(&CcNoticeAccount{}, &CcNoticeAccountList{}) } golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/common_configs/cc_notice_accounts_test.go000066400000000000000000000321241437707610400273520ustar00rootroot00000000000000package common_configs_test import ( "context" "net/http" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/jarcoal/httpmock" "github.com/mimuret/golang-iij-dpf/pkg/apis/dpf/v1/common_configs" "github.com/mimuret/golang-iij-dpf/pkg/testtool" ) var _ = Describe("cc_notice_accounts", func() { var ( c common_configs.CcNoticeAccount cl *testtool.TestClient err error reqId string s1, s2 common_configs.CcNoticeAccount slist common_configs.CcNoticeAccountList ) BeforeEach(func() { cl = testtool.NewTestClient("", "http://localhost", nil) s1 = common_configs.CcNoticeAccount{ AttributeMeta: common_configs.AttributeMeta{ CommonConfigID: 1, }, ResourceName: "user1", Name: "user1", Lang: common_configs.CcNoticeLangJA, Props: common_configs.CcNoticeProps{ Mail: "mail@example.jp", Phone: &common_configs.CcNoticePhone{ CountryCode: "81", Number: "300000000", }, }, } s2 = common_configs.CcNoticeAccount{ AttributeMeta: common_configs.AttributeMeta{ CommonConfigID: 1, }, ResourceName: "user2", Name: "user2", Lang: common_configs.CcNoticeLangENUS, Props: common_configs.CcNoticeProps{ Mail: "mail2@example.com", }, } slist = common_configs.CcNoticeAccountList{ AttributeMeta: common_configs.AttributeMeta{ CommonConfigID: 1, }, Items: []common_configs.CcNoticeAccount{s1, s2}, } }) Describe("CcNoticeAccount", func() { Context("Read", func() { BeforeEach(func() { httpmock.RegisterResponder(http.MethodGet, "http://localhost/common_configs/1/cc_notice_accounts/user1", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "73A87F978AFD42D8B0AC810218AEC7CC", "result": { "resource_name": "user1", "name": "user1", "lang": "ja", "props": { "mail": "mail@example.jp", "phone": { "country_code": "81", "number": "300000000" } } } }`))) httpmock.RegisterResponder(http.MethodGet, "http://localhost/common_configs/1/cc_notice_accounts/user2", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "EBCA51F1CCD8457FB242766B59B5786E", "result": { "resource_name": "user2", "name": "user2", "lang": "en_US", "props": { "mail": "mail2@example.com" } } }`))) }) AfterEach(func() { httpmock.Reset() }) When("returns phone and mail", func() { BeforeEach(func() { c = common_configs.CcNoticeAccount{ AttributeMeta: common_configs.AttributeMeta{ CommonConfigID: 1, }, ResourceName: "user1", } reqId, err = cl.Read(context.Background(), &c) }) It("returns normal", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal("73A87F978AFD42D8B0AC810218AEC7CC")) Expect(c).To(Equal(s1)) }) }) When("returns mail only", func() { BeforeEach(func() { c = common_configs.CcNoticeAccount{ AttributeMeta: common_configs.AttributeMeta{ CommonConfigID: 1, }, ResourceName: "user2", } reqId, err = cl.Read(context.Background(), &c) }) It("returns normal", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal("EBCA51F1CCD8457FB242766B59B5786E")) Expect(c).To(Equal(s2)) }) }) }) Context("Create", func() { var ( id1, bs1 = testtool.CreateAsyncResponse() id2, bs2 = testtool.CreateAsyncResponse() id3, bs3 = testtool.CreateAsyncResponse() ) BeforeEach(func() { httpmock.RegisterResponder(http.MethodPost, "http://localhost/common_configs/10/cc_notice_accounts", httpmock.NewBytesResponder(202, bs1)) httpmock.RegisterResponder(http.MethodPost, "http://localhost/common_configs/20/cc_notice_accounts", httpmock.NewBytesResponder(202, bs2)) httpmock.RegisterResponder(http.MethodPost, "http://localhost/common_configs/30/cc_notice_accounts", httpmock.NewBytesResponder(202, bs3)) }) AfterEach(func() { httpmock.Reset() }) When("phone and mail", func() { BeforeEach(func() { s := common_configs.CcNoticeAccount{ AttributeMeta: common_configs.AttributeMeta{ CommonConfigID: 10, }, ResourceName: "user10", Name: "user10", Lang: common_configs.CcNoticeLangJA, Props: common_configs.CcNoticeProps{ Mail: "mail10@example.jp", }, } reqId, err = cl.Create(context.Background(), &s, nil) }) It("returns job_id", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal(id1)) }) It("post json", func() { Expect(cl.RequestBody["/common_configs/10/cc_notice_accounts"]).To(MatchJSON(`{ "resource_name": "user10", "name": "user10", "lang": "ja", "props": { "mail": "mail10@example.jp" } }`)) }) }) When("phone only", func() { BeforeEach(func() { s := common_configs.CcNoticeAccount{ AttributeMeta: common_configs.AttributeMeta{ CommonConfigID: 20, }, Name: "user20", Lang: common_configs.CcNoticeLangJA, Props: common_configs.CcNoticeProps{ Phone: &common_configs.CcNoticePhone{ CountryCode: "81", Number: "300000000", }, }, } reqId, err = cl.Create(context.Background(), &s, nil) }) It("returns job_id", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal(id2)) }) It("post json", func() { Expect(cl.RequestBody["/common_configs/20/cc_notice_accounts"]).To(MatchJSON(`{ "name": "user20", "lang": "ja", "props": { "phone": { "country_code": "81", "number": "300000000" } } }`)) }) }) When("phone and mail", func() { BeforeEach(func() { s := common_configs.CcNoticeAccount{ AttributeMeta: common_configs.AttributeMeta{ CommonConfigID: 30, }, Name: "user30", Lang: common_configs.CcNoticeLangJA, Props: common_configs.CcNoticeProps{ Mail: "mail5@example.jp", Phone: &common_configs.CcNoticePhone{ CountryCode: "81", Number: "300000000", }, }, } reqId, err = cl.Create(context.Background(), &s, nil) }) It("returns job_id", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal(id3)) }) It("post json", func() { Expect(cl.RequestBody["/common_configs/30/cc_notice_accounts"]).To(MatchJSON(`{ "name": "user30", "lang": "ja", "props": { "mail": "mail5@example.jp", "phone": { "country_code": "81", "number": "300000000" } } }`)) }) }) }) Context("Update", func() { var ( id1, bs1 = testtool.CreateAsyncResponse() id2, bs2 = testtool.CreateAsyncResponse() ) BeforeEach(func() { httpmock.RegisterResponder(http.MethodPatch, "http://localhost/common_configs/1/cc_notice_accounts/user1", httpmock.NewBytesResponder(202, bs1)) httpmock.RegisterResponder(http.MethodPatch, "http://localhost/common_configs/1/cc_notice_accounts/user2", httpmock.NewBytesResponder(202, bs2)) }) AfterEach(func() { httpmock.Reset() }) When("update mail and phone", func() { BeforeEach(func() { reqId, err = cl.Update(context.Background(), &s1, nil) }) It("returns job_id", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal(id1)) }) It("patch json", func() { Expect(cl.RequestBody["/common_configs/1/cc_notice_accounts/user1"]).To(MatchJSON(`{ "name": "user1", "lang": "ja", "props": { "mail": "mail@example.jp", "phone": { "country_code": "81", "number": "300000000" } } }`)) }) }) When("update mail only", func() { BeforeEach(func() { reqId, err = cl.Update(context.Background(), &s2, nil) }) It("returns job_id", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal(id2)) }) It("patch json", func() { Expect(cl.RequestBody["/common_configs/1/cc_notice_accounts/user2"]).To(MatchJSON(`{ "name": "user2", "lang": "en_US", "props": { "mail": "mail2@example.com" } }`)) }) }) }) Context("Delete", func() { id1, bs1 := testtool.CreateAsyncResponse() BeforeEach(func() { httpmock.RegisterResponder(http.MethodDelete, "http://localhost/common_configs/1/cc_notice_accounts/user1", httpmock.NewBytesResponder(202, bs1)) }) AfterEach(func() { httpmock.Reset() }) When("delete", func() { BeforeEach(func() { reqId, err = cl.Delete(context.Background(), &s1) }) It("returns normal", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal(id1)) }) }) }) Context("SetPathParams", func() { When("no arguments, nothing to do", func() { BeforeEach(func() { err = s1.SetPathParams() }) It("returns error", func() { Expect(err).To(Succeed()) }) }) When("enough arguments", func() { BeforeEach(func() { err = s1.SetPathParams(100, "user") }) It("not returns error", func() { Expect(err).To(Succeed()) }) It("can set CommonConfigID", func() { Expect(s1.GetCommonConfigID()).To(Equal(int64(100))) }) It("can set ResourceName", func() { Expect(s1.ResourceName).To(Equal("user")) }) }) When("not enough arguments", func() { BeforeEach(func() { err = s1.SetPathParams(100) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) When("arguments has extra value", func() { BeforeEach(func() { err = s1.SetPathParams(100, "user", 2) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) When("arguments type missmatch (CommonConfigID)", func() { BeforeEach(func() { err = s1.SetPathParams("2", "user") }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) When("arguments type missmatch (Id)", func() { BeforeEach(func() { err = s1.SetPathParams(100, 1) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) }) Context("api.Spec common test", func() { var nilSpec *common_configs.CcPrimary testtool.TestDeepCopyObject(&s1, nilSpec) testtool.TestGetName(&s1, "cc_notice_accounts") testtool.TestGetPathMethodForSpec(&s1, "/common_configs/1/cc_notice_accounts", "/common_configs/1/cc_notice_accounts/user1") }) }) Describe("CcNoticeAccountList", func() { var c common_configs.CcNoticeAccountList Context("List", func() { BeforeEach(func() { httpmock.RegisterResponder(http.MethodGet, "http://localhost/common_configs/1/cc_notice_accounts", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "1194A148B9B34C5F81977EF17A39CD4C", "results": [ { "resource_name": "user1", "name": "user1", "lang": "ja", "props": { "mail": "mail@example.jp", "phone": { "country_code": "81", "number": "300000000" } } }, { "resource_name": "user2", "name": "user2", "lang": "en_US", "props": { "mail": "mail2@example.com" } } ] }`))) }) AfterEach(func() { httpmock.Reset() }) When("returns list ", func() { BeforeEach(func() { c = common_configs.CcNoticeAccountList{ AttributeMeta: common_configs.AttributeMeta{ CommonConfigID: 1, }, } reqId, err = cl.List(context.Background(), &c, nil) }) It("returns normal", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal("1194A148B9B34C5F81977EF17A39CD4C")) Expect(c).To(Equal(slist)) }) }) }) Context("SetPathParams", func() { When("no arguments, nothing to do", func() { BeforeEach(func() { err = slist.SetPathParams() }) It("returns error", func() { Expect(err).To(Succeed()) }) }) When("enough arguments", func() { BeforeEach(func() { err = slist.SetPathParams(99) }) It("not returns error", func() { Expect(err).To(Succeed()) }) It("can set CommonConfigID", func() { Expect(slist.GetCommonConfigID()).To(Equal(int64(99))) }) }) When("arguments has extra value", func() { BeforeEach(func() { err = slist.SetPathParams(100, 2) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) When("arguments type missmatch (CommonConfigID)", func() { BeforeEach(func() { err = slist.SetPathParams("2") }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) }) Context("api.Spec common test", func() { var nilSpec *common_configs.CcPrimaryList testtool.TestDeepCopyObject(&slist, nilSpec) testtool.TestGetName(&slist, "cc_notice_accounts") testtool.TestGetPathMethodForList(&slist, "/common_configs/1/cc_notice_accounts") }) Context("api.ListSpec common test", func() { testtool.TestGetItems(&slist, &slist.Items) testtool.TestLen(&slist, 2) Context("Index", func() { When("index exist", func() { It("returns item", func() { Expect(slist.Index(0)).To(Equal(s1)) }) }) }) }) }) }) golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/common_configs/cc_primary.go000066400000000000000000000037111437707610400246160ustar00rootroot00000000000000package common_configs import ( "net" "github.com/mimuret/golang-iij-dpf/pkg/api" "github.com/mimuret/golang-iij-dpf/pkg/apis" "github.com/mimuret/golang-iij-dpf/pkg/types" ) // for IDE. var _ ChildSpec = &CcPrimary{} // +k8s:deepcopy-gen:interfaces=github.com/mimuret/golang-iij-dpf/pkg/api.Object type CcPrimary struct { AttributeMeta ID int64 `read:"id,omitempty" id:"2,required"` Address net.IP `read:"address" create:"address" update:"address"` TsigID types.NullablePositiveInt64 `read:"tsig_id" create:"tsig_id" update:"tsig_id"` Enabled types.Boolean `read:"enabled" update:"enabled"` } func (c *CcPrimary) SetPathParams(args ...interface{}) error { return apis.SetPathParams(args, &c.CommonConfigID, &c.ID) } func (c *CcPrimary) GetID() int64 { return c.ID } func (c *CcPrimary) SetID(id int64) { c.ID = id } func (c *CcPrimary) GetName() string { return "cc_primaries" } func (c *CcPrimary) GetPathMethod(action api.Action) (string, string) { return GetPathMethodForChildSpec(action, c) } // for IDE. var _ ListSpec = &CcPrimaryList{} // +k8s:deepcopy-gen:interfaces=github.com/mimuret/golang-iij-dpf/pkg/api.Object type CcPrimaryList struct { AttributeMeta Items []CcPrimary `read:"items"` } func (c *CcPrimaryList) SetPathParams(args ...interface{}) error { return apis.SetPathParams(args, &c.CommonConfigID) } func (c *CcPrimaryList) GetPathMethod(action api.Action) (string, string) { return GetPathMethodForListSpec(action, c) } func (c *CcPrimaryList) GetName() string { return "cc_primaries" } func (c *CcPrimaryList) GetItems() interface{} { return &c.Items } func (c *CcPrimaryList) Len() int { return len(c.Items) } func (c *CcPrimaryList) Index(i int) interface{} { return c.Items[i] } func (c *CcPrimaryList) Init() { for i := range c.Items { c.Items[i].AttributeMeta = c.AttributeMeta } } func init() { register(&CcPrimary{}, &CcPrimaryList{}) } golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/common_configs/cc_primary_test.go000066400000000000000000000263201437707610400256560ustar00rootroot00000000000000package common_configs_test import ( "context" "net" "net/http" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/jarcoal/httpmock" "github.com/mimuret/golang-iij-dpf/pkg/apis/dpf/v1/common_configs" "github.com/mimuret/golang-iij-dpf/pkg/testtool" "github.com/mimuret/golang-iij-dpf/pkg/types" ) var _ = Describe("cc_primaries", func() { var ( c common_configs.CcPrimary cl *testtool.TestClient err error reqId string s1, s2 common_configs.CcPrimary slist common_configs.CcPrimaryList ) BeforeEach(func() { cl = testtool.NewTestClient("", "http://localhost", nil) s1 = common_configs.CcPrimary{ AttributeMeta: common_configs.AttributeMeta{ CommonConfigID: 1, }, ID: 1, Address: net.ParseIP("192.168.0.1"), TsigID: 0, Enabled: types.Disabled, } s2 = common_configs.CcPrimary{ AttributeMeta: common_configs.AttributeMeta{ CommonConfigID: 1, }, ID: 2, Address: net.ParseIP("2001:db8::1"), TsigID: 2, Enabled: types.Enabled, } slist = common_configs.CcPrimaryList{ AttributeMeta: common_configs.AttributeMeta{ CommonConfigID: 1, }, Items: []common_configs.CcPrimary{s1, s2}, } }) Describe("CCPrimary", func() { Context("Read", func() { BeforeEach(func() { httpmock.RegisterResponder(http.MethodGet, "http://localhost/common_configs/1/cc_primaries/1", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "73A87F978AFD42D8B0AC810218AEC7CC", "result": { "id": 1, "address": "192.168.0.1", "tsig_id": null, "enabled": 0 } }`))) httpmock.RegisterResponder(http.MethodGet, "http://localhost/common_configs/1/cc_primaries/2", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "EBCA51F1CCD8457FB242766B59B5786E", "result": { "id": 2, "address": "2001:db8::1", "tsig_id": 2, "enabled": 1 } }`))) }) AfterEach(func() { httpmock.Reset() }) When("returns IPv4 server", func() { BeforeEach(func() { c = common_configs.CcPrimary{ AttributeMeta: common_configs.AttributeMeta{ CommonConfigID: 1, }, ID: 1, } reqId, err = cl.Read(context.Background(), &c) }) It("returns normal", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal("73A87F978AFD42D8B0AC810218AEC7CC")) Expect(c).To(Equal(s1)) }) }) When("returns IPv6 server", func() { BeforeEach(func() { c = common_configs.CcPrimary{ AttributeMeta: common_configs.AttributeMeta{ CommonConfigID: 1, }, ID: 2, } reqId, err = cl.Read(context.Background(), &c) }) It("returns normal", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal("EBCA51F1CCD8457FB242766B59B5786E")) Expect(c).To(Equal(s2)) }) }) }) Context("Create", func() { var ( id1, bs1 = testtool.CreateAsyncResponse() id2, bs2 = testtool.CreateAsyncResponse() ) BeforeEach(func() { httpmock.RegisterResponder(http.MethodPost, "http://localhost/common_configs/2/cc_primaries", httpmock.NewBytesResponder(202, bs1)) httpmock.RegisterResponder(http.MethodPost, "http://localhost/common_configs/3/cc_primaries", httpmock.NewBytesResponder(202, bs2)) }) AfterEach(func() { httpmock.Reset() }) When("ipv4 host", func() { BeforeEach(func() { s := common_configs.CcPrimary{ AttributeMeta: common_configs.AttributeMeta{ CommonConfigID: 2, }, Address: net.ParseIP("192.168.10.1"), TsigID: 1, } reqId, err = cl.Create(context.Background(), &s, nil) }) It("returns job_id", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal(id1)) }) It("post json", func() { Expect(cl.RequestBody["/common_configs/2/cc_primaries"]).To(MatchJSON(`{ "address": "192.168.10.1", "tsig_id": 1 }`)) }) }) When("ipv6 host", func() { BeforeEach(func() { s := common_configs.CcPrimary{ AttributeMeta: common_configs.AttributeMeta{ CommonConfigID: 3, }, Address: net.ParseIP("2001:db8::1"), } reqId, err = cl.Create(context.Background(), &s, nil) }) It("returns job_id", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal(id2)) }) It("post json", func() { Expect(cl.RequestBody["/common_configs/3/cc_primaries"]).To(MatchJSON(`{ "address": "2001:db8::1", "tsig_id": null }`)) }) }) }) Context("Update", func() { var ( id1, bs1 = testtool.CreateAsyncResponse() id2, bs2 = testtool.CreateAsyncResponse() ) BeforeEach(func() { httpmock.RegisterResponder(http.MethodPatch, "http://localhost/common_configs/1/cc_primaries/1", httpmock.NewBytesResponder(202, bs1)) httpmock.RegisterResponder(http.MethodPatch, "http://localhost/common_configs/1/cc_primaries/2", httpmock.NewBytesResponder(202, bs2)) }) AfterEach(func() { httpmock.Reset() }) When("ipv4 host", func() { BeforeEach(func() { reqId, err = cl.Update(context.Background(), &s1, nil) }) It("returns job_id", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal(id1)) }) It("post json", func() { Expect(cl.RequestBody["/common_configs/1/cc_primaries/1"]).To(MatchJSON(`{ "address": "192.168.0.1", "enabled": 0, "tsig_id": null }`)) }) }) When("ipv6 host", func() { BeforeEach(func() { reqId, err = cl.Update(context.Background(), &s2, nil) }) It("returns job_id", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal(id2)) }) It("post json", func() { Expect(cl.RequestBody["/common_configs/1/cc_primaries/2"]).To(MatchJSON(`{ "address": "2001:db8::1", "tsig_id": 2, "enabled": 1 }`)) }) }) }) Context("Delete", func() { var ( id1, bs1 = testtool.CreateAsyncResponse() id2, bs2 = testtool.CreateAsyncResponse() ) BeforeEach(func() { httpmock.RegisterResponder(http.MethodDelete, "http://localhost/common_configs/1/cc_primaries/1", httpmock.NewBytesResponder(202, bs1)) httpmock.RegisterResponder(http.MethodDelete, "http://localhost/common_configs/1/cc_primaries/2", httpmock.NewBytesResponder(202, bs2)) }) AfterEach(func() { httpmock.Reset() }) When("returns IPv4 server", func() { BeforeEach(func() { reqId, err = cl.Delete(context.Background(), &s1) }) It("returns normal", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal(id1)) }) }) When("returns IPv6 server", func() { BeforeEach(func() { reqId, err = cl.Delete(context.Background(), &s2) }) It("returns normal", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal(id2)) }) }) }) Context("SetPathParams", func() { When("no arguments, nothing to do", func() { BeforeEach(func() { err = s1.SetPathParams() }) It("returns error", func() { Expect(err).To(Succeed()) }) }) When("enough arguments", func() { BeforeEach(func() { err = s1.SetPathParams(100, 200) }) It("not returns error", func() { Expect(err).To(Succeed()) }) It("can set CommonConfigID", func() { Expect(s1.GetCommonConfigID()).To(Equal(int64(100))) }) It("can set Id", func() { Expect(s1.GetID()).To(Equal(int64(200))) }) }) When("not enough arguments", func() { BeforeEach(func() { err = s1.SetPathParams(100) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) When("arguments has extra value", func() { BeforeEach(func() { err = s1.SetPathParams(100, 1, 2) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) When("arguments type missmatch (CommonConfigID)", func() { BeforeEach(func() { err = s1.SetPathParams("2", 1) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) When("arguments type missmatch (Id)", func() { BeforeEach(func() { err = s1.SetPathParams(100, "1") }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) }) Context("api.Spec common test", func() { var nilSpec *common_configs.CcPrimary testtool.TestDeepCopyObject(&s1, nilSpec) testtool.TestGetName(&s1, "cc_primaries") testtool.TestGetPathMethodForSpec(&s1, "/common_configs/1/cc_primaries", "/common_configs/1/cc_primaries/1") }) Context("contracts.ChildSpec common test", func() { Context("GetID", func() { It("returns Id", func() { Expect(s1.GetID()).To(Equal(s1.ID)) }) }) Context("SetID", func() { BeforeEach(func() { s1.SetID(2) }) It("can set Id", func() { Expect(s1.GetID()).To(Equal(int64(2))) }) }) }) }) Describe("CCPrimaryList", func() { var c common_configs.CcPrimaryList Context("List", func() { BeforeEach(func() { httpmock.RegisterResponder(http.MethodGet, "http://localhost/common_configs/1/cc_primaries", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "1194A148B9B34C5F81977EF17A39CD4C", "results": [ { "id": 1, "address": "192.168.0.1", "tsig_id": null, "enabled": 0 }, { "id": 2, "address": "2001:db8::1", "tsig_id": 2, "enabled": 1 } ] }`))) }) AfterEach(func() { httpmock.Reset() }) When("returns list ", func() { BeforeEach(func() { c = common_configs.CcPrimaryList{ AttributeMeta: common_configs.AttributeMeta{ CommonConfigID: 1, }, } reqId, err = cl.List(context.Background(), &c, nil) }) It("returns normal", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal("1194A148B9B34C5F81977EF17A39CD4C")) Expect(c).To(Equal(slist)) }) }) }) Context("SetPathParams", func() { When("no arguments, nothing to do", func() { BeforeEach(func() { err = slist.SetPathParams() }) It("returns error", func() { Expect(err).To(Succeed()) }) }) When("enough arguments", func() { BeforeEach(func() { err = slist.SetPathParams(99) }) It("not returns error", func() { Expect(err).To(Succeed()) }) It("can set CommonConfigID", func() { Expect(slist.GetCommonConfigID()).To(Equal(int64(99))) }) }) When("arguments has extra value", func() { BeforeEach(func() { err = slist.SetPathParams(100, 2) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) When("arguments type missmatch (CommonConfigID)", func() { BeforeEach(func() { err = slist.SetPathParams("2") }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) }) Context("api.Spec common test", func() { var nilSpec *common_configs.CcPrimaryList testtool.TestDeepCopyObject(&slist, nilSpec) testtool.TestGetName(&slist, "cc_primaries") testtool.TestGetPathMethodForList(&slist, "/common_configs/1/cc_primaries") }) Context("api.ListSpec common test", func() { testtool.TestGetItems(&slist, &slist.Items) testtool.TestLen(&slist, 2) Context("Index", func() { When("index exist", func() { It("returns item", func() { Expect(slist.Index(0)).To(Equal(s1)) }) }) }) }) }) }) golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/common_configs/cc_sec_notified_server.go000066400000000000000000000042261437707610400271560ustar00rootroot00000000000000package common_configs import ( "net" "github.com/mimuret/golang-iij-dpf/pkg/api" "github.com/mimuret/golang-iij-dpf/pkg/apis" "github.com/mimuret/golang-iij-dpf/pkg/types" ) // for IDE. var _ ChildSpec = &CcSecNotifiedServer{} // +k8s:deepcopy-gen:interfaces=github.com/mimuret/golang-iij-dpf/pkg/api.Object type CcSecNotifiedServer struct { AttributeMeta `read:"-" create:"-" update:"-"` ID int64 `read:"id" create:"-" update:"-" id:"2,required"` Address net.IP `read:"address" create:"address" update:"address"` TsigID types.NullablePositiveInt64 `read:"tsig_id" create:"tsig_id" update:"tsig_id"` } func (c *CcSecNotifiedServer) SetPathParams(args ...interface{}) error { return apis.SetPathParams(args, &c.CommonConfigID, &c.ID) } func (c *CcSecNotifiedServer) GetID() int64 { return c.ID } func (c *CcSecNotifiedServer) SetID(id int64) { c.ID = id } func (c *CcSecNotifiedServer) GetName() string { return "cc_sec_notified_servers" } func (c *CcSecNotifiedServer) GetPathMethod(action api.Action) (string, string) { return GetPathMethodForChildSpec(action, c) } // for IDE var _ ListSpec = &CcSecNotifiedServerList{} // +k8s:deepcopy-gen:interfaces=github.com/mimuret/golang-iij-dpf/pkg/api.Object type CcSecNotifiedServerList struct { AttributeMeta Items []CcSecNotifiedServer `read:"items"` } func (c *CcSecNotifiedServerList) SetPathParams(args ...interface{}) error { return apis.SetPathParams(args, &c.CommonConfigID) } func (c *CcSecNotifiedServerList) GetName() string { return "cc_sec_notified_servers" } func (c *CcSecNotifiedServerList) GetItems() interface{} { return &c.Items } func (c *CcSecNotifiedServerList) Len() int { return len(c.Items) } func (c *CcSecNotifiedServerList) Index(i int) interface{} { return c.Items[i] } func (c *CcSecNotifiedServerList) GetPathMethod(action api.Action) (string, string) { return GetPathMethodForListSpec(action, c) } func (c *CcSecNotifiedServerList) Init() { for i := range c.Items { c.Items[i].AttributeMeta = c.AttributeMeta } } func init() { register(&CcSecNotifiedServer{}, &CcSecNotifiedServerList{}) } golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/common_configs/cc_sec_notified_server_test.go000066400000000000000000000265471437707610400302270ustar00rootroot00000000000000package common_configs_test import ( "context" "net" "net/http" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/jarcoal/httpmock" "github.com/mimuret/golang-iij-dpf/pkg/apis/dpf/v1/common_configs" "github.com/mimuret/golang-iij-dpf/pkg/testtool" ) var _ = Describe("cc_sec_notified_servers", func() { var ( c common_configs.CcSecNotifiedServer cl *testtool.TestClient err error reqId string s1, s2 common_configs.CcSecNotifiedServer slist common_configs.CcSecNotifiedServerList ) BeforeEach(func() { cl = testtool.NewTestClient("", "http://localhost", nil) s1 = common_configs.CcSecNotifiedServer{ AttributeMeta: common_configs.AttributeMeta{ CommonConfigID: 1, }, ID: 1, Address: net.ParseIP("192.168.0.1"), TsigID: 0, } s2 = common_configs.CcSecNotifiedServer{ AttributeMeta: common_configs.AttributeMeta{ CommonConfigID: 1, }, ID: 2, Address: net.ParseIP("2001:db8::1"), TsigID: 2, } slist = common_configs.CcSecNotifiedServerList{ AttributeMeta: common_configs.AttributeMeta{ CommonConfigID: 1, }, Items: []common_configs.CcSecNotifiedServer{s1, s2}, } }) Describe("CcSecNotifiedServer", func() { Context("Read", func() { BeforeEach(func() { httpmock.RegisterResponder(http.MethodGet, "http://localhost/common_configs/1/cc_sec_notified_servers/1", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "5D7FECB0A56C49C2B73BD45DD174A575", "result": { "id": 1, "address": "192.168.0.1", "tsig_id": null } }`))) httpmock.RegisterResponder(http.MethodGet, "http://localhost/common_configs/1/cc_sec_notified_servers/2", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "5ABBBEF090DF4F208AD9EDEAC7D702A5", "result": { "id": 2, "address": "2001:db8::1", "tsig_id": 2 } }`))) }) AfterEach(func() { httpmock.Reset() }) When("returns IPv4 server", func() { BeforeEach(func() { c = common_configs.CcSecNotifiedServer{ AttributeMeta: common_configs.AttributeMeta{ CommonConfigID: 1, }, ID: 1, } reqId, err = cl.Read(context.Background(), &c) }) It("returns normal", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal("5D7FECB0A56C49C2B73BD45DD174A575")) Expect(c).To(Equal(s1)) }) }) When("returns IPv6 server", func() { BeforeEach(func() { c = common_configs.CcSecNotifiedServer{ AttributeMeta: common_configs.AttributeMeta{ CommonConfigID: 1, }, ID: 2, } reqId, err = cl.Read(context.Background(), &c) }) It("returns normal", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal("5ABBBEF090DF4F208AD9EDEAC7D702A5")) Expect(c).To(Equal(s2)) }) }) }) Context("Create", func() { var ( id1, bs1 = testtool.CreateAsyncResponse() id2, bs2 = testtool.CreateAsyncResponse() ) BeforeEach(func() { httpmock.RegisterResponder(http.MethodPost, "http://localhost/common_configs/2/cc_sec_notified_servers", httpmock.NewBytesResponder(202, bs1)) httpmock.RegisterResponder(http.MethodPost, "http://localhost/common_configs/3/cc_sec_notified_servers", httpmock.NewBytesResponder(202, bs2)) }) AfterEach(func() { httpmock.Reset() }) When("ipv4 host", func() { BeforeEach(func() { s := common_configs.CcSecNotifiedServer{ AttributeMeta: common_configs.AttributeMeta{ CommonConfigID: 2, }, Address: net.ParseIP("192.168.10.1"), TsigID: 1, } reqId, err = cl.Create(context.Background(), &s, nil) }) It("returns job_id", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal(id1)) }) It("post json", func() { Expect(cl.RequestBody["/common_configs/2/cc_sec_notified_servers"]).To(MatchJSON(`{ "address": "192.168.10.1", "tsig_id": 1 }`)) }) }) When("ipv6 host", func() { BeforeEach(func() { s := common_configs.CcSecNotifiedServer{ AttributeMeta: common_configs.AttributeMeta{ CommonConfigID: 3, }, Address: net.ParseIP("2001:db8::1"), } reqId, err = cl.Create(context.Background(), &s, nil) }) It("returns job_id", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal(id2)) }) It("post json", func() { Expect(cl.RequestBody["/common_configs/3/cc_sec_notified_servers"]).To(MatchJSON(`{ "address": "2001:db8::1", "tsig_id": null }`)) }) }) }) Context("Update", func() { var ( id1, bs1 = testtool.CreateAsyncResponse() id2, bs2 = testtool.CreateAsyncResponse() ) BeforeEach(func() { httpmock.RegisterResponder(http.MethodPatch, "http://localhost/common_configs/1/cc_sec_notified_servers/1", httpmock.NewBytesResponder(202, bs1)) httpmock.RegisterResponder(http.MethodPatch, "http://localhost/common_configs/1/cc_sec_notified_servers/2", httpmock.NewBytesResponder(202, bs2)) }) AfterEach(func() { httpmock.Reset() }) When("ipv4 host", func() { BeforeEach(func() { reqId, err = cl.Update(context.Background(), &s1, nil) }) It("returns job_id", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal(id1)) }) It("post json", func() { Expect(cl.RequestBody["/common_configs/1/cc_sec_notified_servers/1"]).To(MatchJSON(`{ "address": "192.168.0.1", "tsig_id": null }`)) }) }) When("ipv6 host", func() { BeforeEach(func() { reqId, err = cl.Update(context.Background(), &s2, nil) }) It("returns job_id", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal(id2)) }) It("post json", func() { Expect(cl.RequestBody["/common_configs/1/cc_sec_notified_servers/2"]).To(MatchJSON(`{ "address": "2001:db8::1", "tsig_id": 2 }`)) }) }) }) Context("Delete", func() { var ( id1, bs1 = testtool.CreateAsyncResponse() id2, bs2 = testtool.CreateAsyncResponse() ) BeforeEach(func() { httpmock.RegisterResponder(http.MethodDelete, "http://localhost/common_configs/1/cc_sec_notified_servers/1", httpmock.NewBytesResponder(202, bs1)) httpmock.RegisterResponder(http.MethodDelete, "http://localhost/common_configs/1/cc_sec_notified_servers/2", httpmock.NewBytesResponder(202, bs2)) }) AfterEach(func() { httpmock.Reset() }) When("returns IPv4 server", func() { BeforeEach(func() { reqId, err = cl.Delete(context.Background(), &s1) }) It("returns normal", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal(id1)) }) }) When("returns IPv6 server", func() { BeforeEach(func() { reqId, err = cl.Delete(context.Background(), &s2) }) It("returns normal", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal(id2)) }) }) }) Context("SetPathParams", func() { When("no arguments, nothing to do", func() { BeforeEach(func() { err = s1.SetPathParams() }) It("returns error", func() { Expect(err).To(Succeed()) }) }) When("enough arguments", func() { BeforeEach(func() { err = s1.SetPathParams(100, 200) }) It("not returns error", func() { Expect(err).To(Succeed()) }) It("can set CommonConfigID", func() { Expect(s1.GetCommonConfigID()).To(Equal(int64(100))) }) It("can set Id", func() { Expect(s1.GetID()).To(Equal(int64(200))) }) }) When("not enough arguments", func() { BeforeEach(func() { err = s1.SetPathParams(100) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) When("arguments has extra value", func() { BeforeEach(func() { err = s1.SetPathParams(100, 1, 2) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) When("arguments type missmatch (CommonConfigID)", func() { BeforeEach(func() { err = s1.SetPathParams("2", 1) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) When("arguments type missmatch (Id)", func() { BeforeEach(func() { err = s1.SetPathParams(100, "1") }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) }) Context("api.Spec common test", func() { var nilSpec *common_configs.CcSecNotifiedServer testtool.TestDeepCopyObject(&s1, nilSpec) testtool.TestGetName(&s1, "cc_sec_notified_servers") testtool.TestGetPathMethodForSpec(&s1, "/common_configs/1/cc_sec_notified_servers", "/common_configs/1/cc_sec_notified_servers/1") }) Context("contracts.ChildSpec common test", func() { Context("GetID", func() { It("returns Id", func() { Expect(s1.GetID()).To(Equal(s1.ID)) }) }) Context("SetID", func() { BeforeEach(func() { s1.SetID(2) }) It("can set Id", func() { Expect(s1.GetID()).To(Equal(int64(2))) }) }) }) }) Describe("CcSecNotifiedServerList", func() { var c common_configs.CcSecNotifiedServerList Context("List", func() { BeforeEach(func() { httpmock.RegisterResponder(http.MethodGet, "http://localhost/common_configs/1/cc_sec_notified_servers", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "450B94B486D34D548313707FC7590CE0", "results": [ { "id": 1, "address": "192.168.0.1", "tsig_id": null }, { "id": 2, "address": "2001:db8::1", "tsig_id": 2 } ] }`))) }) AfterEach(func() { httpmock.Reset() }) When("returns list ", func() { BeforeEach(func() { c = common_configs.CcSecNotifiedServerList{ AttributeMeta: common_configs.AttributeMeta{ CommonConfigID: 1, }, } reqId, err = cl.List(context.Background(), &c, nil) }) It("returns normal", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal("450B94B486D34D548313707FC7590CE0")) Expect(c).To(Equal(slist)) }) }) }) Context("SetPathParams", func() { When("no arguments, nothing to do", func() { BeforeEach(func() { err = slist.SetPathParams() }) It("returns error", func() { Expect(err).To(Succeed()) }) }) When("enough arguments", func() { BeforeEach(func() { err = slist.SetPathParams(99) }) It("not returns error", func() { Expect(err).To(Succeed()) }) It("can set CommonConfigID", func() { Expect(slist.GetCommonConfigID()).To(Equal(int64(99))) }) }) When("arguments has extra value", func() { BeforeEach(func() { err = slist.SetPathParams(100, 2) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) When("arguments type missmatch (CommonConfigID)", func() { BeforeEach(func() { err = slist.SetPathParams("2") }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) }) Context("api.Spec common test", func() { var nilSpec *common_configs.CcSecNotifiedServerList testtool.TestDeepCopyObject(&slist, nilSpec) testtool.TestGetName(&slist, "cc_sec_notified_servers") testtool.TestGetPathMethodForList(&slist, "/common_configs/1/cc_sec_notified_servers") }) Context("api.ListSpec common test", func() { testtool.TestGetItems(&slist, &slist.Items) testtool.TestLen(&slist, 2) Context("Index", func() { When("index exist", func() { It("returns item", func() { Expect(slist.Index(0)).To(Equal(s1)) }) }) }) }) }) }) golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/common_configs/cc_sec_transfer_acl.go000066400000000000000000000040041437707610400264240ustar00rootroot00000000000000package common_configs import ( "github.com/mimuret/golang-iij-dpf/pkg/api" "github.com/mimuret/golang-iij-dpf/pkg/apis" "github.com/mimuret/golang-iij-dpf/pkg/types" ) // for IDE var _ ChildSpec = &CcSecTransferAcl{} // +k8s:deepcopy-gen:interfaces=github.com/mimuret/golang-iij-dpf/pkg/api.Object type CcSecTransferAcl struct { AttributeMeta ID int64 `read:"id" id:"2,required"` Network *types.IPNet `read:"network" create:"network" update:"network"` TsigID types.NullablePositiveInt64 `read:"tsig_id" create:"tsig_id" update:"tsig_id"` } func (c *CcSecTransferAcl) SetPathParams(args ...interface{}) error { return apis.SetPathParams(args, &c.CommonConfigID, &c.ID) } func (c *CcSecTransferAcl) GetID() int64 { return c.ID } func (c *CcSecTransferAcl) SetID(id int64) { c.ID = id } func (c *CcSecTransferAcl) GetName() string { return "cc_sec_transfer_acls" } func (c *CcSecTransferAcl) GetPathMethod(action api.Action) (string, string) { return GetPathMethodForChildSpec(action, c) } // for IDE var _ ListSpec = &CcSecTransferAclList{} // +k8s:deepcopy-gen:interfaces=github.com/mimuret/golang-iij-dpf/pkg/api.Object type CcSecTransferAclList struct { AttributeMeta Items []CcSecTransferAcl `read:"items"` } func (c *CcSecTransferAclList) SetPathParams(args ...interface{}) error { return apis.SetPathParams(args, &c.CommonConfigID) } func (c *CcSecTransferAclList) GetName() string { return "cc_sec_transfer_acls" } func (c *CcSecTransferAclList) GetItems() interface{} { return &c.Items } func (c *CcSecTransferAclList) Len() int { return len(c.Items) } func (c *CcSecTransferAclList) Index(i int) interface{} { return c.Items[i] } func (c *CcSecTransferAclList) GetPathMethod(action api.Action) (string, string) { return GetPathMethodForListSpec(action, c) } func (c *CcSecTransferAclList) Init() { for i := range c.Items { c.Items[i].AttributeMeta = c.AttributeMeta } } func init() { register(&CcSecTransferAcl{}, &CcSecTransferAclList{}) } golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/common_configs/cc_sec_transfer_acl_test.go000066400000000000000000000264741437707610400275020ustar00rootroot00000000000000package common_configs_test import ( "context" "net/http" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/jarcoal/httpmock" "github.com/mimuret/golang-iij-dpf/pkg/apis/dpf/v1/common_configs" "github.com/mimuret/golang-iij-dpf/pkg/testtool" ) var _ = Describe("cc_sec_transfer_acls", func() { var ( c common_configs.CcSecTransferAcl cl *testtool.TestClient err error reqId string s1, s2 common_configs.CcSecTransferAcl slist common_configs.CcSecTransferAclList ) BeforeEach(func() { cl = testtool.NewTestClient("", "http://localhost", nil) s1 = common_configs.CcSecTransferAcl{ AttributeMeta: common_configs.AttributeMeta{ CommonConfigID: 1, }, ID: 1, Network: testtool.MustParseIPNet("192.168.1.0/24"), TsigID: 0, } s2 = common_configs.CcSecTransferAcl{ AttributeMeta: common_configs.AttributeMeta{ CommonConfigID: 1, }, ID: 2, Network: testtool.MustParseIPNet("2001:db8::/64"), TsigID: 2, } slist = common_configs.CcSecTransferAclList{ AttributeMeta: common_configs.AttributeMeta{ CommonConfigID: 1, }, Items: []common_configs.CcSecTransferAcl{s1, s2}, } }) Describe("CcSecTransferAcl", func() { Context("Read", func() { BeforeEach(func() { httpmock.RegisterResponder(http.MethodGet, "http://localhost/common_configs/1/cc_sec_transfer_acls/1", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "C5E6406DCBFC4931A0EE480ABA9FA505", "result": { "id": 1, "network": "192.168.1.0/24", "tsig_id": null } }`))) httpmock.RegisterResponder(http.MethodGet, "http://localhost/common_configs/1/cc_sec_transfer_acls/2", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "3D82ADCA5479408094DEF876A679BFD3", "result": { "id": 2, "network": "2001:db8::/64", "tsig_id": 2 } }`))) }) AfterEach(func() { httpmock.Reset() }) When("returns IPv4 server", func() { BeforeEach(func() { c = common_configs.CcSecTransferAcl{ AttributeMeta: common_configs.AttributeMeta{ CommonConfigID: 1, }, ID: 1, } reqId, err = cl.Read(context.Background(), &c) }) It("returns normal", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal("C5E6406DCBFC4931A0EE480ABA9FA505")) Expect(c).To(Equal(s1)) }) }) When("returns IPv6 server", func() { BeforeEach(func() { c = common_configs.CcSecTransferAcl{ AttributeMeta: common_configs.AttributeMeta{ CommonConfigID: 1, }, ID: 2, } reqId, err = cl.Read(context.Background(), &c) }) It("returns normal", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal("3D82ADCA5479408094DEF876A679BFD3")) Expect(c).To(Equal(s2)) }) }) }) Context("Create", func() { var ( id1, bs1 = testtool.CreateAsyncResponse() id2, bs2 = testtool.CreateAsyncResponse() ) BeforeEach(func() { httpmock.RegisterResponder(http.MethodPost, "http://localhost/common_configs/2/cc_sec_transfer_acls", httpmock.NewBytesResponder(202, bs1)) httpmock.RegisterResponder(http.MethodPost, "http://localhost/common_configs/3/cc_sec_transfer_acls", httpmock.NewBytesResponder(202, bs2)) }) AfterEach(func() { httpmock.Reset() }) When("ipv4 host", func() { BeforeEach(func() { s := common_configs.CcSecTransferAcl{ AttributeMeta: common_configs.AttributeMeta{ CommonConfigID: 2, }, Network: testtool.MustParseIPNet("10.0.0.0/8"), TsigID: 1, } reqId, err = cl.Create(context.Background(), &s, nil) }) It("returns job_id", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal(id1)) }) It("post json", func() { Expect(cl.RequestBody["/common_configs/2/cc_sec_transfer_acls"]).To(MatchJSON(`{ "network": "10.0.0.0/8", "tsig_id": 1 }`)) }) }) When("ipv6 host", func() { BeforeEach(func() { s := common_configs.CcSecTransferAcl{ AttributeMeta: common_configs.AttributeMeta{ CommonConfigID: 3, }, Network: testtool.MustParseIPNet("2001:db8::/48"), } reqId, err = cl.Create(context.Background(), &s, nil) }) It("returns job_id", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal(id2)) }) It("post json", func() { Expect(cl.RequestBody["/common_configs/3/cc_sec_transfer_acls"]).To(MatchJSON(`{ "network": "2001:db8::/48", "tsig_id": null }`)) }) }) }) Context("Update", func() { var ( id1, bs1 = testtool.CreateAsyncResponse() id2, bs2 = testtool.CreateAsyncResponse() ) BeforeEach(func() { httpmock.RegisterResponder(http.MethodPatch, "http://localhost/common_configs/1/cc_sec_transfer_acls/1", httpmock.NewBytesResponder(202, bs1)) httpmock.RegisterResponder(http.MethodPatch, "http://localhost/common_configs/1/cc_sec_transfer_acls/2", httpmock.NewBytesResponder(202, bs2)) }) AfterEach(func() { httpmock.Reset() }) When("ipv4 host", func() { BeforeEach(func() { reqId, err = cl.Update(context.Background(), &s1, nil) }) It("returns job_id", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal(id1)) }) It("post json", func() { Expect(cl.RequestBody["/common_configs/1/cc_sec_transfer_acls/1"]).To(MatchJSON(`{ "network": "192.168.1.0/24", "tsig_id": null }`)) }) }) When("ipv6 host", func() { BeforeEach(func() { reqId, err = cl.Update(context.Background(), &s2, nil) }) It("returns job_id", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal(id2)) }) It("post json", func() { Expect(cl.RequestBody["/common_configs/1/cc_sec_transfer_acls/2"]).To(MatchJSON(`{ "network": "2001:db8::/64", "tsig_id": 2 }`)) }) }) }) Context("Delete", func() { var ( id1, bs1 = testtool.CreateAsyncResponse() id2, bs2 = testtool.CreateAsyncResponse() ) BeforeEach(func() { httpmock.RegisterResponder(http.MethodDelete, "http://localhost/common_configs/1/cc_sec_transfer_acls/1", httpmock.NewBytesResponder(202, bs1)) httpmock.RegisterResponder(http.MethodDelete, "http://localhost/common_configs/1/cc_sec_transfer_acls/2", httpmock.NewBytesResponder(202, bs2)) }) AfterEach(func() { httpmock.Reset() }) When("returns IPv4 server", func() { BeforeEach(func() { reqId, err = cl.Delete(context.Background(), &s1) }) It("returns normal", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal(id1)) }) }) When("returns IPv6 server", func() { BeforeEach(func() { reqId, err = cl.Delete(context.Background(), &s2) }) It("returns normal", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal(id2)) }) }) }) Context("SetPathParams", func() { When("no arguments, nothing to do", func() { BeforeEach(func() { err = s1.SetPathParams() }) It("returns error", func() { Expect(err).To(Succeed()) }) }) When("enough arguments", func() { BeforeEach(func() { err = s1.SetPathParams(100, 200) }) It("not returns error", func() { Expect(err).To(Succeed()) }) It("can set CommonConfigID", func() { Expect(s1.GetCommonConfigID()).To(Equal(int64(100))) }) It("can set Id", func() { Expect(s1.GetID()).To(Equal(int64(200))) }) }) When("not enough arguments", func() { BeforeEach(func() { err = s1.SetPathParams(100) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) When("arguments has extra value", func() { BeforeEach(func() { err = s1.SetPathParams(100, 1, 2) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) When("arguments type missmatch (CommonConfigID)", func() { BeforeEach(func() { err = s1.SetPathParams("2", 1) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) When("arguments type missmatch (Id)", func() { BeforeEach(func() { err = s1.SetPathParams(100, "1") }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) }) Context("api.Spec common test", func() { var nilSpec *common_configs.CcSecTransferAcl testtool.TestDeepCopyObject(&s1, nilSpec) testtool.TestGetName(&s1, "cc_sec_transfer_acls") testtool.TestGetPathMethodForSpec(&s1, "/common_configs/1/cc_sec_transfer_acls", "/common_configs/1/cc_sec_transfer_acls/1") }) Context("contracts.ChildSpec common test", func() { Context("GetID", func() { It("returns Id", func() { Expect(s1.GetID()).To(Equal(s1.ID)) }) }) Context("SetID", func() { BeforeEach(func() { s1.SetID(2) }) It("can set Id", func() { Expect(s1.GetID()).To(Equal(int64(2))) }) }) }) }) Describe("CcSecTransferAclList", func() { var c common_configs.CcSecTransferAclList Context("List", func() { BeforeEach(func() { httpmock.RegisterResponder(http.MethodGet, "http://localhost/common_configs/1/cc_sec_transfer_acls", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "13032F0785DA47768B3E36A1A854A808", "results": [ { "id": 1, "network": "192.168.1.0/24", "tsig_id": null }, { "id": 2, "network": "2001:db8::/64", "tsig_id": 2 } ] }`))) }) AfterEach(func() { httpmock.Reset() }) When("returns list ", func() { BeforeEach(func() { c = common_configs.CcSecTransferAclList{ AttributeMeta: common_configs.AttributeMeta{ CommonConfigID: 1, }, } reqId, err = cl.List(context.Background(), &c, nil) }) It("returns normal", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal("13032F0785DA47768B3E36A1A854A808")) Expect(c).To(Equal(slist)) }) }) }) Context("SetPathParams", func() { When("no arguments, nothing to do", func() { BeforeEach(func() { err = slist.SetPathParams() }) It("returns error", func() { Expect(err).To(Succeed()) }) }) When("enough arguments", func() { BeforeEach(func() { err = slist.SetPathParams(99) }) It("not returns error", func() { Expect(err).To(Succeed()) }) It("can set CommonConfigID", func() { Expect(slist.GetCommonConfigID()).To(Equal(int64(99))) }) }) When("arguments has extra value", func() { BeforeEach(func() { err = slist.SetPathParams(100, 2) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) When("arguments type missmatch (CommonConfigID)", func() { BeforeEach(func() { err = slist.SetPathParams("2") }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) }) Context("api.Spec common test", func() { var nilSpec *common_configs.CcSecTransferAclList testtool.TestDeepCopyObject(&slist, nilSpec) testtool.TestGetName(&slist, "cc_sec_transfer_acls") testtool.TestGetPathMethodForList(&slist, "/common_configs/1/cc_sec_transfer_acls") }) Context("api.ListSpec common test", func() { testtool.TestGetItems(&slist, &slist.Items) testtool.TestLen(&slist, 2) Context("Index", func() { When("index exist", func() { It("returns item", func() { Expect(slist.Index(0)).To(Equal(s1)) }) }) }) }) }) }) golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/common_configs/common.go000066400000000000000000000027231437707610400237600ustar00rootroot00000000000000package common_configs import ( "fmt" "github.com/mimuret/golang-iij-dpf/pkg/api" "github.com/mimuret/golang-iij-dpf/pkg/apis" "github.com/mimuret/golang-iij-dpf/pkg/schema" ) const groupName = "common-configs.api.dns-platform.jp/v1" func register(items ...apis.Spec) { schema.NewRegister(groupName).Add(items...) } type Spec interface { apis.Spec SetCommonConfigID(int64) GetCommonConfigID() int64 } type ChildSpec interface { Spec GetID() int64 SetID(int64) } type ListSpec interface { api.ListSpec Spec } type AttributeMeta struct { CommonConfigID int64 `read:"-" id:"1,required"` } func (s *AttributeMeta) GetGroup() string { return groupName } func (s *AttributeMeta) SetCommonConfigID(id int64) { s.CommonConfigID = id } func (s *AttributeMeta) GetCommonConfigID() int64 { return s.CommonConfigID } func GetPathMethodForChildSpec(action api.Action, s ChildSpec) (string, string) { switch action { case api.ActionCreate: return action.ToMethod(), fmt.Sprintf("/common_configs/%d/%s", s.GetCommonConfigID(), s.GetName()) case api.ActionRead, api.ActionUpdate, api.ActionDelete: return action.ToMethod(), fmt.Sprintf("/common_configs/%d/%s/%d", s.GetCommonConfigID(), s.GetName(), s.GetID()) } return "", "" } func GetPathMethodForListSpec(action api.Action, s ListSpec) (string, string) { if action == api.ActionList { return action.ToMethod(), fmt.Sprintf("/common_configs/%d/%s", s.GetCommonConfigID(), s.GetName()) } return "", "" } golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/common_configs/common_test.go000066400000000000000000000030671437707610400250210ustar00rootroot00000000000000package common_configs_test import ( "github.com/mimuret/golang-iij-dpf/pkg/apis/dpf/v1/common_configs" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("common_configs", func() { Context("AttributeMeta", func() { var meta common_configs.AttributeMeta BeforeEach(func() { meta = common_configs.AttributeMeta{} }) Context("GetGroup", func() { It("returns name", func() { Expect(meta.GetGroup()).To(Equal("common-configs.api.dns-platform.jp/v1")) }) }) Context("GetCommonConfigID", func() { When("default", func() { It("returns 0", func() { Expect(meta.GetCommonConfigID()).To(Equal(int64(0))) }) }) When("default", func() { BeforeEach(func() { meta.CommonConfigID = 1 }) It("returns CommonConfigID", func() { Expect(meta.GetCommonConfigID()).To(Equal(int64(1))) }) }) }) Context("SetCommonConfigID", func() { BeforeEach(func() { meta.SetCommonConfigID(2) }) It("can set CommonConfigID", func() { Expect(meta.GetCommonConfigID()).To(Equal(int64(2))) }) }) Context("DeepCopy", func() { var ( copy *common_configs.AttributeMeta nilMeta *common_configs.AttributeMeta ) When("AttributeMeta is not nil", func() { BeforeEach(func() { copy = meta.DeepCopy() }) It("returns copy ", func() { Expect(copy).To(Equal(&meta)) }) }) When("AttributeMeta is nil", func() { BeforeEach(func() { copy = nilMeta.DeepCopy() }) It("returns copy ", func() { Expect(copy).To(BeNil()) }) }) }) }) }) golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/common_configs/doc.go000066400000000000000000000000651437707610400232320ustar00rootroot00000000000000package common_configs // +k8s:deepcopy-gen=package golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/common_configs/ginkgo_test.go000066400000000000000000000006421437707610400250030ustar00rootroot00000000000000package common_configs_test import ( "testing" "github.com/jarcoal/httpmock" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) func TestGinkgo(t *testing.T) { RegisterFailHandler(Fail) RunSpecs(t, "common_congigs package test suite") } var _ = BeforeSuite(func() { httpmock.Activate() }) var _ = BeforeEach(func() { httpmock.Reset() }) var _ = AfterSuite(func() { httpmock.DeactivateAndReset() }) golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/contracts/000077500000000000000000000000001437707610400211355ustar00rootroot00000000000000golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/contracts/ZZ_deepcopy_generated.go000066400000000000000000000314261437707610400257430ustar00rootroot00000000000000//go:build !ignore_autogenerated // +build !ignore_autogenerated /* MIT License Copyright (c) 2021 Manabu Sonoda 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. */ // Code generated by deepcopy-gen. DO NOT EDIT. package contracts import ( api "github.com/mimuret/golang-iij-dpf/pkg/api" core "github.com/mimuret/golang-iij-dpf/pkg/apis/dpf/v1/core" ) // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *AttributeMeta) DeepCopyInto(out *AttributeMeta) { *out = *in return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AttributeMeta. func (in *AttributeMeta) DeepCopy() *AttributeMeta { if in == nil { return nil } out := new(AttributeMeta) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *CommonConfig) DeepCopyInto(out *CommonConfig) { *out = *in out.AttributeMeta = in.AttributeMeta return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CommonConfig. func (in *CommonConfig) DeepCopy() *CommonConfig { if in == nil { return nil } out := new(CommonConfig) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new api.Object. func (in *CommonConfig) DeepCopyObject() api.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *CommonConfigDefault) DeepCopyInto(out *CommonConfigDefault) { *out = *in out.AttributeMeta = in.AttributeMeta return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CommonConfigDefault. func (in *CommonConfigDefault) DeepCopy() *CommonConfigDefault { if in == nil { return nil } out := new(CommonConfigDefault) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new api.Object. func (in *CommonConfigDefault) DeepCopyObject() api.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *CommonConfigList) DeepCopyInto(out *CommonConfigList) { *out = *in out.AttributeMeta = in.AttributeMeta out.Count = in.Count if in.Items != nil { in, out := &in.Items, &out.Items *out = make([]CommonConfig, len(*in)) copy(*out, *in) } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CommonConfigList. func (in *CommonConfigList) DeepCopy() *CommonConfigList { if in == nil { return nil } out := new(CommonConfigList) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new api.Object. func (in *CommonConfigList) DeepCopyObject() api.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *CommonConfigManagedDns) DeepCopyInto(out *CommonConfigManagedDns) { *out = *in out.AttributeMeta = in.AttributeMeta return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CommonConfigManagedDns. func (in *CommonConfigManagedDns) DeepCopy() *CommonConfigManagedDns { if in == nil { return nil } out := new(CommonConfigManagedDns) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new api.Object. func (in *CommonConfigManagedDns) DeepCopyObject() api.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ContractPartner) DeepCopyInto(out *ContractPartner) { *out = *in return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ContractPartner. func (in *ContractPartner) DeepCopy() *ContractPartner { if in == nil { return nil } out := new(ContractPartner) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ContractPartnerList) DeepCopyInto(out *ContractPartnerList) { *out = *in out.AttributeMeta = in.AttributeMeta if in.Items != nil { in, out := &in.Items, &out.Items *out = make([]ContractPartner, len(*in)) copy(*out, *in) } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ContractPartnerList. func (in *ContractPartnerList) DeepCopy() *ContractPartnerList { if in == nil { return nil } out := new(ContractPartnerList) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new api.Object. func (in *ContractPartnerList) DeepCopyObject() api.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ContractZoneCommonConfig) DeepCopyInto(out *ContractZoneCommonConfig) { *out = *in out.AttributeMeta = in.AttributeMeta if in.ZoneIDs != nil { in, out := &in.ZoneIDs, &out.ZoneIDs *out = make([]string, len(*in)) copy(*out, *in) } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ContractZoneCommonConfig. func (in *ContractZoneCommonConfig) DeepCopy() *ContractZoneCommonConfig { if in == nil { return nil } out := new(ContractZoneCommonConfig) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new api.Object. func (in *ContractZoneCommonConfig) DeepCopyObject() api.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ContractZoneList) DeepCopyInto(out *ContractZoneList) { *out = *in out.AttributeMeta = in.AttributeMeta out.Count = in.Count if in.Items != nil { in, out := &in.Items, &out.Items *out = make([]core.Zone, len(*in)) copy(*out, *in) } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ContractZoneList. func (in *ContractZoneList) DeepCopy() *ContractZoneList { if in == nil { return nil } out := new(ContractZoneList) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new api.Object. func (in *ContractZoneList) DeepCopyObject() api.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *LogList) DeepCopyInto(out *LogList) { *out = *in out.AttributeMeta = in.AttributeMeta out.Count = in.Count if in.Items != nil { in, out := &in.Items, &out.Items *out = make([]core.Log, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new LogList. func (in *LogList) DeepCopy() *LogList { if in == nil { return nil } out := new(LogList) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new api.Object. func (in *LogList) DeepCopyObject() api.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *QpsHistory) DeepCopyInto(out *QpsHistory) { *out = *in if in.Values != nil { in, out := &in.Values, &out.Values *out = make([]QpsValue, len(*in)) copy(*out, *in) } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new QpsHistory. func (in *QpsHistory) DeepCopy() *QpsHistory { if in == nil { return nil } out := new(QpsHistory) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *QpsHistoryList) DeepCopyInto(out *QpsHistoryList) { *out = *in out.AttributeMeta = in.AttributeMeta if in.Items != nil { in, out := &in.Items, &out.Items *out = make([]QpsHistory, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new QpsHistoryList. func (in *QpsHistoryList) DeepCopy() *QpsHistoryList { if in == nil { return nil } out := new(QpsHistoryList) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new api.Object. func (in *QpsHistoryList) DeepCopyObject() api.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *QpsValue) DeepCopyInto(out *QpsValue) { *out = *in return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new QpsValue. func (in *QpsValue) DeepCopy() *QpsValue { if in == nil { return nil } out := new(QpsValue) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Tsig) DeepCopyInto(out *Tsig) { *out = *in out.AttributeMeta = in.AttributeMeta return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Tsig. func (in *Tsig) DeepCopy() *Tsig { if in == nil { return nil } out := new(Tsig) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new api.Object. func (in *Tsig) DeepCopyObject() api.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *TsigCommonConfigList) DeepCopyInto(out *TsigCommonConfigList) { *out = *in out.AttributeMeta = in.AttributeMeta out.Count = in.Count if in.Items != nil { in, out := &in.Items, &out.Items *out = make([]CommonConfig, len(*in)) copy(*out, *in) } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new TsigCommonConfigList. func (in *TsigCommonConfigList) DeepCopy() *TsigCommonConfigList { if in == nil { return nil } out := new(TsigCommonConfigList) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new api.Object. func (in *TsigCommonConfigList) DeepCopyObject() api.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *TsigList) DeepCopyInto(out *TsigList) { *out = *in out.AttributeMeta = in.AttributeMeta out.Count = in.Count if in.Items != nil { in, out := &in.Items, &out.Items *out = make([]Tsig, len(*in)) copy(*out, *in) } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new TsigList. func (in *TsigList) DeepCopy() *TsigList { if in == nil { return nil } out := new(TsigList) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new api.Object. func (in *TsigList) DeepCopyObject() api.Object { if c := in.DeepCopy(); c != nil { return c } return nil } golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/contracts/common.go000066400000000000000000000032021437707610400227510ustar00rootroot00000000000000package contracts import ( "fmt" "net/http" "github.com/mimuret/golang-iij-dpf/pkg/api" "github.com/mimuret/golang-iij-dpf/pkg/apis" "github.com/mimuret/golang-iij-dpf/pkg/schema" ) const groupName = "contracts.api.dns-platform.jp/v1" func register(items ...apis.Spec) { schema.NewRegister(groupName).Add(items...) } type Spec interface { api.Spec apis.Params GetContractID() string SetContractID(string) } type ChildSpec interface { Spec GetID() int64 SetID(int64) } type ListSpec interface { api.ListSpec Spec } type CountableListSpec interface { api.CountableListSpec Spec } type AttributeMeta struct { ContractID string } func (s *AttributeMeta) GetGroup() string { return groupName } func (s *AttributeMeta) GetContractID() string { return s.ContractID } func (s *AttributeMeta) SetContractID(id string) { s.ContractID = id } func GetPathMethodForChildSpec(action api.Action, s ChildSpec) (string, string) { switch action { case api.ActionCreate: return action.ToMethod(), fmt.Sprintf("/contracts/%s/%s", s.GetContractID(), s.GetName()) case api.ActionRead, api.ActionUpdate, api.ActionDelete: return action.ToMethod(), fmt.Sprintf("/contracts/%s/%s/%d", s.GetContractID(), s.GetName(), s.GetID()) } return "", "" } func GetPathMethodForListSpec(action api.Action, s ListSpec) (string, string) { switch action { case api.ActionList: return http.MethodGet, fmt.Sprintf("/contracts/%s/%s", s.GetContractID(), s.GetName()) case api.ActionCount: if _, ok := s.(api.CountableListSpec); ok { return http.MethodGet, fmt.Sprintf("/contracts/%s/%s/count", s.GetContractID(), s.GetName()) } } return "", "" } golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/contracts/common_config.go000066400000000000000000000054271437707610400243110ustar00rootroot00000000000000package contracts import ( "net/url" "github.com/google/go-querystring/query" "github.com/mimuret/golang-iij-dpf/pkg/api" "github.com/mimuret/golang-iij-dpf/pkg/apis" "github.com/mimuret/golang-iij-dpf/pkg/types" ) var _ ChildSpec = &CommonConfig{} // +k8s:deepcopy-gen:interfaces=github.com/mimuret/golang-iij-dpf/pkg/api.Object type CommonConfig struct { AttributeMeta ID int64 `read:"id"` // patchable Name string `read:"name" create:"name" update:"name"` Description string `read:"description" create:"description" update:"description"` // not patchable ManagedDNSEnabled types.Boolean `read:"managed_dns_enabled"` Default types.Boolean `read:"default"` } func (c *CommonConfig) GetName() string { return "common_configs" } func (c *CommonConfig) GetID() int64 { return c.ID } func (c *CommonConfig) SetID(id int64) { c.ID = id } func (c *CommonConfig) GetPathMethod(action api.Action) (string, string) { return GetPathMethodForChildSpec(action, c) } func (c *CommonConfig) SetPathParams(args ...interface{}) error { return apis.SetPathParams(args, &c.ContractID, &c.ID) } var _ CountableListSpec = &CommonConfigList{} // +k8s:deepcopy-gen:interfaces=github.com/mimuret/golang-iij-dpf/pkg/api.Object type CommonConfigList struct { AttributeMeta api.Count Items []CommonConfig `read:"items"` } func (c *CommonConfigList) GetName() string { return "common_configs" } func (c *CommonConfigList) GetItems() interface{} { return &c.Items } func (c *CommonConfigList) Len() int { return len(c.Items) } func (c *CommonConfigList) Index(i int) interface{} { return c.Items[i] } func (c *CommonConfigList) GetMaxLimit() int32 { return 10000 } func (c *CommonConfigList) ClearItems() { c.Items = []CommonConfig{} } func (c *CommonConfigList) AddItem(v interface{}) bool { if a, ok := v.(CommonConfig); ok { c.Items = append(c.Items, a) return true } return false } func (c *CommonConfigList) GetPathMethod(action api.Action) (string, string) { return GetPathMethodForListSpec(action, c) } func (c *CommonConfigList) Init() { for i := range c.Items { c.Items[i].AttributeMeta = c.AttributeMeta } } func (c *CommonConfigList) SetPathParams(args ...interface{}) error { return apis.SetPathParams(args, &c.ContractID) } var _ api.SearchParams = &CommonConfigListSearchKeywords{} // +k8s:deepcopy-gen=false type CommonConfigListSearchKeywords struct { api.CommonSearchParams FullText api.KeywordsString `url:"_keywords_full_text[],omitempty"` Name api.KeywordsString `url:"_keywords_name[],omitempty"` Description api.KeywordsString `url:"_keywords_description[],omitempty"` } func (s *CommonConfigListSearchKeywords) GetValues() (url.Values, error) { return query.Values(s) } func init() { register(&CommonConfigList{}) } golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/contracts/common_config_default.go000066400000000000000000000016701437707610400260110ustar00rootroot00000000000000package contracts import ( "fmt" "github.com/mimuret/golang-iij-dpf/pkg/api" "github.com/mimuret/golang-iij-dpf/pkg/apis" ) var _ Spec = &CommonConfigDefault{} // +k8s:deepcopy-gen:interfaces=github.com/mimuret/golang-iij-dpf/pkg/api.Object type CommonConfigDefault struct { AttributeMeta ID int64 `apply:"common_config_id"` } func (c *CommonConfigDefault) GetName() string { return "common_configs/default" } func (c *CommonConfigDefault) GetID() int64 { return c.ID } func (c *CommonConfigDefault) SetID(id int64) { c.ID = id } func (c *CommonConfigDefault) GetPathMethod(action api.Action) (string, string) { if action == api.ActionApply { return action.ToMethod(), fmt.Sprintf("/contracts/%s/common_configs/default", c.GetContractID()) } return "", "" } func (c *CommonConfigDefault) SetPathParams(args ...interface{}) error { return apis.SetPathParams(args, &c.ContractID) } func init() { register(&CommonConfigDefault{}) } golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/contracts/common_config_default_test.go000066400000000000000000000061771437707610400270570ustar00rootroot00000000000000package contracts_test import ( "context" "net/http" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/jarcoal/httpmock" api "github.com/mimuret/golang-iij-dpf/pkg/api" "github.com/mimuret/golang-iij-dpf/pkg/apis/dpf/v1/contracts" "github.com/mimuret/golang-iij-dpf/pkg/testtool" ) var _ = Describe("common_configs/default", func() { var ( cl *testtool.TestClient err error reqId string s1 contracts.CommonConfigDefault ) BeforeEach(func() { cl = testtool.NewTestClient("", "http://localhost", nil) s1 = contracts.CommonConfigDefault{ AttributeMeta: contracts.AttributeMeta{ ContractID: "f1", }, ID: 10, } }) Describe("CommonConfigDefault", func() { Context("Apply", func() { id1, bs1 := testtool.CreateAsyncResponse() BeforeEach(func() { httpmock.RegisterResponder(http.MethodPatch, "http://localhost/contracts/f1/common_configs/default", httpmock.NewBytesResponder(202, bs1)) reqId, err = cl.Apply(context.Background(), &s1, nil) }) AfterEach(func() { httpmock.Reset() }) It("returns job_id", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal(id1)) }) It("sends json", func() { Expect(cl.RequestBody["/contracts/f1/common_configs/default"]).To(MatchJSON(`{ "common_config_id": 10 }`)) }) }) Context("SetPathParams", func() { When("no arguments, nothing to do", func() { BeforeEach(func() { err = s1.SetPathParams() }) It("returns error", func() { Expect(err).To(Succeed()) }) }) When("enough arguments", func() { BeforeEach(func() { err = s1.SetPathParams("f10") }) It("not returns error", func() { Expect(err).To(Succeed()) }) It("can set ContractID", func() { Expect(s1.GetContractID()).To(Equal("f10")) }) }) When("arguments has extra value", func() { BeforeEach(func() { err = s1.SetPathParams("f10", 1) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) When("arguments type missmatch (ContractID)", func() { BeforeEach(func() { err = s1.SetPathParams(2) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) }) Context("api.Spec common test", func() { var nilSpec *contracts.CommonConfigDefault testtool.TestDeepCopyObject(&s1, nilSpec) testtool.TestGetName(&s1, "common_configs/default") Context("GetPathMethod", func() { testtool.TestGetPathMethod(&s1, api.ActionApply, http.MethodPatch, "/contracts/f1/common_configs/default") When("action is ActionApply", func() { testtool.TestGetPathMethod(&s1, api.ActionApply, http.MethodPatch, "/contracts/f1/common_configs/default") }) When("action is other", func() { testtool.TestGetPathMethod(&s1, api.ActionRead, "", "") }) }) }) Context("contracts.ChildSpec common test", func() { Context("GetID", func() { It("returns Id", func() { Expect(s1.GetID()).To(Equal(s1.ID)) }) }) Context("SetID", func() { BeforeEach(func() { s1.SetID(2) }) It("can set Id", func() { Expect(s1.GetID()).To(Equal(int64(2))) }) }) }) }) }) golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/contracts/common_config_managed_dns.go000066400000000000000000000021371437707610400266240ustar00rootroot00000000000000package contracts import ( "fmt" "github.com/mimuret/golang-iij-dpf/pkg/api" "github.com/mimuret/golang-iij-dpf/pkg/apis" "github.com/mimuret/golang-iij-dpf/pkg/types" ) var _ Spec = &CommonConfigManagedDns{} // +k8s:deepcopy-gen:interfaces=github.com/mimuret/golang-iij-dpf/pkg/api.Object type CommonConfigManagedDns struct { AttributeMeta ID int64 ManagedDnsEnabled types.Boolean `apply:"managed_dns_enabled"` } func (c *CommonConfigManagedDns) GetName() string { return fmt.Sprintf("common_configs/%d/managed_dns", c.ID) } func (c *CommonConfigManagedDns) GetID() int64 { return c.ID } func (c *CommonConfigManagedDns) SetID(id int64) { c.ID = id } func (c *CommonConfigManagedDns) GetPathMethod(action api.Action) (string, string) { if action == api.ActionApply { return action.ToMethod(), fmt.Sprintf("/contracts/%s/common_configs/%d/managed_dns", c.GetContractID(), c.ID) } return "", "" } func (c *CommonConfigManagedDns) SetPathParams(args ...interface{}) error { return apis.SetPathParams(args, &c.ContractID, &c.ID) } func init() { register(&CommonConfigManagedDns{}) } golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/contracts/common_config_managed_dns_test.go000066400000000000000000000111231437707610400276560ustar00rootroot00000000000000package contracts_test import ( "context" "net/http" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/jarcoal/httpmock" "github.com/mimuret/golang-iij-dpf/pkg/api" "github.com/mimuret/golang-iij-dpf/pkg/apis/dpf/v1/contracts" "github.com/mimuret/golang-iij-dpf/pkg/testtool" "github.com/mimuret/golang-iij-dpf/pkg/types" ) var _ = Describe("common_configs/managed_dns", func() { var ( cl *testtool.TestClient err error reqId string s1, s2 contracts.CommonConfigManagedDns ) BeforeEach(func() { cl = testtool.NewTestClient("", "http://localhost", nil) s1 = contracts.CommonConfigManagedDns{ AttributeMeta: contracts.AttributeMeta{ ContractID: "f1", }, ID: 1, ManagedDnsEnabled: types.Enabled, } s2 = contracts.CommonConfigManagedDns{ AttributeMeta: contracts.AttributeMeta{ ContractID: "f1", }, ID: 2, ManagedDnsEnabled: types.Disabled, } }) Describe("CommonConfigManagedDns", func() { Context("Apply", func() { var ( id1, bs1 = testtool.CreateAsyncResponse() id2, bs2 = testtool.CreateAsyncResponse() ) BeforeEach(func() { httpmock.RegisterResponder(http.MethodPatch, "http://localhost/contracts/f1/common_configs/1/managed_dns", httpmock.NewBytesResponder(202, bs1)) httpmock.RegisterResponder(http.MethodPatch, "http://localhost/contracts/f1/common_configs/2/managed_dns", httpmock.NewBytesResponder(202, bs2)) }) AfterEach(func() { httpmock.Reset() }) When("enable", func() { BeforeEach(func() { reqId, err = cl.Apply(context.Background(), &s1, nil) }) It("returns job_id", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal(id1)) }) It("apply json", func() { Expect(cl.RequestBody["/contracts/f1/common_configs/1/managed_dns"]).To(MatchJSON(`{ "managed_dns_enabled": 1 }`)) }) }) When("disable", func() { BeforeEach(func() { reqId, err = cl.Apply(context.Background(), &s2, nil) }) It("returns job_id", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal(id2)) }) It("apply json", func() { Expect(cl.RequestBody["/contracts/f1/common_configs/2/managed_dns"]).To(MatchJSON(`{ "managed_dns_enabled": 0 }`)) }) }) }) Context("SetPathParams", func() { When("no arguments, nothing to do", func() { BeforeEach(func() { err = s1.SetPathParams() }) It("returns error", func() { Expect(err).To(Succeed()) }) }) When("enough arguments", func() { BeforeEach(func() { err = s1.SetPathParams("f10", 200) }) It("not returns error", func() { Expect(err).To(Succeed()) }) It("can set ContractId", func() { Expect(s1.GetContractID()).To(Equal("f10")) }) It("can set Id", func() { Expect(s1.GetID()).To(Equal(int64(200))) }) }) When("not enough arguments", func() { BeforeEach(func() { err = s1.SetPathParams("f10") }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) When("arguments has extra value", func() { BeforeEach(func() { err = s1.SetPathParams("f10", 1, 2) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) When("arguments type missmatch (ContractId)", func() { BeforeEach(func() { err = s1.SetPathParams(2, 1) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) When("arguments type missmatch (Id)", func() { BeforeEach(func() { err = s1.SetPathParams("id1", "1") }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) }) Context("api.Spec common test", func() { var nilSpec *contracts.CommonConfigManagedDns testtool.TestDeepCopyObject(&s1, nilSpec) testtool.TestGetName(&s1, "common_configs/1/managed_dns") Context("GetPathMethod", func() { testtool.TestGetPathMethod(&s1, api.ActionApply, http.MethodPatch, "/contracts/f1/common_configs/1/managed_dns") When("action is ActionApply", func() { testtool.TestGetPathMethod(&s1, api.ActionApply, http.MethodPatch, "/contracts/f1/common_configs/1/managed_dns") }) When("action is other", func() { testtool.TestGetPathMethod(&s1, api.ActionRead, "", "") }) }) }) Context("contracts.ChildSpec common test", func() { Context("GetID", func() { It("returns Id", func() { Expect(s1.GetID()).To(Equal(s1.ID)) }) }) Context("SetID", func() { BeforeEach(func() { s1.SetID(2) }) It("can set Id", func() { Expect(s1.GetID()).To(Equal(int64(2))) }) }) }) }) }) golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/contracts/common_config_test.go000066400000000000000000000261471437707610400253520ustar00rootroot00000000000000package contracts_test import ( "context" "net/http" "net/url" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/jarcoal/httpmock" "github.com/mimuret/golang-iij-dpf/pkg/api" "github.com/mimuret/golang-iij-dpf/pkg/apis/dpf/v1/contracts" "github.com/mimuret/golang-iij-dpf/pkg/testtool" "github.com/mimuret/golang-iij-dpf/pkg/types" ) var _ = Describe("common_configs", func() { var ( c contracts.CommonConfig cl *testtool.TestClient err error reqId string s1, s2 contracts.CommonConfig slist contracts.CommonConfigList ) BeforeEach(func() { cl = testtool.NewTestClient("", "http://localhost", nil) s1 = contracts.CommonConfig{ AttributeMeta: contracts.AttributeMeta{ ContractID: "f1", }, ID: 1, Name: "共通設定1", ManagedDNSEnabled: types.Enabled, Default: types.Enabled, Description: "common config 1", } s2 = contracts.CommonConfig{ AttributeMeta: contracts.AttributeMeta{ ContractID: "f1", }, ID: 2, Name: "共通設定2", ManagedDNSEnabled: types.Disabled, Default: types.Disabled, Description: "common config 2", } slist = contracts.CommonConfigList{ AttributeMeta: contracts.AttributeMeta{ ContractID: "f1", }, Items: []contracts.CommonConfig{s1, s2}, } }) Describe("CommonConfig", func() { Context("Read", func() { BeforeEach(func() { httpmock.RegisterResponder(http.MethodGet, "http://localhost/contracts/f1/common_configs/1", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "9901FF93F9BB430F921C4541BBF6882E", "result": { "id": 1, "name": "共通設定1", "managed_dns_enabled": 1, "default": 1, "description": "common config 1" } }`))) httpmock.RegisterResponder(http.MethodGet, "http://localhost/contracts/f1/common_configs/2", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "C8FEC177EF804512A40EF7FB358037C0", "result": { "id": 2, "name": "共通設定2", "managed_dns_enabled": 0, "default": 0, "description": "common config 2" } }`))) }) AfterEach(func() { httpmock.Reset() }) When("returns CommonConfig id1", func() { BeforeEach(func() { c = contracts.CommonConfig{ AttributeMeta: contracts.AttributeMeta{ ContractID: "f1", }, ID: 1, } reqId, err = cl.Read(context.Background(), &c) }) It("returns normal", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal("9901FF93F9BB430F921C4541BBF6882E")) Expect(c).To(Equal(s1)) }) }) When("returns CommonConfig id2", func() { BeforeEach(func() { c = contracts.CommonConfig{ AttributeMeta: contracts.AttributeMeta{ ContractID: "f1", }, ID: 2, } reqId, err = cl.Read(context.Background(), &c) }) It("returns normal", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal("C8FEC177EF804512A40EF7FB358037C0")) Expect(c).To(Equal(s2)) }) }) }) Context("Create", func() { id1, bs1 := testtool.CreateAsyncResponse() BeforeEach(func() { httpmock.RegisterResponder(http.MethodPost, "http://localhost/contracts/f2/common_configs", httpmock.NewBytesResponder(202, bs1)) s := contracts.CommonConfig{ AttributeMeta: contracts.AttributeMeta{ ContractID: "f2", }, Name: "create ðŸ»", Description: "ðŸºðŸ‡", } reqId, err = cl.Create(context.Background(), &s, nil) }) AfterEach(func() { httpmock.Reset() }) It("returns job_id", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal(id1)) }) It("post json", func() { Expect(cl.RequestBody["/contracts/f2/common_configs"]).To(MatchJSON(`{ "name": "create ðŸ»", "description": "ðŸºðŸ‡" }`)) }) }) Context("Update", func() { id1, bs1 := testtool.CreateAsyncResponse() BeforeEach(func() { httpmock.RegisterResponder(http.MethodPatch, "http://localhost/contracts/f1/common_configs/1", httpmock.NewBytesResponder(202, bs1)) reqId, err = cl.Update(context.Background(), &s1, nil) }) AfterEach(func() { httpmock.Reset() }) It("returns job_id", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal(id1)) }) It("post json", func() { Expect(cl.RequestBody["/contracts/f1/common_configs/1"]).To(MatchJSON(`{ "name": "共通設定1", "description": "common config 1" }`)) }) }) Context("Delete", func() { id1, bs1 := testtool.CreateAsyncResponse() BeforeEach(func() { httpmock.RegisterResponder(http.MethodDelete, "http://localhost/contracts/f1/common_configs/1", httpmock.NewBytesResponder(202, bs1)) reqId, err = cl.Delete(context.Background(), &s1) }) AfterEach(func() { httpmock.Reset() }) It("can deletel", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal(id1)) }) }) Context("SetPathParams", func() { When("no arguments, nothing to do", func() { BeforeEach(func() { err = s1.SetPathParams() }) It("returns error", func() { Expect(err).To(Succeed()) }) }) When("enough arguments", func() { BeforeEach(func() { err = s1.SetPathParams("f10", 200) }) It("not returns error", func() { Expect(err).To(Succeed()) }) It("can set ContractID", func() { Expect(s1.GetContractID()).To(Equal("f10")) }) It("can set Id", func() { Expect(s1.GetID()).To(Equal(int64(200))) }) }) When("not enough arguments", func() { BeforeEach(func() { err = s1.SetPathParams("f10") }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) When("arguments has extra value", func() { BeforeEach(func() { err = s1.SetPathParams("f10", 1, 2) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) When("arguments type missmatch (ContractID)", func() { BeforeEach(func() { err = s1.SetPathParams(2, 1) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) When("arguments type missmatch (Id)", func() { BeforeEach(func() { err = s1.SetPathParams("id1", "1") }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) }) Context("api.Spec common test", func() { var nilSpec *contracts.CommonConfig testtool.TestDeepCopyObject(&s1, nilSpec) testtool.TestGetName(&s1, "common_configs") testtool.TestGetPathMethodForSpec(&s1, "/contracts/f1/common_configs", "/contracts/f1/common_configs/1") }) Context("contracts.ChildSpec common test", func() { Context("GetID", func() { It("returns Id", func() { Expect(s1.GetID()).To(Equal(s1.ID)) }) }) Context("SetID", func() { BeforeEach(func() { s1.SetID(2) }) It("can set Id", func() { Expect(s1.GetID()).To(Equal(int64(2))) }) }) }) }) Describe("CommonConfigList", func() { var c contracts.CommonConfigList Context("List", func() { BeforeEach(func() { httpmock.RegisterResponder(http.MethodGet, "http://localhost/contracts/f1/common_configs", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "D1203ABF5C6E4A73AD1F184F5F2C1A6B", "results": [ { "id": 1, "name": "共通設定1", "managed_dns_enabled": 1, "default": 1, "description": "common config 1" }, { "id": 2, "name": "共通設定2", "managed_dns_enabled": 0, "default": 0, "description": "common config 2" } ] }`))) }) AfterEach(func() { httpmock.Reset() }) When("returns list ", func() { BeforeEach(func() { c = contracts.CommonConfigList{ AttributeMeta: contracts.AttributeMeta{ ContractID: "f1", }, } reqId, err = cl.List(context.Background(), &c, nil) }) It("returns normal", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal("D1203ABF5C6E4A73AD1F184F5F2C1A6B")) Expect(c).To(Equal(slist)) }) }) }) Context("SetPathParams", func() { When("no arguments, nothing to do", func() { BeforeEach(func() { err = slist.SetPathParams() }) It("returns error", func() { Expect(err).To(Succeed()) }) }) When("enough arguments", func() { BeforeEach(func() { err = slist.SetPathParams("id12") }) It("not returns error", func() { Expect(err).To(Succeed()) }) It("can set ContractID", func() { Expect(slist.GetContractID()).To(Equal("id12")) }) }) When("arguments has extra value", func() { BeforeEach(func() { err = slist.SetPathParams("f1", 2) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) When("arguments type missmatch (ContractID)", func() { BeforeEach(func() { err = slist.SetPathParams(2) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) }) Context("api.Spec common test", func() { var nilSpec *contracts.CommonConfigList testtool.TestDeepCopyObject(&slist, nilSpec) testtool.TestGetName(&slist, "common_configs") testtool.TestGetPathMethodForCountableList(&slist, "/contracts/f1/common_configs") }) Context("api.ListSpec common test", func() { testtool.TestGetItems(&slist, &slist.Items) testtool.TestLen(&slist, 2) Context("Index", func() { When("index exist", func() { It("returns item", func() { Expect(slist.Index(0)).To(Equal(s1)) }) }) }) }) Context("api.CountableListSpec common test", func() { testtool.TestGetMaxLimit(&slist, 10000) testtool.TestClearItems(&slist) testtool.TestAddItem(&slist, s1) }) }) Describe("CommonConfigListSearchKeywords", func() { Context("GetValues", func() { testcase := []struct { keyword contracts.CommonConfigListSearchKeywords values url.Values }{ { contracts.CommonConfigListSearchKeywords{ CommonSearchParams: api.CommonSearchParams{ Type: api.SearchTypeAND, Offset: int32(10), Limit: int32(100), }, }, url.Values{ "type": []string{"AND"}, "offset": []string{"10"}, "limit": []string{"100"}, }, }, { contracts.CommonConfigListSearchKeywords{ CommonSearchParams: api.CommonSearchParams{ Type: api.SearchTypeOR, Offset: int32(10), Limit: int32(100), }, FullText: api.KeywordsString{"hogehoge", "ðŸ°"}, Name: api.KeywordsString{"hogehogeã‚ðŸº"}, Description: api.KeywordsString{"ã‚ã‚ã‚", "ðŸº"}, }, url.Values{ "type": []string{"OR"}, "offset": []string{"10"}, "limit": []string{"100"}, "_keywords_full_text[]": []string{"hogehoge", "ðŸ°"}, "_keywords_name[]": []string{"hogehogeã‚ðŸº"}, "_keywords_description[]": []string{"ã‚ã‚ã‚", "ðŸº"}, }, }, } It("can convert url.Value", func() { for _, tc := range testcase { s, err := tc.keyword.GetValues() Expect(err).To(Succeed()) Expect(s).To(Equal(tc.values)) } }) }) }) }) golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/contracts/common_test.go000066400000000000000000000030111437707610400240060ustar00rootroot00000000000000package contracts_test import ( "github.com/mimuret/golang-iij-dpf/pkg/apis/dpf/v1/contracts" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("contracts", func() { Context("AttributeMeta", func() { var meta contracts.AttributeMeta BeforeEach(func() { meta = contracts.AttributeMeta{} }) Context("GetGroup", func() { It("returns contracts", func() { Expect(meta.GetGroup()).To(Equal("contracts.api.dns-platform.jp/v1")) }) }) Context("GetContractID", func() { When("default", func() { It("returns ", func() { Expect(meta.GetContractID()).To(Equal("")) }) }) When("default", func() { BeforeEach(func() { meta.ContractID = "id1" }) It("returns ContractID", func() { Expect(meta.GetContractID()).To(Equal("id1")) }) }) Context("SetContractID", func() { BeforeEach(func() { meta.SetContractID("id2") }) It("can set ContractID", func() { Expect(meta.GetContractID()).To(Equal("id2")) }) }) Context("DeepCopy", func() { var ( copy *contracts.AttributeMeta nilMeta *contracts.AttributeMeta ) When("AttributeMeta is not nil", func() { BeforeEach(func() { copy = meta.DeepCopy() }) It("returns copy ", func() { Expect(copy).To(Equal(&meta)) }) }) When("AttributeMeta is nil", func() { BeforeEach(func() { copy = nilMeta.DeepCopy() }) It("returns copy ", func() { Expect(copy).To(BeNil()) }) }) }) }) }) }) golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/contracts/contract_partner.go000066400000000000000000000020611437707610400250330ustar00rootroot00000000000000package contracts import ( "github.com/mimuret/golang-iij-dpf/pkg/api" "github.com/mimuret/golang-iij-dpf/pkg/apis" ) type ContractPartner struct { ServiceCode string `read:"service_code"` } var _ ListSpec = &ContractPartnerList{} // +k8s:deepcopy-gen:interfaces=github.com/mimuret/golang-iij-dpf/pkg/api.Object type ContractPartnerList struct { AttributeMeta Items []ContractPartner `read:"items"` } func (c *ContractPartnerList) GetName() string { return "contract_partners" } func (c *ContractPartnerList) GetItems() interface{} { return &c.Items } func (c *ContractPartnerList) Len() int { return len(c.Items) } func (c *ContractPartnerList) Index(i int) interface{} { return c.Items[i] } func (c *ContractPartnerList) GetPathMethod(action api.Action) (string, string) { return GetPathMethodForListSpec(action, c) } func (c *ContractPartnerList) SetPathParams(args ...interface{}) error { return apis.SetPathParams(args, &c.ContractID) } func (c *ContractPartnerList) Init() {} func init() { register(&ContractPartnerList{}) } golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/contracts/contract_partner_test.go000066400000000000000000000073211437707610400260760ustar00rootroot00000000000000package contracts_test import ( "context" "net/http" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/jarcoal/httpmock" "github.com/mimuret/golang-iij-dpf/pkg/apis/dpf/v1/contracts" "github.com/mimuret/golang-iij-dpf/pkg/testtool" ) var _ = Describe("contract_partners", func() { var ( cl *testtool.TestClient err error reqId string s1, s2 contracts.ContractPartner slist contracts.ContractPartnerList ) BeforeEach(func() { cl = testtool.NewTestClient("", "http://localhost", nil) s1 = contracts.ContractPartner{"svc001"} s2 = contracts.ContractPartner{"svc002"} slist = contracts.ContractPartnerList{ AttributeMeta: contracts.AttributeMeta{ ContractID: "f1", }, Items: []contracts.ContractPartner{s1, s2}, } }) Describe("ContractPartnerList", func() { var c contracts.ContractPartnerList Context("List", func() { BeforeEach(func() { httpmock.RegisterResponder(http.MethodGet, "http://localhost/contracts/f1/contract_partners", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "0EF26E92E5D54352A78C9EA4551BE502", "results": [ { "service_code": "svc001" }, { "service_code": "svc002" } ] }`))) }) AfterEach(func() { httpmock.Reset() }) When("returns list ", func() { BeforeEach(func() { c = contracts.ContractPartnerList{ AttributeMeta: contracts.AttributeMeta{ ContractID: "f1", }, } reqId, err = cl.List(context.Background(), &c, nil) }) It("returns normal", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal("0EF26E92E5D54352A78C9EA4551BE502")) Expect(c).To(Equal(slist)) }) }) }) Context("SetPathParams", func() { When("no arguments, nothing to do", func() { BeforeEach(func() { err = slist.SetPathParams() }) It("returns error", func() { Expect(err).To(Succeed()) }) }) When("enough arguments", func() { BeforeEach(func() { err = slist.SetPathParams("id12") }) It("not returns error", func() { Expect(err).To(Succeed()) }) It("can set ContractID", func() { Expect(slist.GetContractID()).To(Equal("id12")) }) }) When("arguments has extra value", func() { BeforeEach(func() { err = slist.SetPathParams("f1", 2) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) When("arguments type missmatch (ContractID)", func() { BeforeEach(func() { err = slist.SetPathParams(2) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) }) Context("api.Spec common test", func() { var nilSpec *contracts.ContractPartnerList testtool.TestDeepCopyObject(&slist, nilSpec) testtool.TestGetName(&slist, "contract_partners") testtool.TestGetPathMethodForList(&slist, "/contracts/f1/contract_partners") }) Context("api.ListSpec common test", func() { testtool.TestGetItems(&slist, &slist.Items) testtool.TestLen(&slist, 2) Context("Index", func() { When("index exist", func() { It("returns item", func() { Expect(slist.Index(0)).To(Equal(s1)) }) }) }) }) }) Describe("ContractPartner", func() { var s, copy, nilSpec *contracts.ContractPartner BeforeEach(func() { s = &contracts.ContractPartner{} }) Context("DeepCopyObject", func() { When("object is not nil", func() { BeforeEach(func() { copy = s.DeepCopy() }) It("returns copy", func() { Expect(copy).NotTo(BeNil()) Expect(copy).To(Equal(s)) }) }) When("object is not nil", func() { BeforeEach(func() { copy = nilSpec.DeepCopy() }) It("returns nil", func() { Expect(copy).To(BeNil()) }) }) }) }) }) golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/contracts/contract_zone.go000066400000000000000000000024631437707610400243410ustar00rootroot00000000000000package contracts import ( "github.com/mimuret/golang-iij-dpf/pkg/api" "github.com/mimuret/golang-iij-dpf/pkg/apis" "github.com/mimuret/golang-iij-dpf/pkg/apis/dpf/v1/core" ) var _ CountableListSpec = &ContractZoneList{} // +k8s:deepcopy-gen:interfaces=github.com/mimuret/golang-iij-dpf/pkg/api.Object type ContractZoneList struct { AttributeMeta api.Count Items []core.Zone `read:"items"` } func (c *ContractZoneList) GetName() string { return "zones" } func (c *ContractZoneList) GetItems() interface{} { return &c.Items } func (c *ContractZoneList) Len() int { return len(c.Items) } func (c *ContractZoneList) Index(i int) interface{} { return c.Items[i] } func (c *ContractZoneList) GetMaxLimit() int32 { return 10000 } func (c *ContractZoneList) ClearItems() { c.Items = []core.Zone{} } func (c *ContractZoneList) AddItem(v interface{}) bool { if a, ok := v.(core.Zone); ok { c.Items = append(c.Items, a) return true } return false } func (c *ContractZoneList) GetPathMethod(action api.Action) (string, string) { return GetPathMethodForListSpec(action, c) } func (c *ContractZoneList) SetPathParams(args ...interface{}) error { return apis.SetPathParams(args, &c.ContractID) } func (c *ContractZoneList) Init() {} func init() { register(&ContractZoneList{}) } golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/contracts/contract_zone_common_config.go000066400000000000000000000016211437707610400272310ustar00rootroot00000000000000package contracts import ( "fmt" "github.com/mimuret/golang-iij-dpf/pkg/api" "github.com/mimuret/golang-iij-dpf/pkg/apis" ) var _ Spec = &ContractZoneCommonConfig{} // +k8s:deepcopy-gen:interfaces=github.com/mimuret/golang-iij-dpf/pkg/api.Object type ContractZoneCommonConfig struct { AttributeMeta CommonConfigID int64 `apply:"common_config_id"` ZoneIDs []string `apply:"zone_ids"` } func (c *ContractZoneCommonConfig) GetName() string { return "zones/common_configs" } func (c *ContractZoneCommonConfig) GetPathMethod(action api.Action) (string, string) { if action == api.ActionApply { return action.ToMethod(), fmt.Sprintf("/contracts/%s/zones/common_configs", c.GetContractID()) } return "", "" } func (c *ContractZoneCommonConfig) SetPathParams(args ...interface{}) error { return apis.SetPathParams(args, &c.ContractID) } func init() { register(&ContractZoneCommonConfig{}) } golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/contracts/contract_zone_common_config_test.go000066400000000000000000000056321437707610400302760ustar00rootroot00000000000000package contracts_test import ( "context" "net/http" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/jarcoal/httpmock" "github.com/mimuret/golang-iij-dpf/pkg/api" "github.com/mimuret/golang-iij-dpf/pkg/apis/dpf/v1/contracts" "github.com/mimuret/golang-iij-dpf/pkg/testtool" ) var _ = Describe("zones/common_configs", func() { var ( cl *testtool.TestClient err error reqId string s1 contracts.ContractZoneCommonConfig ) BeforeEach(func() { cl = testtool.NewTestClient("", "http://localhost", nil) s1 = contracts.ContractZoneCommonConfig{ AttributeMeta: contracts.AttributeMeta{ ContractID: "f1", }, CommonConfigID: 10, ZoneIDs: []string{ "m1", "m2", }, } }) Describe("CommonConfigDefault", func() { Context("Apply", func() { id1, bs1 := testtool.CreateAsyncResponse() BeforeEach(func() { httpmock.RegisterResponder(http.MethodPatch, "http://localhost/contracts/f1/zones/common_configs", httpmock.NewBytesResponder(202, bs1)) reqId, err = cl.Apply(context.Background(), &s1, nil) }) AfterEach(func() { httpmock.Reset() }) It("returns job_id", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal(id1)) }) It("sends json", func() { Expect(cl.RequestBody["/contracts/f1/zones/common_configs"]).To(MatchJSON(`{ "common_config_id": 10, "zone_ids": ["m1","m2"] }`)) }) }) Context("GetName", func() { It("returns name", func() { Expect(s1.GetName()).To(Equal("zones/common_configs")) }) }) Context("SetPathParams", func() { When("no arguments, nothing to do", func() { BeforeEach(func() { err = s1.SetPathParams() }) It("returns error", func() { Expect(err).To(Succeed()) }) }) When("enough arguments", func() { BeforeEach(func() { err = s1.SetPathParams("f10") }) It("not returns error", func() { Expect(err).To(Succeed()) }) It("can set ContractID", func() { Expect(s1.GetContractID()).To(Equal("f10")) }) }) When("arguments has extra value", func() { BeforeEach(func() { err = s1.SetPathParams("f10", 1) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) When("arguments type missmatch (ContractID)", func() { BeforeEach(func() { err = s1.SetPathParams(2) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) }) Context("api.Spec common test", func() { var nilSpec *contracts.ContractZoneCommonConfig testtool.TestDeepCopyObject(&s1, nilSpec) testtool.TestGetName(&s1, "zones/common_configs") Context("GetPathMethod", func() { When("action is ActionApply", func() { testtool.TestGetPathMethod(&s1, api.ActionApply, http.MethodPatch, "/contracts/f1/zones/common_configs") }) When("action is Other", func() { testtool.TestGetPathMethod(&s1, api.ActionCancel, "", "") }) }) }) }) }) golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/contracts/contract_zone_test.go000066400000000000000000000105501437707610400253740ustar00rootroot00000000000000package contracts_test import ( "context" "net/http" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/jarcoal/httpmock" "github.com/mimuret/golang-iij-dpf/pkg/apis/dpf/v1/contracts" "github.com/mimuret/golang-iij-dpf/pkg/apis/dpf/v1/core" "github.com/mimuret/golang-iij-dpf/pkg/testtool" "github.com/mimuret/golang-iij-dpf/pkg/types" ) var _ = Describe("contract_zones", func() { var ( cl *testtool.TestClient err error reqId string s1, s2 core.Zone slist contracts.ContractZoneList ) BeforeEach(func() { cl = testtool.NewTestClient("", "http://localhost", nil) s1 = core.Zone{ ID: "m1", CommonConfigID: 1, ServiceCode: "dpm0000001", State: types.StateBeforeStart, Favorite: types.FavoriteHighPriority, Name: "example.jp.", Network: "", Description: "zone 1", ZoneProxyEnabled: types.Disabled, } s2 = core.Zone{ ID: "m2", CommonConfigID: 2, ServiceCode: "dpm0000002", State: types.StateRunning, Favorite: types.FavoriteLowPriority, Name: "168.192.in-addr.arpa.", Network: "192.168.0.0/16", Description: "zone 2", ZoneProxyEnabled: types.Enabled, } slist = contracts.ContractZoneList{ AttributeMeta: contracts.AttributeMeta{ ContractID: "f1", }, Items: []core.Zone{s1, s2}, } }) Describe("ContractZoneList", func() { var c contracts.ContractZoneList Context("List", func() { BeforeEach(func() { httpmock.RegisterResponder(http.MethodGet, "http://localhost/contracts/f1/zones", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "E8FCA53D138A4AAD8DCED5514A5AF7CB", "results": [ { "id": "m1", "common_config_id": 1, "service_code": "dpm0000001", "state": 1, "favorite": 1, "name": "example.jp.", "network": "", "description": "zone 1", "zone_proxy_enabled": 0 }, { "id": "m2", "common_config_id": 2, "service_code": "dpm0000002", "state": 2, "favorite":2, "name": "168.192.in-addr.arpa.", "network": "192.168.0.0/16", "description": "zone 2", "zone_proxy_enabled": 1 } ] }`))) }) AfterEach(func() { httpmock.Reset() }) When("returns list ", func() { BeforeEach(func() { c = contracts.ContractZoneList{ AttributeMeta: contracts.AttributeMeta{ ContractID: "f1", }, } reqId, err = cl.List(context.Background(), &c, nil) }) It("returns normal", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal("E8FCA53D138A4AAD8DCED5514A5AF7CB")) Expect(c).To(Equal(slist)) }) }) }) Context("SetPathParams", func() { When("no arguments, nothing to do", func() { BeforeEach(func() { err = slist.SetPathParams() }) It("returns error", func() { Expect(err).To(Succeed()) }) }) When("enough arguments", func() { BeforeEach(func() { err = slist.SetPathParams("id12") }) It("not returns error", func() { Expect(err).To(Succeed()) }) It("can set ContractID", func() { Expect(slist.GetContractID()).To(Equal("id12")) }) }) When("arguments has extra value", func() { BeforeEach(func() { err = slist.SetPathParams("f1", 2) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) When("arguments type missmatch (ContractID)", func() { BeforeEach(func() { err = slist.SetPathParams(2) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) }) Context("api.Spec common test", func() { var nilSpec *contracts.ContractZoneList testtool.TestDeepCopyObject(&slist, nilSpec) testtool.TestGetName(&slist, "zones") testtool.TestGetPathMethodForCountableList(&slist, "/contracts/f1/zones") }) Context("api.ListSpec common test", func() { testtool.TestGetItems(&slist, &slist.Items) testtool.TestLen(&slist, 2) Context("Index", func() { When("index exist", func() { It("returns item", func() { Expect(slist.Index(0)).To(Equal(s1)) }) }) }) }) Context("api.CountableListSpec common test", func() { testtool.TestGetMaxLimit(&slist, 10000) testtool.TestClearItems(&slist) testtool.TestAddItem(&slist, s1) }) }) }) golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/contracts/doc.go000066400000000000000000000000601437707610400222250ustar00rootroot00000000000000package contracts // +k8s:deepcopy-gen=package golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/contracts/ginkgo_test.go000066400000000000000000000006301437707610400240000ustar00rootroot00000000000000package contracts_test import ( "testing" "github.com/jarcoal/httpmock" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) func TestGinkgo(t *testing.T) { RegisterFailHandler(Fail) RunSpecs(t, "contracts package test suite") } var _ = BeforeSuite(func() { httpmock.Activate() }) var _ = BeforeEach(func() { httpmock.Reset() }) var _ = AfterSuite(func() { httpmock.DeactivateAndReset() }) golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/contracts/log.go000066400000000000000000000022751437707610400222530ustar00rootroot00000000000000package contracts import ( "github.com/mimuret/golang-iij-dpf/pkg/api" "github.com/mimuret/golang-iij-dpf/pkg/apis" core "github.com/mimuret/golang-iij-dpf/pkg/apis/dpf/v1/core" ) // +k8s:deepcopy-gen:interfaces=github.com/mimuret/golang-iij-dpf/pkg/api.Object type LogList struct { AttributeMeta api.Count Items []core.Log `read:"items"` } var _ CountableListSpec = &LogList{} func (c *LogList) GetName() string { return "logs" } func (c *LogList) GetItems() interface{} { return &c.Items } func (c *LogList) Len() int { return len(c.Items) } func (c *LogList) Index(i int) interface{} { return c.Items[i] } func (c *LogList) GetMaxLimit() int32 { return 100 } func (c *LogList) ClearItems() { c.Items = []core.Log{} } func (c *LogList) AddItem(v interface{}) bool { if a, ok := v.(core.Log); ok { c.Items = append(c.Items, a) return true } return false } func (c *LogList) GetPathMethod(action api.Action) (string, string) { return GetPathMethodForListSpec(action, c) } func (c *LogList) SetPathParams(args ...interface{}) error { return apis.SetPathParams(args, &c.ContractID) } func (c *LogList) Init() {} func init() { register(&LogList{}) } golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/contracts/log_test.go000066400000000000000000000103341437707610400233050ustar00rootroot00000000000000package contracts_test import ( "context" "net/http" "time" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/jarcoal/httpmock" "github.com/mimuret/golang-iij-dpf/pkg/apis/dpf/v1/contracts" core "github.com/mimuret/golang-iij-dpf/pkg/apis/dpf/v1/core" "github.com/mimuret/golang-iij-dpf/pkg/testtool" "github.com/mimuret/golang-iij-dpf/pkg/types" ) var _ = Describe("logs", func() { var ( cl *testtool.TestClient err error reqId string s1, s2 core.Log atTime types.Time slist contracts.LogList ) BeforeEach(func() { atTime, err = types.ParseTime(time.RFC3339Nano, "2021-06-20T07:55:17.753Z") Expect(err).To((Succeed())) cl = testtool.NewTestClient("", "http://localhost", nil) s1 = core.Log{ Time: atTime, LogType: "service", Operator: "user1", Operation: "add_cc_primary", Target: "1", Status: core.LogStatusStart, } s2 = core.Log{ Time: atTime, LogType: "common_config", Operator: "user2", Operation: "create_tsig", Target: "2", Status: core.LogStatusSuccess, } slist = contracts.LogList{ AttributeMeta: contracts.AttributeMeta{ ContractID: "f1", }, Items: []core.Log{s1, s2}, } }) Describe("LogList", func() { var c contracts.LogList Context("List", func() { BeforeEach(func() { httpmock.RegisterResponder(http.MethodGet, "http://localhost/contracts/f1/logs", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "8026628BA5AD4ECA93F8506972DD50A7", "results": [ { "time": "2021-06-20T07:55:17.753Z", "log_type": "service", "operator": "user1", "operation": "add_cc_primary", "target": "1", "status": "start" }, { "time": "2021-06-20T07:55:17.753Z", "log_type": "common_config", "operator": "user2", "operation": "create_tsig", "target": "2", "status": "success" } ] }`))) httpmock.RegisterResponder(http.MethodGet, "http://localhost/contracts/f1/logs/count", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "8026628BA5AD4ECA93F8506972DD50A7", "result": { "count": 2 } }`))) }) AfterEach(func() { httpmock.Reset() }) When("returns list ", func() { BeforeEach(func() { c = contracts.LogList{ AttributeMeta: contracts.AttributeMeta{ ContractID: "f1", }, } reqId, err = cl.List(context.Background(), &c, nil) }) It("returns normal", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal("8026628BA5AD4ECA93F8506972DD50A7")) Expect(c).To(Equal(slist)) }) }) }) Context("SetPathParams", func() { When("no arguments, nothing to do", func() { BeforeEach(func() { err = slist.SetPathParams() }) It("returns error", func() { Expect(err).To(Succeed()) }) }) When("enough arguments", func() { BeforeEach(func() { err = slist.SetPathParams("id12") }) It("not returns error", func() { Expect(err).To(Succeed()) }) It("can set ContractID", func() { Expect(slist.GetContractID()).To(Equal("id12")) }) }) When("arguments has extra value", func() { BeforeEach(func() { err = slist.SetPathParams("f1", 2) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) When("arguments type missmatch (ContractID)", func() { BeforeEach(func() { err = slist.SetPathParams(2) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) }) Context("api.Spec common test", func() { var nilSpec *contracts.LogList testtool.TestDeepCopyObject(&slist, nilSpec) testtool.TestGetName(&slist, "logs") testtool.TestGetPathMethodForCountableList(&slist, "/contracts/f1/logs") }) Context("api.ListSpec common test", func() { testtool.TestGetItems(&slist, &slist.Items) testtool.TestLen(&slist, 2) Context("Index", func() { When("index exist", func() { It("returns item", func() { Expect(slist.Index(0)).To(Equal(s1)) }) }) }) }) Context("api.CountableListSpec common test", func() { testtool.TestGetMaxLimit(&slist, 100) testtool.TestClearItems(&slist) testtool.TestAddItem(&slist, s1) }) }) }) golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/contracts/qps_history.go000066400000000000000000000022761437707610400240570ustar00rootroot00000000000000package contracts import ( "github.com/mimuret/golang-iij-dpf/pkg/api" "github.com/mimuret/golang-iij-dpf/pkg/apis" ) type QpsValue struct { Month string `read:"month"` Qps int `read:"qps"` } type QpsHistory struct { ServiceCode string `read:"service_code"` Name string `read:"name"` Values []QpsValue `read:"values"` } // +k8s:deepcopy-gen:interfaces=github.com/mimuret/golang-iij-dpf/pkg/api.Object type QpsHistoryList struct { AttributeMeta Items []QpsHistory `read:"items"` } var _ ListSpec = &QpsHistoryList{} func (c *QpsHistoryList) GetName() string { return "qps/histories" } func (c *QpsHistoryList) GetItems() interface{} { return &c.Items } func (c *QpsHistoryList) Len() int { return len(c.Items) } func (c *QpsHistoryList) Index(i int) interface{} { return c.Items[i] } // /contracts/{ContractID}/qps/histories func (c *QpsHistoryList) GetPathMethod(action api.Action) (string, string) { return GetPathMethodForListSpec(action, c) } func (c *QpsHistoryList) SetPathParams(args ...interface{}) error { return apis.SetPathParams(args, &c.ContractID) } func (c *QpsHistoryList) Init() {} func init() { register(&QpsHistoryList{}) } golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/contracts/qps_history_test.go000066400000000000000000000116361437707610400251160ustar00rootroot00000000000000package contracts_test import ( "context" "net/http" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/jarcoal/httpmock" "github.com/mimuret/golang-iij-dpf/pkg/apis/dpf/v1/contracts" "github.com/mimuret/golang-iij-dpf/pkg/testtool" ) var _ = Describe("qps_histories", func() { var ( cl *testtool.TestClient err error reqId string s1, s2 contracts.QpsHistory slist contracts.QpsHistoryList ) BeforeEach(func() { cl = testtool.NewTestClient("", "http://localhost", nil) s1 = contracts.QpsHistory{ ServiceCode: "f00001", Name: "hoge", Values: []contracts.QpsValue{ { Month: "2021-01", Qps: 100, }, { Month: "2021-02", Qps: 100, }, }, } s2 = contracts.QpsHistory{ ServiceCode: "f00002", Name: "hogehoge", Values: []contracts.QpsValue{ { Month: "2021-07", Qps: 20, }, { Month: "2021-09", Qps: 100, }, }, } slist = contracts.QpsHistoryList{ AttributeMeta: contracts.AttributeMeta{ ContractID: "f1", }, Items: []contracts.QpsHistory{s1, s2}, } }) Describe("QpsHistoryList", func() { var c contracts.QpsHistoryList Context("List", func() { BeforeEach(func() { httpmock.RegisterResponder(http.MethodGet, "http://localhost/contracts/f1/qps/histories", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "3649092EAD70427A854CE933973AFFF8", "results": [ { "service_code": "f00001", "name": "hoge", "values": [ { "month": "2021-01", "qps": 100 }, { "month": "2021-02", "qps": 100 } ] }, { "service_code": "f00002", "name": "hogehoge", "values": [ { "month": "2021-07", "qps": 20 }, { "month": "2021-09", "qps": 100 } ] } ] }`))) }) AfterEach(func() { httpmock.Reset() }) When("returns list ", func() { BeforeEach(func() { c = contracts.QpsHistoryList{ AttributeMeta: contracts.AttributeMeta{ ContractID: "f1", }, } reqId, err = cl.List(context.Background(), &c, nil) }) It("returns normal", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal("3649092EAD70427A854CE933973AFFF8")) Expect(c).To(Equal(slist)) }) }) }) Context("SetPathParams", func() { When("no arguments, nothing to do", func() { BeforeEach(func() { err = slist.SetPathParams() }) It("returns error", func() { Expect(err).To(Succeed()) }) }) When("enough arguments", func() { BeforeEach(func() { err = slist.SetPathParams("id12") }) It("not returns error", func() { Expect(err).To(Succeed()) }) It("can set ContractID", func() { Expect(slist.GetContractID()).To(Equal("id12")) }) }) When("arguments has extra value", func() { BeforeEach(func() { err = slist.SetPathParams("f1", 2) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) When("arguments type missmatch (ContractID)", func() { BeforeEach(func() { err = slist.SetPathParams(2) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) }) Context("api.Spec common test", func() { var nilSpec *contracts.QpsHistoryList testtool.TestDeepCopyObject(&slist, nilSpec) testtool.TestGetName(&slist, "qps/histories") testtool.TestGetPathMethodForList(&slist, "/contracts/f1/qps/histories") }) Context("api.ListSpec common test", func() { testtool.TestGetItems(&slist, &slist.Items) testtool.TestLen(&slist, 2) Context("Index", func() { When("index exist", func() { It("returns item", func() { Expect(slist.Index(0)).To(Equal(s1)) }) }) }) }) }) Describe("QpsHistory", func() { var s, copy, nilSpec *contracts.QpsHistory BeforeEach(func() { s = &contracts.QpsHistory{} }) Context("DeepCopyt", func() { When("object is not nil", func() { BeforeEach(func() { copy = s.DeepCopy() }) It("returns copy", func() { Expect(copy).NotTo(BeNil()) Expect(copy).To(Equal(s)) }) }) When("object is not nil", func() { BeforeEach(func() { copy = nilSpec.DeepCopy() }) It("returns nil", func() { Expect(copy).To(BeNil()) }) }) }) }) Describe("QpsValue", func() { var s, copy, nilSpec *contracts.QpsValue BeforeEach(func() { s = &contracts.QpsValue{} }) Context("DeepCopy", func() { When("object is not nil", func() { BeforeEach(func() { copy = s.DeepCopy() }) It("returns copy", func() { Expect(copy).NotTo(BeNil()) Expect(copy).To(Equal(s)) }) }) When("object is not nil", func() { BeforeEach(func() { copy = nilSpec.DeepCopy() }) It("returns nil", func() { Expect(copy).To(BeNil()) }) }) }) }) }) golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/contracts/tsig.go000066400000000000000000000053321437707610400224350ustar00rootroot00000000000000package contracts import ( "net/url" "github.com/google/go-querystring/query" "github.com/mimuret/golang-iij-dpf/pkg/api" "github.com/mimuret/golang-iij-dpf/pkg/apis" ) var _ ChildSpec = &Tsig{} type TsigAlgorithm int const ( TsigAlgorithmHMACSHA256 TsigAlgorithm = 0 ) func (c TsigAlgorithm) String() string { tsigAlgorithmToString := map[TsigAlgorithm]string{ TsigAlgorithmHMACSHA256: "HMAC-SHA256", } return tsigAlgorithmToString[c] } // +k8s:deepcopy-gen:interfaces=github.com/mimuret/golang-iij-dpf/pkg/api.Object type Tsig struct { AttributeMeta ID int64 `read:"id"` Name string `read:"name" create:"name"` Algorithm TsigAlgorithm `read:"algorithm"` Secret string `read:"secret"` Description string `read:"description" create:"description" update:"description"` } func (c *Tsig) GetName() string { return "tsigs" } func (c *Tsig) GetID() int64 { return c.ID } func (c *Tsig) SetID(id int64) { c.ID = id } func (c *Tsig) GetPathMethod(action api.Action) (string, string) { return GetPathMethodForChildSpec(action, c) } func (c *Tsig) SetPathParams(args ...interface{}) error { return apis.SetPathParams(args, &c.ContractID, &c.ID) } var _ ListSpec = &TsigList{} // +k8s:deepcopy-gen:interfaces=github.com/mimuret/golang-iij-dpf/pkg/api.Object type TsigList struct { AttributeMeta api.Count Items []Tsig `read:"items"` } func (c *TsigList) GetName() string { return "tsigs" } func (c *TsigList) GetItems() interface{} { return &c.Items } func (c *TsigList) Len() int { return len(c.Items) } func (c *TsigList) Index(i int) interface{} { return c.Items[i] } func (c *TsigList) GetMaxLimit() int32 { return 10000 } func (c *TsigList) ClearItems() { c.Items = []Tsig{} } func (c *TsigList) AddItem(v interface{}) bool { if a, ok := v.(Tsig); ok { c.Items = append(c.Items, a) return true } return false } func (c *TsigList) GetPathMethod(action api.Action) (string, string) { return GetPathMethodForListSpec(action, c) } func (c *TsigList) Init() { for i := range c.Items { c.Items[i].AttributeMeta = c.AttributeMeta } } func (c *TsigList) SetPathParams(args ...interface{}) error { return apis.SetPathParams(args, &c.ContractID) } var _ api.SearchParams = &TsigListSearchKeywords{} // +k8s:deepcopy-gen=false type TsigListSearchKeywords struct { api.CommonSearchParams FullText api.KeywordsString `url:"_keywords_full_text[],omitempty"` Name api.KeywordsString `url:"_keywords_name[],omitempty"` Description api.KeywordsString `url:"_keywords_description[],omitempty"` } func (s *TsigListSearchKeywords) GetValues() (url.Values, error) { return query.Values(s) } func init() { register(&Tsig{}, &TsigList{}) } golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/contracts/tsig_common_config.go000066400000000000000000000030701437707610400253270ustar00rootroot00000000000000package contracts import ( "fmt" "github.com/mimuret/golang-iij-dpf/pkg/api" "github.com/mimuret/golang-iij-dpf/pkg/apis" ) var _ CountableListSpec = &TsigCommonConfigList{} // +k8s:deepcopy-gen:interfaces=github.com/mimuret/golang-iij-dpf/pkg/api.Object type TsigCommonConfigList struct { AttributeMeta api.Count ID int64 Items []CommonConfig `read:"items"` } func (c *TsigCommonConfigList) GetName() string { return fmt.Sprintf("tsigs/%d/common_configs", c.ID) } func (c *TsigCommonConfigList) GetID() int64 { return c.ID } func (c *TsigCommonConfigList) SetID(id int64) { c.ID = id } func (c *TsigCommonConfigList) GetItems() interface{} { return &c.Items } func (c *TsigCommonConfigList) Len() int { return len(c.Items) } func (c *TsigCommonConfigList) Index(i int) interface{} { return c.Items[i] } func (c *TsigCommonConfigList) GetMaxLimit() int32 { return 10000 } func (c *TsigCommonConfigList) ClearItems() { c.Items = []CommonConfig{} } func (c *TsigCommonConfigList) AddItem(v interface{}) bool { if a, ok := v.(CommonConfig); ok { c.Items = append(c.Items, a) return true } return false } func (c *TsigCommonConfigList) GetPathMethod(action api.Action) (string, string) { return GetPathMethodForListSpec(action, c) } func (c *TsigCommonConfigList) Init() { for i := range c.Items { c.Items[i].AttributeMeta = c.AttributeMeta } } func (c *TsigCommonConfigList) SetPathParams(args ...interface{}) error { return apis.SetPathParams(args, &c.ContractID, &c.ID) } func init() { register(&TsigCommonConfigList{}) } golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/contracts/tsig_common_config_test.go000066400000000000000000000122771437707610400263770ustar00rootroot00000000000000package contracts_test import ( "context" "net/http" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/jarcoal/httpmock" "github.com/mimuret/golang-iij-dpf/pkg/apis/dpf/v1/contracts" "github.com/mimuret/golang-iij-dpf/pkg/testtool" "github.com/mimuret/golang-iij-dpf/pkg/types" ) var _ = Describe("tsigs/common_configs", func() { var ( c contracts.TsigCommonConfigList cl *testtool.TestClient err error reqId string s1, s2 contracts.CommonConfig slist contracts.TsigCommonConfigList ) BeforeEach(func() { cl = testtool.NewTestClient("", "http://localhost", nil) s1 = contracts.CommonConfig{ AttributeMeta: contracts.AttributeMeta{ ContractID: "f1", }, ID: 1, Name: "共通設定1", ManagedDNSEnabled: types.Enabled, Default: types.Enabled, Description: "common config 1", } s2 = contracts.CommonConfig{ AttributeMeta: contracts.AttributeMeta{ ContractID: "f1", }, ID: 2, Name: "共通設定2", ManagedDNSEnabled: types.Disabled, Default: types.Disabled, Description: "common config 2", } slist = contracts.TsigCommonConfigList{ AttributeMeta: contracts.AttributeMeta{ ContractID: "f1", }, Items: []contracts.CommonConfig{s1, s2}, ID: 1, } }) Describe("TsigCommonConfigList", func() { Context("List", func() { BeforeEach(func() { httpmock.RegisterResponder(http.MethodGet, "http://localhost/contracts/f1/tsigs/1/common_configs", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "C38FBA61C657432695BC798DD96B0D9A", "results": [ { "id": 1, "name": "共通設定1", "managed_dns_enabled": 1, "default": 1, "description": "common config 1" }, { "id": 2, "name": "共通設定2", "managed_dns_enabled": 0, "default": 0, "description": "common config 2" } ] }`))) httpmock.RegisterResponder(http.MethodGet, "http://localhost/contracts/f1/tsigs/1/common_configs/count", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "1073C4F38C0A4027B4776F0F3E8197BB", "result": { "count": 2 } }`))) }) AfterEach(func() { httpmock.Reset() }) When("returns list ", func() { BeforeEach(func() { c = contracts.TsigCommonConfigList{ AttributeMeta: contracts.AttributeMeta{ ContractID: "f1", }, ID: 1, } reqId, err = cl.List(context.Background(), &c, nil) }) It("returns normal", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal("C38FBA61C657432695BC798DD96B0D9A")) Expect(c).To(Equal(slist)) }) }) }) Context("SetPathParams", func() { When("no arguments, nothing to do", func() { BeforeEach(func() { err = slist.SetPathParams() }) It("returns error", func() { Expect(err).To(Succeed()) }) }) When("enough arguments", func() { BeforeEach(func() { err = slist.SetPathParams("id12", 122) }) It("not returns error", func() { Expect(err).To(Succeed()) }) It("can set ContractID", func() { Expect(slist.GetContractID()).To(Equal("id12")) }) It("can set Id (tsig_id)", func() { Expect(slist.ID).To(Equal(int64(122))) }) }) When("not enough arguments", func() { BeforeEach(func() { err = slist.SetPathParams("id12") }) It("not returns error", func() { Expect(err).To(HaveOccurred()) }) }) When("arguments has extra value", func() { BeforeEach(func() { err = slist.SetPathParams("f1", 2, 3) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) When("arguments type missmatch (ContractID)", func() { BeforeEach(func() { err = slist.SetPathParams(2, 2) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) When("arguments type missmatch (Id)", func() { BeforeEach(func() { err = slist.SetPathParams("F1", "f2") }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) }) Context("api.Spec common test", func() { var nilSpec *contracts.TsigCommonConfigList testtool.TestDeepCopyObject(&slist, nilSpec) testtool.TestGetName(&slist, "tsigs/1/common_configs") testtool.TestGetPathMethodForCountableList(&slist, "/contracts/f1/tsigs/1/common_configs") }) Context("api.ListSpec common test", func() { testtool.TestGetItems(&slist, &slist.Items) testtool.TestLen(&slist, 2) Context("Index", func() { When("index exist", func() { It("returns item", func() { Expect(slist.Index(0)).To(Equal(s1)) }) }) }) }) Context("api.CountableListSpec common test", func() { testtool.TestGetMaxLimit(&slist, 10000) testtool.TestClearItems(&slist) testtool.TestAddItem(&slist, s1) }) Context("contracts.ChildSpec common test", func() { Context("GetID", func() { It("returns Id", func() { Expect(slist.GetID()).To(Equal(slist.ID)) }) }) Context("SetID", func() { BeforeEach(func() { slist.SetID(2) }) It("can set Id", func() { Expect(slist.GetID()).To(Equal(int64(2))) }) }) }) }) }) golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/contracts/tsig_test.go000066400000000000000000000265671437707610400235110ustar00rootroot00000000000000package contracts_test import ( "context" "net/http" "net/url" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/jarcoal/httpmock" "github.com/mimuret/golang-iij-dpf/pkg/api" "github.com/mimuret/golang-iij-dpf/pkg/apis/dpf/v1/contracts" "github.com/mimuret/golang-iij-dpf/pkg/testtool" ) var _ = Describe("tsigs", func() { var ( c contracts.Tsig cl *testtool.TestClient err error reqId string s1, s2 contracts.Tsig slist contracts.TsigList ) BeforeEach(func() { cl = testtool.NewTestClient("", "http://localhost", nil) s1 = contracts.Tsig{ AttributeMeta: contracts.AttributeMeta{ ContractID: "f1", }, ID: 1, Name: "hogehoge1", Algorithm: contracts.TsigAlgorithmHMACSHA256, Secret: "PDeNDXwzjh0OKbQLaVIZIQe6QR8La1uvfPiCCm3HL8Y=", Description: "tsig 1", } s2 = contracts.Tsig{ AttributeMeta: contracts.AttributeMeta{ ContractID: "f1", }, ID: 2, Name: "hogehoge2", Algorithm: contracts.TsigAlgorithmHMACSHA256, Secret: "dplF06cJHAiSdZoe0IldzfF5FYq7U5+INTmb/esvXSo=", Description: "tsig 2", } slist = contracts.TsigList{ AttributeMeta: contracts.AttributeMeta{ ContractID: "f1", }, Items: []contracts.Tsig{s1, s2}, } }) Describe("Tsig", func() { Context("Read", func() { BeforeEach(func() { httpmock.RegisterResponder(http.MethodGet, "http://localhost/contracts/f1/tsigs/1", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "96043C4DF2EE4EEF9094FF566F87505A", "result": { "id": 1, "name": "hogehoge1", "algorithm": 0, "secret": "PDeNDXwzjh0OKbQLaVIZIQe6QR8La1uvfPiCCm3HL8Y=", "description": "tsig 1" } }`))) httpmock.RegisterResponder(http.MethodGet, "http://localhost/contracts/f1/tsigs/2", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "E16A52E5C5DD4EB7B4A60F99E8FACE95", "result": { "id": 2, "name": "hogehoge2", "algorithm": 0, "secret": "dplF06cJHAiSdZoe0IldzfF5FYq7U5+INTmb/esvXSo=", "description": "tsig 2" } }`))) }) AfterEach(func() { httpmock.Reset() }) When("returns Tsig id1", func() { BeforeEach(func() { c = contracts.Tsig{ AttributeMeta: contracts.AttributeMeta{ ContractID: "f1", }, ID: 1, } reqId, err = cl.Read(context.Background(), &c) }) It("returns normal", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal("96043C4DF2EE4EEF9094FF566F87505A")) Expect(c).To(Equal(s1)) }) }) When("returns Tsig id2", func() { BeforeEach(func() { c = contracts.Tsig{ AttributeMeta: contracts.AttributeMeta{ ContractID: "f1", }, ID: 2, } reqId, err = cl.Read(context.Background(), &c) }) It("returns normal", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal("E16A52E5C5DD4EB7B4A60F99E8FACE95")) Expect(c).To(Equal(s2)) }) }) }) Context("Create", func() { id1, bs1 := testtool.CreateAsyncResponse() BeforeEach(func() { httpmock.RegisterResponder(http.MethodPost, "http://localhost/contracts/f2/tsigs", httpmock.NewBytesResponder(202, bs1)) s := contracts.Tsig{ AttributeMeta: contracts.AttributeMeta{ ContractID: "f2", }, Name: "hoge-huga", Description: "ðŸºðŸ‡", } reqId, err = cl.Create(context.Background(), &s, nil) }) AfterEach(func() { httpmock.Reset() }) It("returns job_id", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal(id1)) }) It("post json", func() { Expect(cl.RequestBody["/contracts/f2/tsigs"]).To(MatchJSON(`{ "name": "hoge-huga", "description": "ðŸºðŸ‡" }`)) }) }) Context("Update", func() { id1, bs1 := testtool.CreateAsyncResponse() BeforeEach(func() { httpmock.RegisterResponder(http.MethodPatch, "http://localhost/contracts/f1/tsigs/1", httpmock.NewBytesResponder(202, bs1)) reqId, err = cl.Update(context.Background(), &s1, nil) }) AfterEach(func() { httpmock.Reset() }) It("returns job_id", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal(id1)) }) It("sends json", func() { Expect(cl.RequestBody["/contracts/f1/tsigs/1"]).To(MatchJSON(`{ "description": "tsig 1" }`)) }) }) Context("Delete", func() { id1, bs1 := testtool.CreateAsyncResponse() BeforeEach(func() { httpmock.RegisterResponder(http.MethodDelete, "http://localhost/contracts/f1/tsigs/1", httpmock.NewBytesResponder(202, bs1)) reqId, err = cl.Delete(context.Background(), &s1) }) AfterEach(func() { httpmock.Reset() }) It("can delete", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal(id1)) }) }) Context("SetPathParams", func() { When("no arguments, nothing to do", func() { BeforeEach(func() { err = s1.SetPathParams() }) It("returns error", func() { Expect(err).To(Succeed()) }) }) When("enough arguments", func() { BeforeEach(func() { err = s1.SetPathParams("f10", 200) }) It("not returns error", func() { Expect(err).To(Succeed()) }) It("can set ContractID", func() { Expect(s1.GetContractID()).To(Equal("f10")) }) It("can set Id", func() { Expect(s1.GetID()).To(Equal(int64(200))) }) }) When("not enough arguments", func() { BeforeEach(func() { err = s1.SetPathParams("f10") }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) When("arguments has extra value", func() { BeforeEach(func() { err = s1.SetPathParams("f10", 1, 2) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) When("arguments type missmatch (ContractID)", func() { BeforeEach(func() { err = s1.SetPathParams(2, 1) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) When("arguments type missmatch (Id)", func() { BeforeEach(func() { err = s1.SetPathParams("id1", "1") }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) }) Context("api.Spec common test", func() { var nilSpec *contracts.Tsig testtool.TestDeepCopyObject(&s1, nilSpec) testtool.TestGetName(&s1, "tsigs") testtool.TestGetPathMethodForSpec(&s1, "/contracts/f1/tsigs", "/contracts/f1/tsigs/1") }) Context("contracts.ChildSpec common test", func() { Context("GetID", func() { It("returns Id", func() { Expect(s1.GetID()).To(Equal(s1.ID)) }) }) Context("SetID", func() { BeforeEach(func() { s1.SetID(2) }) It("can set Id", func() { Expect(s1.GetID()).To(Equal(int64(2))) }) }) }) }) Describe("TsigList", func() { var c contracts.TsigList Context("List", func() { BeforeEach(func() { httpmock.RegisterResponder(http.MethodGet, "http://localhost/contracts/f1/tsigs", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "062ED092113E4509BE4E2E4EF6C6EB2B", "results": [ { "id": 1, "name": "hogehoge1", "algorithm": 0, "secret": "PDeNDXwzjh0OKbQLaVIZIQe6QR8La1uvfPiCCm3HL8Y=", "description": "tsig 1" }, { "id": 2, "name": "hogehoge2", "algorithm": 0, "secret": "dplF06cJHAiSdZoe0IldzfF5FYq7U5+INTmb/esvXSo=", "description": "tsig 2" } ] }`))) httpmock.RegisterResponder(http.MethodGet, "http://localhost/contracts/f1/tsigs/count", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "F60D8455D0C7456286565E4D28A35951", "result": { "count": 2 } }`))) }) AfterEach(func() { httpmock.Reset() }) When("returns list ", func() { BeforeEach(func() { c = contracts.TsigList{ AttributeMeta: contracts.AttributeMeta{ ContractID: "f1", }, } reqId, err = cl.List(context.Background(), &c, nil) }) It("returns normal", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal("062ED092113E4509BE4E2E4EF6C6EB2B")) Expect(c).To(Equal(slist)) }) }) }) Context("SetPathParams", func() { When("no arguments, nothing to do", func() { BeforeEach(func() { err = slist.SetPathParams() }) It("returns error", func() { Expect(err).To(Succeed()) }) }) When("enough arguments", func() { BeforeEach(func() { err = slist.SetPathParams("id12") }) It("not returns error", func() { Expect(err).To(Succeed()) }) It("can set ContractID", func() { Expect(slist.GetContractID()).To(Equal("id12")) }) }) When("arguments has extra value", func() { BeforeEach(func() { err = slist.SetPathParams("f1", 2) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) When("arguments type missmatch (ContractID)", func() { BeforeEach(func() { err = slist.SetPathParams(2) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) }) Context("api.Spec common test", func() { var nilSpec *contracts.TsigList testtool.TestDeepCopyObject(&slist, nilSpec) testtool.TestGetName(&slist, "tsigs") testtool.TestGetPathMethodForCountableList(&slist, "/contracts/f1/tsigs") }) Context("api.ListSpec common test", func() { testtool.TestGetItems(&slist, &slist.Items) testtool.TestLen(&slist, 2) Context("Index", func() { When("index exist", func() { It("returns item", func() { Expect(slist.Index(0)).To(Equal(s1)) }) }) }) }) Context("api.CountableListSpec common test", func() { testtool.TestGetMaxLimit(&slist, 10000) testtool.TestClearItems(&slist) testtool.TestAddItem(&slist, s1) }) }) Describe("TsigListSearchKeywords", func() { Context("GetValues", func() { testcase := []struct { keyword contracts.TsigListSearchKeywords values url.Values }{ { contracts.TsigListSearchKeywords{ CommonSearchParams: api.CommonSearchParams{ Type: api.SearchTypeAND, Offset: int32(10), Limit: int32(100), }, }, url.Values{ "type": []string{"AND"}, "offset": []string{"10"}, "limit": []string{"100"}, }, }, { contracts.TsigListSearchKeywords{ CommonSearchParams: api.CommonSearchParams{ Type: api.SearchTypeOR, Offset: int32(10), Limit: int32(100), }, FullText: api.KeywordsString{"hogehoge", "ðŸ°"}, Name: api.KeywordsString{"hogehogeã‚ðŸº"}, Description: api.KeywordsString{"ã‚ã‚ã‚", "ðŸº"}, }, url.Values{ "type": []string{"OR"}, "offset": []string{"10"}, "limit": []string{"100"}, "_keywords_full_text[]": []string{"hogehoge", "ðŸ°"}, "_keywords_name[]": []string{"hogehogeã‚ðŸº"}, "_keywords_description[]": []string{"ã‚ã‚ã‚", "ðŸº"}, }, }, } It("can convert url.Value", func() { for _, tc := range testcase { s, err := tc.keyword.GetValues() Expect(err).To(Succeed()) Expect(s).To(Equal(tc.values)) } }) }) }) Describe("TsigAlgorithm", func() { var a contracts.TsigAlgorithm Context("String", func() { When("TsigAlgorithmHMACSHA256", func() { BeforeEach(func() { a = contracts.TsigAlgorithmHMACSHA256 }) It("returns HMAC-SHA256", func() { Expect(a.String()).To(Equal("HMAC-SHA256")) }) }) }) }) }) golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/core/000077500000000000000000000000001437707610400200655ustar00rootroot00000000000000golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/core/ZZ_deepcopy_generated.go000066400000000000000000000230761437707610400246750ustar00rootroot00000000000000//go:build !ignore_autogenerated // +build !ignore_autogenerated /* MIT License Copyright (c) 2021 Manabu Sonoda 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. */ // Code generated by deepcopy-gen. DO NOT EDIT. package core import ( api "github.com/mimuret/golang-iij-dpf/pkg/api" ) // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *AttributeMeta) DeepCopyInto(out *AttributeMeta) { *out = *in return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AttributeMeta. func (in *AttributeMeta) DeepCopy() *AttributeMeta { if in == nil { return nil } out := new(AttributeMeta) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Contract) DeepCopyInto(out *Contract) { *out = *in out.AttributeMeta = in.AttributeMeta return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Contract. func (in *Contract) DeepCopy() *Contract { if in == nil { return nil } out := new(Contract) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new api.Object. func (in *Contract) DeepCopyObject() api.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ContractList) DeepCopyInto(out *ContractList) { *out = *in out.AttributeMeta = in.AttributeMeta out.Count = in.Count if in.Items != nil { in, out := &in.Items, &out.Items *out = make([]Contract, len(*in)) copy(*out, *in) } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ContractList. func (in *ContractList) DeepCopy() *ContractList { if in == nil { return nil } out := new(ContractList) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new api.Object. func (in *ContractList) DeepCopyObject() api.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Delegation) DeepCopyInto(out *Delegation) { *out = *in out.AttributeMeta = in.AttributeMeta in.DelegationRequestedAt.DeepCopyInto(&out.DelegationRequestedAt) return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Delegation. func (in *Delegation) DeepCopy() *Delegation { if in == nil { return nil } out := new(Delegation) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new api.Object. func (in *Delegation) DeepCopyObject() api.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *DelegationApply) DeepCopyInto(out *DelegationApply) { *out = *in out.AttributeMeta = in.AttributeMeta if in.ZoneIDs != nil { in, out := &in.ZoneIDs, &out.ZoneIDs *out = make([]string, len(*in)) copy(*out, *in) } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DelegationApply. func (in *DelegationApply) DeepCopy() *DelegationApply { if in == nil { return nil } out := new(DelegationApply) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new api.Object. func (in *DelegationApply) DeepCopyObject() api.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *DelegationList) DeepCopyInto(out *DelegationList) { *out = *in out.AttributeMeta = in.AttributeMeta out.Count = in.Count if in.Items != nil { in, out := &in.Items, &out.Items *out = make([]Delegation, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DelegationList. func (in *DelegationList) DeepCopy() *DelegationList { if in == nil { return nil } out := new(DelegationList) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new api.Object. func (in *DelegationList) DeepCopyObject() api.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Job) DeepCopyInto(out *Job) { *out = *in out.AttributeMeta = in.AttributeMeta return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Job. func (in *Job) DeepCopy() *Job { if in == nil { return nil } out := new(Job) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new api.Object. func (in *Job) DeepCopyObject() api.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *LBDomain) DeepCopyInto(out *LBDomain) { *out = *in out.AttributeMeta = in.AttributeMeta return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new LBDomain. func (in *LBDomain) DeepCopy() *LBDomain { if in == nil { return nil } out := new(LBDomain) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new api.Object. func (in *LBDomain) DeepCopyObject() api.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *LBDomainList) DeepCopyInto(out *LBDomainList) { *out = *in out.AttributeMeta = in.AttributeMeta out.Count = in.Count if in.Items != nil { in, out := &in.Items, &out.Items *out = make([]LBDomain, len(*in)) copy(*out, *in) } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new LBDomainList. func (in *LBDomainList) DeepCopy() *LBDomainList { if in == nil { return nil } out := new(LBDomainList) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new api.Object. func (in *LBDomainList) DeepCopyObject() api.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Log) DeepCopyInto(out *Log) { *out = *in in.Time.DeepCopyInto(&out.Time) return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Log. func (in *Log) DeepCopy() *Log { if in == nil { return nil } out := new(Log) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Zone) DeepCopyInto(out *Zone) { *out = *in out.AttributeMeta = in.AttributeMeta return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Zone. func (in *Zone) DeepCopy() *Zone { if in == nil { return nil } out := new(Zone) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new api.Object. func (in *Zone) DeepCopyObject() api.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ZoneList) DeepCopyInto(out *ZoneList) { *out = *in out.AttributeMeta = in.AttributeMeta out.Count = in.Count if in.Items != nil { in, out := &in.Items, &out.Items *out = make([]Zone, len(*in)) copy(*out, *in) } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ZoneList. func (in *ZoneList) DeepCopy() *ZoneList { if in == nil { return nil } out := new(ZoneList) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new api.Object. func (in *ZoneList) DeepCopyObject() api.Object { if c := in.DeepCopy(); c != nil { return c } return nil } golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/core/common.go000066400000000000000000000005311437707610400217030ustar00rootroot00000000000000package core import ( "github.com/mimuret/golang-iij-dpf/pkg/apis" "github.com/mimuret/golang-iij-dpf/pkg/schema" ) const groupName = "core.api.dns-platform.jp/v1" func register(items ...apis.Spec) { schema.NewRegister(groupName).Add(items...) } type AttributeMeta struct{} func (s *AttributeMeta) GetGroup() string { return groupName } golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/core/common_test.go000066400000000000000000000014421437707610400227440ustar00rootroot00000000000000package core_test import ( "github.com/mimuret/golang-iij-dpf/pkg/apis/dpf/v1/core" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("AttributeMeta", func() { a := core.AttributeMeta{} Context("GetGroup", func() { It("returns core", func() { Expect(a.GetGroup()).To(Equal("core.api.dns-platform.jp/v1")) }) }) Context("DeepCopy", func() { var ( copy *core.AttributeMeta nilMeta *core.AttributeMeta ) When("AttributeMeta is not nil", func() { BeforeEach(func() { copy = a.DeepCopy() }) It("returns copy ", func() { Expect(copy).To(Equal(&a)) }) }) When("AttributeMeta is nil", func() { BeforeEach(func() { copy = nilMeta.DeepCopy() }) It("returns copy ", func() { Expect(copy).To(BeNil()) }) }) }) }) golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/core/contract.go000066400000000000000000000064751437707610400222450ustar00rootroot00000000000000package core import ( "fmt" "net/url" "strconv" "github.com/google/go-querystring/query" "github.com/mimuret/golang-iij-dpf/pkg/api" "github.com/mimuret/golang-iij-dpf/pkg/apis" "github.com/mimuret/golang-iij-dpf/pkg/types" ) type Plan int const ( PlanBasic Plan = 1 PlanPremium Plan = 2 ) func (c Plan) String() string { planToString := map[Plan]string{ PlanBasic: "basic", PlanPremium: "premium", } return planToString[c] } // +k8s:deepcopy-gen=false type KeywordsPlan []Plan func (c KeywordsPlan) EncodeValues(key string, v *url.Values) error { for _, plan := range c { v.Add(key, strconv.Itoa(int(plan))) } return nil } var _ apis.Spec = &Contract{} // +k8s:deepcopy-gen:interfaces=github.com/mimuret/golang-iij-dpf/pkg/api.Object type Contract struct { AttributeMeta ID string `read:"id"` ServiceCode string `read:"service_code"` State types.State `read:"state"` Favorite types.Favorite `read:"favorite" update:"favorite"` Plan Plan `read:"plan"` Description string `read:"description" update:"description"` } func (c *Contract) GetName() string { return "contracts" } func (c *Contract) GetPathMethod(action api.Action) (string, string) { switch action { case api.ActionRead, api.ActionUpdate: return action.ToMethod(), fmt.Sprintf("/contracts/%s", c.ID) } return "", "" } func (c *Contract) SetPathParams(args ...interface{}) error { return apis.SetPathParams(args, &c.ID) } var _ apis.CountableListSpec = &ContractList{} // +k8s:deepcopy-gen:interfaces=github.com/mimuret/golang-iij-dpf/pkg/api.Object type ContractList struct { AttributeMeta api.Count Items []Contract `read:"items"` } func (c *ContractList) GetName() string { return "contracts" } func (c *ContractList) GetItems() interface{} { return &c.Items } func (c *ContractList) Len() int { return len(c.Items) } func (c *ContractList) Index(i int) interface{} { return c.Items[i] } func (c *ContractList) GetMaxLimit() int32 { return 10000 } func (c *ContractList) ClearItems() { c.Items = []Contract{} } func (c *ContractList) AddItem(v interface{}) bool { if a, ok := v.(Contract); ok { c.Items = append(c.Items, a) return true } return false } func (c *ContractList) GetPathMethod(action api.Action) (string, string) { switch action { case api.ActionList: return action.ToMethod(), "/contracts" case api.ActionCount: return action.ToMethod(), "/contracts/count" } return "", "" } func (c *ContractList) SetPathParams(args ...interface{}) error { return nil } func (c *ContractList) Init() {} var _ api.SearchParams = &ContractListSearchKeywords{} // +k8s:deepcopy-gen=false type ContractListSearchKeywords struct { api.CommonSearchParams FullText api.KeywordsString `url:"_keywords_full_text[],omitempty"` ServiceCode api.KeywordsString `url:"_keywords_service_code[],omitempty"` Plan KeywordsPlan `url:"_keywords_plan[],omitempty"` State api.KeywordsState `url:"_keywords_state[],omitempty"` Favorite api.KeywordsFavorite `url:"_keywords_favorite[],omitempty"` Description api.KeywordsString `url:"_keywords_description[],omitempty"` } func (s *ContractListSearchKeywords) GetValues() (url.Values, error) { return query.Values(s) } func init() { register(&Contract{}, &ContractList{}) } golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/core/contract_test.go000066400000000000000000000215051437707610400232730ustar00rootroot00000000000000package core_test import ( "context" "net/http" "net/url" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/jarcoal/httpmock" "github.com/mimuret/golang-iij-dpf/pkg/api" "github.com/mimuret/golang-iij-dpf/pkg/apis/dpf/v1/core" "github.com/mimuret/golang-iij-dpf/pkg/testtool" "github.com/mimuret/golang-iij-dpf/pkg/types" ) var _ = Describe("contract", func() { var ( c core.Contract cl *testtool.TestClient err error reqId string s1, s2 core.Contract slist core.ContractList ) BeforeEach(func() { cl = testtool.NewTestClient("", "http://localhost", nil) s1 = core.Contract{ ID: "f1", ServiceCode: "dpf0000001", State: types.StateBeforeStart, Favorite: types.FavoriteHighPriority, Plan: core.PlanBasic, Description: "contract 1", } s2 = core.Contract{ ID: "f2", ServiceCode: "dpf0000002", State: types.StateRunning, Favorite: types.FavoriteLowPriority, Plan: core.PlanPremium, Description: "contract 2", } slist = core.ContractList{ Items: []core.Contract{s1, s2}, } }) Describe("Contract", func() { Context("Read", func() { BeforeEach(func() { httpmock.RegisterResponder(http.MethodGet, "http://localhost/contracts/f1", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "D7155DA183ED47C48437183873DAC765", "result": { "id": "f1", "service_code": "dpf0000001", "state": 1, "favorite": 1, "plan": 1, "description": "contract 1" } }`))) httpmock.RegisterResponder(http.MethodGet, "http://localhost/contracts/f2", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "EECF5BC0FF834BFFA4F0253224667D10", "result": { "id": "f2", "service_code": "dpf0000002", "state": 2, "favorite": 2, "plan": 2, "description": "contract 2" } }`))) }) AfterEach(func() { httpmock.Reset() }) When("returns Contract f1", func() { BeforeEach(func() { c = core.Contract{ ID: "f1", } reqId, err = cl.Read(context.Background(), &c) }) It("returns normal", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal("D7155DA183ED47C48437183873DAC765")) Expect(c).To(Equal(s1)) }) }) When("returns Contract f2", func() { BeforeEach(func() { c = core.Contract{ ID: "f2", } reqId, err = cl.Read(context.Background(), &c) }) It("returns normal", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal("EECF5BC0FF834BFFA4F0253224667D10")) Expect(c).To(Equal(s2)) }) }) }) Context("Update", func() { id1, bs1 := testtool.CreateAsyncResponse() BeforeEach(func() { httpmock.RegisterResponder(http.MethodPatch, "http://localhost/contracts/f1", httpmock.NewBytesResponder(202, bs1)) reqId, err = cl.Update(context.Background(), &s1, nil) }) AfterEach(func() { httpmock.Reset() }) It("returns job_id", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal(id1)) }) It("post json", func() { Expect(cl.RequestBody["/contracts/f1"]).To(MatchJSON(`{ "favorite": 1, "description": "contract 1" }`)) }) }) Context("SetPathParams", func() { When("no arguments, nothing to do", func() { BeforeEach(func() { err = s1.SetPathParams() }) It("returns error", func() { Expect(err).To(Succeed()) }) }) When("enough arguments", func() { BeforeEach(func() { err = s1.SetPathParams("f10") }) It("not returns error", func() { Expect(err).To(Succeed()) }) It("can set ContractID", func() { Expect(s1.ID).To(Equal("f10")) }) }) When("arguments has extra value", func() { BeforeEach(func() { err = s1.SetPathParams("f10", 2) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) When("arguments type missmatch (ContractID)", func() { BeforeEach(func() { err = s1.SetPathParams(2) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) }) Context("api.Spec common test", func() { var nilSpec *core.Contract testtool.TestDeepCopyObject(&s1, nilSpec) testtool.TestGetName(&s1, "contracts") Context("GetPathMethod", func() { When("action is ActionRead", func() { testtool.TestGetPathMethod(&s1, api.ActionRead, http.MethodGet, "/contracts/f1") }) When("action is ActionUpdate", func() { testtool.TestGetPathMethod(&s1, api.ActionUpdate, http.MethodPatch, "/contracts/f1") }) When("action is other", func() { testtool.TestGetPathMethod(&s1, api.ActionApply, "", "") }) }) }) }) Describe("CommonConfigList", func() { var c core.ContractList Context("List", func() { BeforeEach(func() { httpmock.RegisterResponder(http.MethodGet, "http://localhost/contracts", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "1773D7B5F415464C944837053CE8BBF2", "results": [ { "id": "f1", "service_code": "dpf0000001", "state": 1, "favorite": 1, "plan": 1, "description": "contract 1" }, { "id": "f2", "service_code": "dpf0000002", "state": 2, "favorite": 2, "plan": 2, "description": "contract 2" } ] }`))) httpmock.RegisterResponder(http.MethodGet, "http://localhost/contracts/count", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "BD88B5E38397477989002302583C7FCC", "result": { "count": 2 } }`))) }) AfterEach(func() { httpmock.Reset() }) When("returns list ", func() { BeforeEach(func() { c = core.ContractList{} reqId, err = cl.List(context.Background(), &c, nil) }) It("returns normal", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal("1773D7B5F415464C944837053CE8BBF2")) Expect(c).To(Equal(slist)) }) }) }) Context("SetPathParams", func() { BeforeEach(func() { err = slist.SetPathParams() }) It("nothing todo", func() { Expect(err).To(Succeed()) }) }) Context("api.Spec common test", func() { var nilSpec *core.ContractList testtool.TestDeepCopyObject(&slist, nilSpec) testtool.TestGetName(&slist, "contracts") testtool.TestGetPathMethodForCountableList(&slist, "/contracts") }) Context("api.ListSpec common test", func() { testtool.TestGetItems(&slist, &slist.Items) testtool.TestLen(&slist, 2) Context("Index", func() { When("index exist", func() { It("returns item", func() { Expect(slist.Index(0)).To(Equal(s1)) }) }) }) }) Context("api.CountableListSpec common test", func() { testtool.TestGetMaxLimit(&slist, 10000) testtool.TestClearItems(&slist) testtool.TestAddItem(&slist, s1) }) }) Describe("ContractListSearchKeywords", func() { Context("GetValues", func() { testcase := []struct { keyword core.ContractListSearchKeywords values url.Values }{ { core.ContractListSearchKeywords{ CommonSearchParams: api.CommonSearchParams{ Type: api.SearchTypeAND, Offset: int32(10), Limit: int32(100), }, }, url.Values{ "type": []string{"AND"}, "offset": []string{"10"}, "limit": []string{"100"}, }, }, { core.ContractListSearchKeywords{ CommonSearchParams: api.CommonSearchParams{ Type: api.SearchTypeOR, Offset: int32(10), Limit: int32(100), }, FullText: api.KeywordsString{"hogehoge", "ðŸ°"}, ServiceCode: api.KeywordsString{"fxxxxxx", "fxxxxxx1"}, Plan: core.KeywordsPlan{core.PlanBasic, core.PlanPremium}, State: api.KeywordsState{types.StateBeforeStart, types.StateRunning}, Favorite: api.KeywordsFavorite{types.FavoriteHighPriority, types.FavoriteLowPriority}, Description: api.KeywordsString{"ã‚ã‚ã‚", "ðŸº"}, }, url.Values{ "type": []string{"OR"}, "offset": []string{"10"}, "limit": []string{"100"}, "_keywords_full_text[]": []string{"hogehoge", "ðŸ°"}, "_keywords_service_code[]": []string{"fxxxxxx", "fxxxxxx1"}, "_keywords_plan[]": []string{"1", "2"}, "_keywords_state[]": []string{"1", "2"}, "_keywords_favorite[]": []string{"1", "2"}, "_keywords_description[]": []string{"ã‚ã‚ã‚", "ðŸº"}, }, }, } It("can convert url.Value", func() { for _, tc := range testcase { s, err := tc.keyword.GetValues() Expect(err).To(Succeed()) Expect(s).To(Equal(tc.values)) } }) }) }) Context("PlanToString", func() { Context("String", func() { It("returns plan string", func() { Expect(core.PlanBasic.String()).To(Equal("basic")) Expect(core.PlanPremium.String()).To(Equal("premium")) }) }) }) }) golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/core/delegation.go000066400000000000000000000051511437707610400225310ustar00rootroot00000000000000package core import ( "net/url" "github.com/google/go-querystring/query" "github.com/mimuret/golang-iij-dpf/pkg/api" "github.com/mimuret/golang-iij-dpf/pkg/apis" "github.com/mimuret/golang-iij-dpf/pkg/types" ) // +k8s:deepcopy-gen:interfaces=github.com/mimuret/golang-iij-dpf/pkg/api.Object type Delegation struct { AttributeMeta ID string `read:"id"` ServiceCode string `read:"service_code"` Name string `read:"name"` Network string `read:"network"` Description string `read:"description"` DelegationRequestedAt types.Time `read:"delegation_requested_at"` } var _ apis.CountableListSpec = &DelegationList{} // +k8s:deepcopy-gen:interfaces=github.com/mimuret/golang-iij-dpf/pkg/api.Object type DelegationList struct { AttributeMeta api.Count Items []Delegation `read:"items"` } func (c *DelegationList) GetName() string { return "delegations" } func (c *DelegationList) GetItems() interface{} { return &c.Items } func (c *DelegationList) Len() int { return len(c.Items) } func (c *DelegationList) Index(i int) interface{} { return c.Items[i] } func (c *DelegationList) GetMaxLimit() int32 { return 10000 } func (c *DelegationList) ClearItems() { c.Items = []Delegation{} } func (c *DelegationList) AddItem(v interface{}) bool { if a, ok := v.(Delegation); ok { c.Items = append(c.Items, a) return true } return false } func (c *DelegationList) GetPathMethod(action api.Action) (string, string) { switch action { case api.ActionList: return action.ToMethod(), "/delegations" case api.ActionCount: return action.ToMethod(), "/delegations/count" } return "", "" } func (c *DelegationList) SetPathParams(args ...interface{}) error { return nil } func (c *DelegationList) Init() {} var _ api.SearchParams = &DelegationListSearchKeywords{} // +k8s:deepcopy-gen=false type DelegationListSearchKeywords struct { api.CommonSearchParams FullText api.KeywordsString `url:"_keywords_full_text[],omitempty"` ServiceCode api.KeywordsString `url:"_keywords_service_code[],omitempty"` Name api.KeywordsString `url:"_keywords_name[],omitempty"` Network api.KeywordsString `url:"_keywords_network[],omitempty"` Favorite api.KeywordsFavorite `url:"_keywords_favorite[],omitempty"` Description api.KeywordsString `url:"_keywords_description[],omitempty"` Requested api.KeywordsBoolean `url:"_keywords_requested[],omitempty"` } func (s *DelegationListSearchKeywords) GetValues() (url.Values, error) { return query.Values(s) } func init() { register(&DelegationList{}) } golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/core/delegation_apply.go000066400000000000000000000013001437707610400237260ustar00rootroot00000000000000package core import ( "net/http" "github.com/mimuret/golang-iij-dpf/pkg/api" "github.com/mimuret/golang-iij-dpf/pkg/apis" ) var _ apis.Spec = &DelegationApply{} // +k8s:deepcopy-gen:interfaces=github.com/mimuret/golang-iij-dpf/pkg/api.Object type DelegationApply struct { AttributeMeta ZoneIDs []string `apply:"zone_ids"` } func (c *DelegationApply) GetName() string { return "delegations" } func (c *DelegationApply) GetPathMethod(action api.Action) (string, string) { if action == api.ActionApply { return http.MethodPost, "/delegations" } return "", "" } func (c *DelegationApply) SetPathParams(args ...interface{}) error { return nil } func init() { register(&DelegationApply{}) } golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/core/delegation_apply_test.go000066400000000000000000000034551437707610400250020ustar00rootroot00000000000000package core_test import ( "context" "net/http" "github.com/jarcoal/httpmock" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/mimuret/golang-iij-dpf/pkg/api" "github.com/mimuret/golang-iij-dpf/pkg/apis/dpf/v1/core" "github.com/mimuret/golang-iij-dpf/pkg/testtool" ) var _ = Describe("delegations", func() { var ( cl *testtool.TestClient err error reqId string s core.DelegationApply ) BeforeEach(func() { Expect(err).To(Succeed()) cl = testtool.NewTestClient("", "http://localhost", nil) s = core.DelegationApply{ ZoneIDs: []string{"m1", "m2"}, } }) Describe("DelegationApply", func() { Context("Apply", func() { id1, bs1 := testtool.CreateAsyncResponse() BeforeEach(func() { httpmock.RegisterResponder(http.MethodPost, "http://localhost/delegations", httpmock.NewBytesResponder(202, bs1)) reqId, err = cl.Apply(context.Background(), &s, nil) }) AfterEach(func() { httpmock.Reset() }) It("returns job_id", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal(id1)) }) It("post json", func() { Expect(cl.RequestBody["/delegations"]).To(MatchJSON(`{ "zone_ids": ["m1","m2"] }`)) }) }) Context("SetPathParams", func() { BeforeEach(func() { err = s.SetPathParams() }) It("nothing todo", func() { Expect(err).To(Succeed()) }) }) Context("api.Spec common test", func() { var nilSpec *core.DelegationApply testtool.TestDeepCopyObject(&s, nilSpec) testtool.TestGetName(&s, "delegations") Context("GetPathMethod", func() { When("action is ActionApply", func() { testtool.TestGetPathMethod(&s, api.ActionApply, http.MethodPost, "/delegations") }) When("other", func() { testtool.TestGetPathMethod(&s, api.ActionRead, "", "") }) }) }) }) }) golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/core/delegation_test.go000066400000000000000000000131771437707610400235770ustar00rootroot00000000000000package core_test import ( "context" "net/http" "net/url" "time" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/jarcoal/httpmock" "github.com/mimuret/golang-iij-dpf/pkg/api" "github.com/mimuret/golang-iij-dpf/pkg/apis/dpf/v1/core" "github.com/mimuret/golang-iij-dpf/pkg/testtool" "github.com/mimuret/golang-iij-dpf/pkg/types" ) var _ = Describe("delegations", func() { var ( cl *testtool.TestClient err error reqId string s1, s2 core.Delegation slist core.DelegationList atTime types.Time ) BeforeEach(func() { atTime, err = types.ParseTime(time.RFC3339Nano, "2021-06-20T13:21:12.881Z") Expect(err).To(Succeed()) cl = testtool.NewTestClient("", "http://localhost", nil) s1 = core.Delegation{ ID: "m1", ServiceCode: "dpm000001", Name: "example.jp.", Network: "", Description: "zone 1", DelegationRequestedAt: atTime, } s2 = core.Delegation{ ID: "m2", ServiceCode: "dpm000002", Name: "168.192.in-addr.arpa.", Network: "192.168.0.0/16", Description: "zone 2", DelegationRequestedAt: types.Time{}, } slist = core.DelegationList{ Items: []core.Delegation{s1, s2}, } }) Describe("Delegation", func() { Context("DeepCopyObject", func() { var nilSpec *core.Delegation testtool.TestDeepCopyObject(&s1, nilSpec) }) }) Describe("DelegationList", func() { var c core.DelegationList Context("List", func() { BeforeEach(func() { httpmock.RegisterResponder(http.MethodGet, "http://localhost/delegations", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "51367A80A2B447EFA490AF379F12DD48", "results": [ { "id": "m1", "service_code": "dpm000001", "name": "example.jp.", "network": "", "description": "zone 1", "delegation_requested_at": "2021-06-20T13:21:12.881Z" }, { "id": "m2", "service_code": "dpm000002", "name": "168.192.in-addr.arpa.", "network": "192.168.0.0/16", "description": "zone 2", "delegation_requested_at": "" } ] }`))) httpmock.RegisterResponder(http.MethodGet, "http://localhost/delegations/count", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "D371175B1BB248BE812A845C351FDE82", "result": { "count": 2 } }`))) }) AfterEach(func() { httpmock.Reset() }) When("returns list ", func() { BeforeEach(func() { c = core.DelegationList{} reqId, err = cl.List(context.Background(), &c, nil) }) It("returns normal", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal("51367A80A2B447EFA490AF379F12DD48")) Expect(c).To(Equal(slist)) }) }) }) Context("SetPathParams", func() { BeforeEach(func() { err = slist.SetPathParams() }) It("nothing todo", func() { Expect(err).To(Succeed()) }) }) Context("api.Spec common test", func() { var nilSpec *core.DelegationList testtool.TestDeepCopyObject(&slist, nilSpec) testtool.TestGetName(&slist, "delegations") testtool.TestGetPathMethodForCountableList(&slist, "/delegations") }) Context("api.ListSpec common test", func() { testtool.TestGetItems(&slist, &slist.Items) testtool.TestLen(&slist, 2) Context("Index", func() { When("index exist", func() { It("returns item", func() { Expect(slist.Index(0)).To(Equal(s1)) }) }) }) }) Context("api.CountableListSpec common test", func() { testtool.TestGetMaxLimit(&slist, 10000) testtool.TestClearItems(&slist) testtool.TestAddItem(&slist, s1) }) }) Describe("DelegationListSearchKeywords", func() { Context("GetValues", func() { testcase := []struct { keyword core.DelegationListSearchKeywords values url.Values }{ { core.DelegationListSearchKeywords{ CommonSearchParams: api.CommonSearchParams{ Type: api.SearchTypeAND, Offset: int32(10), Limit: int32(100), }, }, url.Values{ "type": []string{"AND"}, "offset": []string{"10"}, "limit": []string{"100"}, }, }, { core.DelegationListSearchKeywords{ CommonSearchParams: api.CommonSearchParams{ Type: api.SearchTypeOR, Offset: int32(10), Limit: int32(100), }, FullText: api.KeywordsString{"hogehoge", "ðŸ°"}, ServiceCode: api.KeywordsString{"mxxxxxx", "mxxxxxx1"}, Name: api.KeywordsString{"example.jp", "example.net"}, Network: api.KeywordsString{"192.168.0.0/24"}, Favorite: api.KeywordsFavorite{types.FavoriteHighPriority, types.FavoriteLowPriority}, Description: api.KeywordsString{"ã‚ã‚ã‚", "ðŸº"}, Requested: api.KeywordsBoolean{types.Disabled, types.Enabled}, }, url.Values{ "type": []string{"OR"}, "offset": []string{"10"}, "limit": []string{"100"}, "_keywords_full_text[]": []string{"hogehoge", "ðŸ°"}, "_keywords_service_code[]": []string{"mxxxxxx", "mxxxxxx1"}, "_keywords_name[]": []string{"example.jp", "example.net"}, "_keywords_network[]": []string{"192.168.0.0/24"}, "_keywords_favorite[]": []string{"1", "2"}, "_keywords_description[]": []string{"ã‚ã‚ã‚", "ðŸº"}, "_keywords_requested[]": []string{"0", "1"}, }, }, } It("can convert url.Value", func() { for _, tc := range testcase { s, err := tc.keyword.GetValues() Expect(err).To(Succeed()) Expect(s).To(Equal(tc.values)) } }) }) }) }) golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/core/doc.go000066400000000000000000000000531437707610400211570ustar00rootroot00000000000000package core // +k8s:deepcopy-gen=package golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/core/ginkgo_test.go000066400000000000000000000006161437707610400227340ustar00rootroot00000000000000package core_test import ( "testing" "github.com/jarcoal/httpmock" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) func TestGinkgo(t *testing.T) { RegisterFailHandler(Fail) RunSpecs(t, "core package test suite") } var _ = BeforeSuite(func() { httpmock.Activate() }) var _ = BeforeEach(func() { httpmock.Reset() }) var _ = AfterSuite(func() { httpmock.DeactivateAndReset() }) golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/core/job.go000066400000000000000000000023401437707610400211650ustar00rootroot00000000000000package core import ( "fmt" "github.com/mimuret/golang-iij-dpf/pkg/api" "github.com/mimuret/golang-iij-dpf/pkg/apis" ) type JobStatus string var _ apis.Spec = &Job{} const ( JobStatusRunning JobStatus = "RUNNING" JobStatusSuccessful JobStatus = "SUCCESSFUL" JobStatusFailed JobStatus = "FAILED" ) func (c JobStatus) String() string { return string(c) } // +k8s:deepcopy-gen:interfaces=github.com/mimuret/golang-iij-dpf/pkg/api.Object type Job struct { AttributeMeta RequestID string `read:"request_id"` Status JobStatus `read:"status"` ResourceUrl string `read:"resources_url"` ErrorType string `read:"error_type"` ErrorMessage string `read:"error_message"` } func (c *Job) GetError() error { if c.Status == JobStatusFailed { return fmt.Errorf("ErrorType: %s Messages %s", c.ErrorType, c.ErrorMessage) } return nil } func (c *Job) GetName() string { return "jobs" } func (c *Job) GetPathMethod(action api.Action) (string, string) { if action == api.ActionRead { return action.ToMethod(), fmt.Sprintf("/jobs/%s", c.RequestID) } return "", "" } func (c *Job) SetPathParams(args ...interface{}) error { return apis.SetPathParams(args, &c.RequestID) } func init() { register(&Job{}) } golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/core/job_test.go000066400000000000000000000126111437707610400222260ustar00rootroot00000000000000package core_test import ( "context" "net/http" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/jarcoal/httpmock" "github.com/mimuret/golang-iij-dpf/pkg/api" "github.com/mimuret/golang-iij-dpf/pkg/apis/dpf/v1/core" "github.com/mimuret/golang-iij-dpf/pkg/testtool" ) var _ = Describe("jobs", func() { var ( c core.Job cl *testtool.TestClient err error reqId string s1, s2, s3 core.Job ) BeforeEach(func() { cl = testtool.NewTestClient("", "http://localhost", nil) s1 = core.Job{ RequestID: "9BCFE2E9C10D4D9A8444CB0B48C72830", Status: core.JobStatusRunning, } s2 = core.Job{ RequestID: "B52CBA3FBA8D4A5C951C4EBD9EB48076", Status: core.JobStatusSuccessful, ResourceUrl: "http://localhost/contracts/f1", } s3 = core.Job{ RequestID: "9F16F8E85D104D5C9C6BC58676B5D0BD", Status: core.JobStatusFailed, ErrorType: "fail", ErrorMessage: "error message", } }) Describe("Contract", func() { Context("Read", func() { BeforeEach(func() { httpmock.RegisterResponder(http.MethodGet, "http://localhost/jobs/9BCFE2E9C10D4D9A8444CB0B48C72830", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "9BCFE2E9C10D4D9A8444CB0B48C72830", "status": "RUNNING" }`))) httpmock.RegisterResponder(http.MethodGet, "http://localhost/jobs/B52CBA3FBA8D4A5C951C4EBD9EB48076", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "B52CBA3FBA8D4A5C951C4EBD9EB48076", "status": "SUCCESSFUL", "resources_url": "http://localhost/contracts/f1" }`))) httpmock.RegisterResponder(http.MethodGet, "http://localhost/jobs/9F16F8E85D104D5C9C6BC58676B5D0BD", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "9F16F8E85D104D5C9C6BC58676B5D0BD", "status": "FAILED", "error_type": "fail", "error_message": "error message" }`))) }) AfterEach(func() { httpmock.Reset() }) When("returns Job s1", func() { BeforeEach(func() { c = core.Job{ RequestID: "9BCFE2E9C10D4D9A8444CB0B48C72830", } reqId, err = cl.Read(context.Background(), &c) }) It("returns normal", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal("9BCFE2E9C10D4D9A8444CB0B48C72830")) Expect(c).To(Equal(s1)) }) }) When("returns Job s2", func() { BeforeEach(func() { c = core.Job{ RequestID: "B52CBA3FBA8D4A5C951C4EBD9EB48076", } reqId, err = cl.Read(context.Background(), &c) }) It("returns normal", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal("B52CBA3FBA8D4A5C951C4EBD9EB48076")) Expect(c).To(Equal(s2)) }) }) When("returns Job s3", func() { BeforeEach(func() { c = core.Job{ RequestID: "9F16F8E85D104D5C9C6BC58676B5D0BD", } reqId, err = cl.Read(context.Background(), &c) }) It("returns normal", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal("9F16F8E85D104D5C9C6BC58676B5D0BD")) Expect(c).To(Equal(s3)) }) }) }) Context("SetPathParams", func() { When("no arguments, nothing to do", func() { BeforeEach(func() { err = s1.SetPathParams() }) It("returns error", func() { Expect(err).To(Succeed()) }) }) When("enough arguments", func() { BeforeEach(func() { err = s1.SetPathParams("f10") }) It("not returns error", func() { Expect(err).To(Succeed()) }) It("can set ContractID", func() { Expect(s1.RequestID).To(Equal("f10")) }) }) When("arguments has extra value", func() { BeforeEach(func() { err = s1.SetPathParams("f10", 2) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) When("arguments type missmatch (RequestID)", func() { BeforeEach(func() { err = s1.SetPathParams(2) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) }) Context("api.Spec common test", func() { var nilSpec *core.Job testtool.TestDeepCopyObject(&s1, nilSpec) testtool.TestGetName(&s1, "jobs") Context("GetPathMethod", func() { When("action is ActionRead", func() { testtool.TestGetPathMethod(&s1, api.ActionRead, http.MethodGet, "/jobs/9BCFE2E9C10D4D9A8444CB0B48C72830") }) When("action is other", func() { testtool.TestGetPathMethod(&s1, api.ActionApply, "", "") }) }) }) Context("GetError", func() { When("running", func() { It("returns nil", func() { Expect(s1.Status).To(Equal(core.JobStatusRunning)) Expect(s1.GetError()).To(Succeed()) }) }) When("successful", func() { It("returns nil", func() { Expect(s2.Status).To(Equal(core.JobStatusSuccessful)) Expect(s2.GetError()).To(Succeed()) }) }) When("failed", func() { It("returns err", func() { Expect(s3.Status).To(Equal(core.JobStatusFailed)) Expect(s3.GetError()).To(HaveOccurred()) }) }) }) }) Context("JobStatus", func() { Context("String", func() { When("JobStatusRunning", func() { It("returns RUNNING", func() { Expect(core.JobStatusRunning.String()).To(Equal("RUNNING")) }) }) When("JobStatusRunning", func() { It("returns SUCCESSFUL", func() { Expect(core.JobStatusSuccessful.String()).To(Equal("SUCCESSFUL")) }) }) When("JobStatusRunning", func() { It("returns FAILED", func() { Expect(core.JobStatusFailed.String()).To(Equal("FAILED")) }) }) }) }) }) golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/core/lb_domain.go000066400000000000000000000063551437707610400223510ustar00rootroot00000000000000package core import ( "fmt" "net/url" "github.com/google/go-querystring/query" "github.com/mimuret/golang-iij-dpf/pkg/api" "github.com/mimuret/golang-iij-dpf/pkg/apis" "github.com/mimuret/golang-iij-dpf/pkg/types" ) var _ api.Spec = &LBDomain{} // +k8s:deepcopy-gen:interfaces=github.com/mimuret/golang-iij-dpf/pkg/api.Object type LBDomain struct { AttributeMeta ID string `read:"id"` CommonConfigID int64 `read:"common_config_id"` ServiceCode string `read:"service_code"` State types.State `read:"state"` Favorite types.Favorite `read:"favorite" update:"favorite"` Name string `read:"name"` Description string `read:"description" update:"description"` RuleResourceName string `read:"rule_resource_name" update:"rule_resource_name"` } func (c *LBDomain) GetName() string { return "lb_domains" } func (c *LBDomain) GetPathMethod(action api.Action) (string, string) { switch action { case api.ActionRead, api.ActionUpdate: return action.ToMethod(), fmt.Sprintf("/lb_domains/%s", c.ID) } return "", "" } func (c *LBDomain) SetPathParams(args ...interface{}) error { return apis.SetPathParams(args, &c.ID) } var _ apis.CountableListSpec = &ZoneList{} // +k8s:deepcopy-gen:interfaces=github.com/mimuret/golang-iij-dpf/pkg/api.Object type LBDomainList struct { AttributeMeta api.Count Items []LBDomain `read:"items"` } func (c *LBDomainList) GetName() string { return "lb_domains" } func (c *LBDomainList) GetItems() interface{} { return &c.Items } func (c *LBDomainList) Len() int { return len(c.Items) } func (c *LBDomainList) Index(i int) interface{} { return c.Items[i] } func (c *LBDomainList) GetMaxLimit() int32 { return 10000 } func (c *LBDomainList) ClearItems() { c.Items = []LBDomain{} } func (c *LBDomainList) AddItem(v interface{}) bool { if a, ok := v.(LBDomain); ok { c.Items = append(c.Items, a) return true } return false } func (c *LBDomainList) GetPathMethod(action api.Action) (string, string) { switch action { case api.ActionList: return action.ToMethod(), "/lb_domains" case api.ActionCount: return action.ToMethod(), "/lb_domains/count" } return "", "" } func (c *LBDomainList) Init() {} func (c *LBDomainList) SetPathParams(args ...interface{}) error { return nil } var _ api.SearchParams = &LBDomainListSearchKeywords{} // +k8s:deepcopy-gen=false type LBDomainListSearchKeywords struct { api.CommonSearchParams FullText api.KeywordsString `url:"_keywords_full_text[],omitempty"` ServiceCode api.KeywordsString `url:"_keywords_service_code[],omitempty"` Name api.KeywordsString `url:"_keywords_name[],omitempty"` State api.KeywordsState `url:"_keywords_state[],omitempty"` Favorite api.KeywordsFavorite `url:"_keywords_favorite[],omitempty"` Description api.KeywordsString `url:"_keywords_description[],omitempty"` CommonConfigID api.KeywordsID `url:"_keywords_common_config_id[],omitempty"` Label api.KeywordsLabels `url:"_keywords_label[],omitempty"` } func (s *LBDomainListSearchKeywords) GetValues() (url.Values, error) { return query.Values(s) } func init() { register(&LBDomain{}, &LBDomainList{}) } golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/core/lb_domain_test.go000066400000000000000000000237631437707610400234120ustar00rootroot00000000000000package core_test import ( "context" "net/http" "net/url" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/jarcoal/httpmock" "github.com/mimuret/golang-iij-dpf/pkg/api" "github.com/mimuret/golang-iij-dpf/pkg/apis/dpf/v1/core" "github.com/mimuret/golang-iij-dpf/pkg/testtool" "github.com/mimuret/golang-iij-dpf/pkg/types" ) var _ = Describe("lb_domains", func() { var ( c core.LBDomain cl *testtool.TestClient err error reqId string s1, s2 core.LBDomain slist core.LBDomainList ) BeforeEach(func() { cl = testtool.NewTestClient("", "http://localhost", nil) s1 = core.LBDomain{ ID: "b0000000000001", CommonConfigID: 1, ServiceCode: "dpl0000001", State: types.StateBeforeStart, Favorite: types.FavoriteHighPriority, Name: "lb.xxxxxxxxxxxxxxxx.x.d-16.jp.", Description: "lb_domains 1", RuleResourceName: "rule-1", } s2 = core.LBDomain{ ID: "b0000000000002", CommonConfigID: 2, ServiceCode: "dpl0000002", State: types.StateRunning, Favorite: types.FavoriteLowPriority, Name: "lb.xxxxxxxxxxxxxxxx.x.d-16.jp.", Description: "lb_domains 2", RuleResourceName: "rule-2", } slist = core.LBDomainList{ Items: []core.LBDomain{s1, s2}, } }) Describe("Contract", func() { Context("Read", func() { BeforeEach(func() { httpmock.RegisterResponder(http.MethodGet, "http://localhost/lb_domains/b0000000000001", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "76D7462F50E3417C96898A827E0D1EC1", "result": { "id": "b0000000000001", "common_config_id": 1, "service_code": "dpl0000001", "state": 1, "favorite": 1, "name": "lb.xxxxxxxxxxxxxxxx.x.d-16.jp.", "description": "lb_domains 1", "rule_resource_name": "rule-1" } }`))) httpmock.RegisterResponder(http.MethodGet, "http://localhost/lb_domains/b0000000000002", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "B10F0042282A46C18BFB440B5B58BF8C", "result": { "id": "b0000000000002", "common_config_id": 2, "service_code": "dpl0000002", "state": 2, "favorite":2, "name": "lb.xxxxxxxxxxxxxxxx.x.d-16.jp.", "description": "lb_domains 2", "rule_resource_name": "rule-2" } }`))) }) AfterEach(func() { httpmock.Reset() }) When("returns LBDomain m1", func() { BeforeEach(func() { c = core.LBDomain{ ID: "b0000000000001", } reqId, err = cl.Read(context.Background(), &c) }) It("returns normal", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal("76D7462F50E3417C96898A827E0D1EC1")) Expect(c).To(Equal(s1)) }) }) When("returns LBDomain m2", func() { BeforeEach(func() { c = core.LBDomain{ ID: "b0000000000002", } reqId, err = cl.Read(context.Background(), &c) }) It("returns normal", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal("B10F0042282A46C18BFB440B5B58BF8C")) Expect(c).To(Equal(s2)) }) }) }) Context("Update", func() { id1, bs1 := testtool.CreateAsyncResponse() BeforeEach(func() { httpmock.RegisterResponder(http.MethodPatch, "http://localhost/lb_domains/b0000000000001", httpmock.NewBytesResponder(202, bs1)) reqId, err = cl.Update(context.Background(), &s1, nil) }) AfterEach(func() { httpmock.Reset() }) It("returns job_id", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal(id1)) }) It("post json", func() { Expect(cl.RequestBody["/lb_domains/b0000000000001"]).To(MatchJSON(`{ "favorite": 1, "description": "lb_domains 1", "rule_resource_name": "rule-1" }`)) }) }) Context("SetPathParams", func() { When("no arguments, nothing to do", func() { BeforeEach(func() { err = s1.SetPathParams() }) It("returns error", func() { Expect(err).To(Succeed()) }) }) When("enough arguments", func() { BeforeEach(func() { err = s1.SetPathParams("b0000000000010") }) It("not returns error", func() { Expect(err).To(Succeed()) }) It("can set ContractID", func() { Expect(s1.ID).To(Equal("b0000000000010")) }) }) When("arguments has extra value", func() { BeforeEach(func() { err = s1.SetPathParams("b0000000000010", 2) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) When("arguments type missmatch", func() { BeforeEach(func() { err = s1.SetPathParams(2) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) }) Context("api.Spec common test", func() { var nilSpec *core.LBDomain testtool.TestDeepCopyObject(&s1, nilSpec) testtool.TestGetName(&s1, "lb_domains") Context("GetPathMethod", func() { When("action is ActionRead", func() { testtool.TestGetPathMethod(&s1, api.ActionRead, http.MethodGet, "/lb_domains/b0000000000001") }) When("action is ActionUpdate", func() { testtool.TestGetPathMethod(&s1, api.ActionUpdate, http.MethodPatch, "/lb_domains/b0000000000001") }) When("action is other", func() { testtool.TestGetPathMethod(&s1, api.ActionApply, "", "") }) }) }) }) Describe("LBDomainList", func() { var c core.LBDomainList Context("List", func() { BeforeEach(func() { httpmock.RegisterResponder(http.MethodGet, "http://localhost/lb_domains", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "2C18922432DC48D485613F5383A7ED8E", "results": [ { "id": "b0000000000001", "common_config_id": 1, "service_code": "dpl0000001", "state": 1, "favorite": 1, "name": "lb.xxxxxxxxxxxxxxxx.x.d-16.jp.", "description": "lb_domains 1", "rule_resource_name": "rule-1" }, { "id": "b0000000000002", "common_config_id": 2, "service_code": "dpl0000002", "state": 2, "favorite":2, "name": "lb.xxxxxxxxxxxxxxxx.x.d-16.jp.", "description": "lb_domains 2", "rule_resource_name": "rule-2" } ] }`))) httpmock.RegisterResponder(http.MethodGet, "http://localhost/lb_domains/count", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "9C518C729E5541D999389C686FE8987D", "result": { "count": 2 } }`))) }) AfterEach(func() { httpmock.Reset() }) When("returns list ", func() { BeforeEach(func() { c = core.LBDomainList{} reqId, err = cl.List(context.Background(), &c, nil) }) It("returns normal", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal("2C18922432DC48D485613F5383A7ED8E")) Expect(c).To(Equal(slist)) }) }) }) Context("SetPathParams", func() { BeforeEach(func() { err = slist.SetPathParams() }) It("nothing todo", func() { Expect(err).To(Succeed()) }) }) Context("api.Spec common test", func() { var nilSpec *core.LBDomainList testtool.TestDeepCopyObject(&slist, nilSpec) testtool.TestGetName(&slist, "lb_domains") testtool.TestGetPathMethodForCountableList(&slist, "/lb_domains") }) Context("api.ListSpec common test", func() { testtool.TestGetItems(&slist, &slist.Items) testtool.TestLen(&slist, 2) Context("Index", func() { When("index exist", func() { It("returns item", func() { Expect(slist.Index(0)).To(Equal(s1)) }) }) }) }) Context("api.CountableListSpec common test", func() { testtool.TestGetMaxLimit(&slist, 10000) testtool.TestClearItems(&slist) testtool.TestAddItem(&slist, s1) }) }) Describe("LBDomainListSearchKeywords", func() { Context("GetValues", func() { testcase := []struct { keyword core.LBDomainListSearchKeywords values url.Values }{ { core.LBDomainListSearchKeywords{ CommonSearchParams: api.CommonSearchParams{ Type: api.SearchTypeAND, Offset: int32(10), Limit: int32(100), }, }, url.Values{ "type": []string{"AND"}, "offset": []string{"10"}, "limit": []string{"100"}, }, }, { core.LBDomainListSearchKeywords{ CommonSearchParams: api.CommonSearchParams{ Type: api.SearchTypeOR, Offset: int32(10), Limit: int32(100), }, FullText: api.KeywordsString{"hogehoge", "ðŸ°"}, ServiceCode: api.KeywordsString{"mxxxxxx", "mxxxxxx1"}, Name: api.KeywordsString{"example.jp", "example.net"}, State: api.KeywordsState{types.StateBeforeStart, types.StateRunning}, Favorite: api.KeywordsFavorite{types.FavoriteHighPriority, types.FavoriteLowPriority}, Description: api.KeywordsString{"ã‚ã‚ã‚", "ðŸº"}, CommonConfigID: api.KeywordsID{100, 200}, Label: api.KeywordsLabels{api.Label{Key: "hogehoge", Value: "hugahuga"}}, }, /* _keywords_full_text[] _keywords_service_code[] _keywords_name[] _keywords_state[] _keywords_favorite[] _keywords_description[] _keywords_common_config_id[] _keywords_label[] */ url.Values{ "type": []string{"OR"}, "offset": []string{"10"}, "limit": []string{"100"}, "_keywords_full_text[]": []string{"hogehoge", "ðŸ°"}, "_keywords_service_code[]": []string{"mxxxxxx", "mxxxxxx1"}, "_keywords_name[]": []string{"example.jp", "example.net"}, "_keywords_state[]": []string{"1", "2"}, "_keywords_favorite[]": []string{"1", "2"}, "_keywords_description[]": []string{"ã‚ã‚ã‚", "ðŸº"}, "_keywords_common_config_id[]": []string{"100", "200"}, "_keywords_label[]": []string{"hogehoge=hugahuga"}, }, }, } It("can convert url.Value", func() { for _, tc := range testcase { s, err := tc.keyword.GetValues() Expect(err).To(Succeed()) Expect(s).To(Equal(tc.values)) } }) }) }) }) golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/core/log.go000066400000000000000000000035221437707610400211770ustar00rootroot00000000000000package core import ( "net/url" "github.com/google/go-querystring/query" "github.com/mimuret/golang-iij-dpf/pkg/api" "github.com/mimuret/golang-iij-dpf/pkg/types" ) type LogStatus string const ( LogStatusStart LogStatus = "start" LogStatusSuccess LogStatus = "success" LogStatusFailure LogStatus = "failure" LogStatusRetry LogStatus = "retry" ) func (c LogStatus) String() string { return string(c) } // +k8s:deepcopy-gen=false type KeywordsLogStatus []LogStatus type Log struct { Time types.Time `read:"time"` LogType string `read:"log_type"` Operator string `read:"operator"` Operation string `read:"operation"` Target string `read:"target"` RequestID string `read:"request_id"` Status LogStatus `read:"status"` } // +k8s:deepcopy-gen=false type SearchLogsOffset int32 func (s SearchLogsOffset) Validate() bool { if s < 0 || s > 9900 { return false } return true } // +k8s:deepcopy-gen=false type SearchLogsLimit int32 func (s SearchLogsLimit) Validate() bool { if s < 1 || s > 100 { return false } return true } var _ api.SearchParams = &LogListSearchKeywords{} // +k8s:deepcopy-gen=false type LogListSearchKeywords struct { api.CommonSearchParams FullText api.KeywordsString `url:"_keywords_full_text[],omitempty"` LogType api.KeywordsString `url:"_keywords_log_type[],omitempty"` Operator api.KeywordsString `url:"_keywords_operator[],omitempty"` Operation api.KeywordsString `url:"_keywords_operation[],omitempty"` Target api.KeywordsString `url:"_keywords_target[],omitempty"` Detail api.KeywordsString `url:"_keywords_detail[],omitempty"` RequestID api.KeywordsString `url:"_keywords_request_id[],omitempty"` Status KeywordsLogStatus `url:"_keywords_status[],omitempty"` } func (s *LogListSearchKeywords) GetValues() (url.Values, error) { return query.Values(s) } golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/core/log_test.go000066400000000000000000000116271437707610400222430ustar00rootroot00000000000000package core_test import ( "net/url" "time" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/mimuret/golang-iij-dpf/pkg/api" "github.com/mimuret/golang-iij-dpf/pkg/apis/dpf/v1/core" "github.com/mimuret/golang-iij-dpf/pkg/types" ) var _ = Describe("log", func() { var ( err error s1 core.Log atTime types.Time ) BeforeEach(func() { atTime, err = types.ParseTime(time.RFC3339Nano, "2021-06-20T13:21:12.881Z") Expect(err).To(Succeed()) s1 = core.Log{ Time: atTime, LogType: "service", Operator: "user1", Operation: "add_cc_primary", Target: "1", Status: core.LogStatusStart, } }) Describe("Log", func() { Context("DeepCopy", func() { var ( copy *core.Log nilMeta *core.Log ) When("Log is not nil", func() { BeforeEach(func() { copy = s1.DeepCopy() }) It("returns copy ", func() { Expect(copy).To(Equal(&s1)) }) }) When("Log is nil", func() { BeforeEach(func() { copy = nilMeta.DeepCopy() }) It("returns copy ", func() { Expect(copy).To(BeNil()) }) }) }) }) Describe("LogStatus", func() { Context("String", func() { It("returns string", func() { Expect(core.LogStatusStart.String()).To(Equal("start")) }) }) }) Describe("SearchLogsOffset", func() { Context("Validate", func() { When("value < 0", func() { It("returns false", func() { Expect(core.SearchLogsOffset(-1).Validate()).To(BeFalse()) }) }) When("normal", func() { It("returns true", func() { Expect(core.SearchLogsOffset(0).Validate()).To(BeTrue()) Expect(core.SearchLogsOffset(9900).Validate()).To(BeTrue()) }) }) When("value > 9900", func() { It("returns false", func() { Expect(core.SearchLogsOffset(9901).Validate()).To(BeFalse()) }) }) }) }) Describe("SearchLogsLimit", func() { Context("Validate", func() { When("value < 0", func() { It("returns false", func() { Expect(core.SearchLogsLimit(0).Validate()).To(BeFalse()) Expect(core.SearchLogsLimit(-1).Validate()).To(BeFalse()) }) }) When("normal", func() { It("returns true", func() { Expect(core.SearchLogsLimit(1).Validate()).To(BeTrue()) Expect(core.SearchLogsLimit(100).Validate()).To(BeTrue()) }) }) When("value > 9900", func() { It("returns false", func() { Expect(core.SearchLogsLimit(101).Validate()).To(BeFalse()) }) }) }) }) Describe("TestLogListSearchKeywords", func() { Context("GetValues", func() { testcase := []struct { keyword core.LogListSearchKeywords values url.Values }{ { core.LogListSearchKeywords{ CommonSearchParams: api.CommonSearchParams{ Type: api.SearchTypeAND, Offset: int32(10), Limit: int32(100), }, }, url.Values{ "type": []string{"AND"}, "offset": []string{"10"}, "limit": []string{"100"}, }, }, { core.LogListSearchKeywords{ CommonSearchParams: api.CommonSearchParams{ Type: api.SearchTypeOR, Offset: int32(10), Limit: int32(100), }, FullText: api.KeywordsString{"hogehoge", "ðŸ°"}, LogType: api.KeywordsString{"service", "record", "dnssec"}, Operator: api.KeywordsString{"rabbit@example.jp", "SA0000000"}, Operation: api.KeywordsString{"updating_default_ttl", "dismiss_zone_edits"}, Target: api.KeywordsString{"hoge", "fuga"}, Detail: api.KeywordsString{"ðŸ‡", "ðŸº"}, RequestID: api.KeywordsString{"f02fe1e1404140cab93c8f7af26081b7", "f098f808cde249d48a885490f7622df9"}, Status: core.KeywordsLogStatus{core.LogStatusStart, core.LogStatusSuccess, core.LogStatusFailure, core.LogStatusRetry}, }, /* _keywords_full_text[] _keywords_log_type[] _keywords_operator[] _keywords_operation[] _keywords_target[] _keywords_detail[] _keywords_request_id[] _keywords_status[] */ url.Values{ "type": []string{"OR"}, "offset": []string{"10"}, "limit": []string{"100"}, "_keywords_full_text[]": []string{"hogehoge", "ðŸ°"}, "_keywords_log_type[]": []string{"service", "record", "dnssec"}, "_keywords_operator[]": []string{"rabbit@example.jp", "SA0000000"}, "_keywords_operation[]": []string{"updating_default_ttl", "dismiss_zone_edits"}, "_keywords_target[]": []string{"hoge", "fuga"}, "_keywords_detail[]": []string{"ðŸ‡", "ðŸº"}, "_keywords_request_id[]": []string{"f02fe1e1404140cab93c8f7af26081b7", "f098f808cde249d48a885490f7622df9"}, "_keywords_status[]": []string{"start", "success", "failure", "retry"}, }, }, } It("can convert url.Value", func() { for _, tc := range testcase { s, err := tc.keyword.GetValues() Expect(err).To(Succeed()) Expect(s).To(Equal(tc.values)) } }) }) }) }) golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/core/zone.go000066400000000000000000000063641437707610400214000ustar00rootroot00000000000000package core import ( "fmt" "net/url" "github.com/google/go-querystring/query" "github.com/mimuret/golang-iij-dpf/pkg/api" "github.com/mimuret/golang-iij-dpf/pkg/apis" "github.com/mimuret/golang-iij-dpf/pkg/types" ) var _ api.Spec = &Zone{} // +k8s:deepcopy-gen:interfaces=github.com/mimuret/golang-iij-dpf/pkg/api.Object type Zone struct { AttributeMeta ID string `read:"id"` CommonConfigID int64 `read:"common_config_id"` ServiceCode string `read:"service_code"` State types.State `read:"state"` Favorite types.Favorite `read:"favorite" update:"favorite"` Name string `read:"name"` Network string `read:"network"` Description string `read:"description" update:"description"` ZoneProxyEnabled types.Boolean `read:"zone_proxy_enabled"` } func (c *Zone) GetName() string { return "zones" } func (c *Zone) GetPathMethod(action api.Action) (string, string) { switch action { case api.ActionRead, api.ActionUpdate: return action.ToMethod(), fmt.Sprintf("/zones/%s", c.ID) } return "", "" } func (c *Zone) SetPathParams(args ...interface{}) error { return apis.SetPathParams(args, &c.ID) } var _ apis.CountableListSpec = &ZoneList{} // +k8s:deepcopy-gen:interfaces=github.com/mimuret/golang-iij-dpf/pkg/api.Object type ZoneList struct { AttributeMeta api.Count Items []Zone `read:"items"` } func (c *ZoneList) GetName() string { return "zones" } func (c *ZoneList) GetItems() interface{} { return &c.Items } func (c *ZoneList) Len() int { return len(c.Items) } func (c *ZoneList) Index(i int) interface{} { return c.Items[i] } func (c *ZoneList) GetMaxLimit() int32 { return 10000 } func (c *ZoneList) ClearItems() { c.Items = []Zone{} } func (c *ZoneList) AddItem(v interface{}) bool { if a, ok := v.(Zone); ok { c.Items = append(c.Items, a) return true } return false } func (c *ZoneList) GetPathMethod(action api.Action) (string, string) { switch action { case api.ActionList: return action.ToMethod(), "/zones" case api.ActionCount: return action.ToMethod(), "/zones/count" } return "", "" } func (c *ZoneList) Init() {} func (c *ZoneList) SetPathParams(args ...interface{}) error { return nil } var _ api.SearchParams = &ZoneListSearchKeywords{} // +k8s:deepcopy-gen=false type ZoneListSearchKeywords struct { api.CommonSearchParams FullText api.KeywordsString `url:"_keywords_full_text[],omitempty"` ServiceCode api.KeywordsString `url:"_keywords_service_code[],omitempty"` Name api.KeywordsString `url:"_keywords_name[],omitempty"` Network api.KeywordsString `url:"_keywords_network[],omitempty"` State api.KeywordsState `url:"_keywords_state[],omitempty"` Favorite api.KeywordsFavorite `url:"_keywords_favorite[],omitempty"` Description api.KeywordsString `url:"_keywords_description[],omitempty"` CommonConfigID api.KeywordsID `url:"_keywords_common_config_id[],omitempty"` ZoneProxyEnabled api.KeywordsBoolean `url:"_keywords_zone_proxy_enabled[],omitempty"` } func (s *ZoneListSearchKeywords) GetValues() (url.Values, error) { return query.Values(s) } func init() { register(&Zone{}, &ZoneList{}) } golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/core/zone_test.go000066400000000000000000000235341437707610400224350ustar00rootroot00000000000000package core_test import ( "context" "net/http" "net/url" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/jarcoal/httpmock" "github.com/mimuret/golang-iij-dpf/pkg/api" "github.com/mimuret/golang-iij-dpf/pkg/apis/dpf/v1/core" "github.com/mimuret/golang-iij-dpf/pkg/testtool" "github.com/mimuret/golang-iij-dpf/pkg/types" ) var _ = Describe("zones", func() { var ( c core.Zone cl *testtool.TestClient err error reqId string s1, s2 core.Zone slist core.ZoneList ) BeforeEach(func() { cl = testtool.NewTestClient("", "http://localhost", nil) s1 = core.Zone{ ID: "m1", CommonConfigID: 1, ServiceCode: "dpm0000001", State: types.StateBeforeStart, Favorite: types.FavoriteHighPriority, Name: "example.jp.", Network: "", Description: "zone 1", ZoneProxyEnabled: types.Disabled, } s2 = core.Zone{ ID: "m2", CommonConfigID: 2, ServiceCode: "dpm0000002", State: types.StateRunning, Favorite: types.FavoriteLowPriority, Name: "168.192.in-addr.arpa.", Network: "192.168.0.0/16", Description: "zone 2", ZoneProxyEnabled: types.Enabled, } slist = core.ZoneList{ Items: []core.Zone{s1, s2}, } }) Describe("Contract", func() { Context("Read", func() { BeforeEach(func() { httpmock.RegisterResponder(http.MethodGet, "http://localhost/zones/m1", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "76D7462F50E3417C96898A827E0D1EC1", "result": { "id": "m1", "common_config_id": 1, "service_code": "dpm0000001", "state": 1, "favorite": 1, "name": "example.jp.", "network": "", "description": "zone 1", "zone_proxy_enabled": 0 } }`))) httpmock.RegisterResponder(http.MethodGet, "http://localhost/zones/m2", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "B10F0042282A46C18BFB440B5B58BF8C", "result": { "id": "m2", "common_config_id": 2, "service_code": "dpm0000002", "state": 2, "favorite":2, "name": "168.192.in-addr.arpa.", "network": "192.168.0.0/16", "description": "zone 2", "zone_proxy_enabled": 1 } }`))) }) AfterEach(func() { httpmock.Reset() }) When("returns Zone m1", func() { BeforeEach(func() { c = core.Zone{ ID: "m1", } reqId, err = cl.Read(context.Background(), &c) }) It("returns normal", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal("76D7462F50E3417C96898A827E0D1EC1")) Expect(c).To(Equal(s1)) }) }) When("returns Zone m2", func() { BeforeEach(func() { c = core.Zone{ ID: "m2", } reqId, err = cl.Read(context.Background(), &c) }) It("returns normal", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal("B10F0042282A46C18BFB440B5B58BF8C")) Expect(c).To(Equal(s2)) }) }) }) Context("Update", func() { id1, bs1 := testtool.CreateAsyncResponse() BeforeEach(func() { httpmock.RegisterResponder(http.MethodPatch, "http://localhost/zones/m1", httpmock.NewBytesResponder(202, bs1)) reqId, err = cl.Update(context.Background(), &s1, nil) }) AfterEach(func() { httpmock.Reset() }) It("returns job_id", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal(id1)) }) It("post json", func() { Expect(cl.RequestBody["/zones/m1"]).To(MatchJSON(`{ "favorite": 1, "description": "zone 1" }`)) }) }) Context("SetPathParams", func() { When("no arguments, nothing to do", func() { BeforeEach(func() { err = s1.SetPathParams() }) It("returns error", func() { Expect(err).To(Succeed()) }) }) When("enough arguments", func() { BeforeEach(func() { err = s1.SetPathParams("m100") }) It("not returns error", func() { Expect(err).To(Succeed()) }) It("can set ContractID", func() { Expect(s1.ID).To(Equal("m100")) }) }) When("arguments has extra value", func() { BeforeEach(func() { err = s1.SetPathParams("m100", 2) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) When("arguments type missmatch (ZoneID)", func() { BeforeEach(func() { err = s1.SetPathParams(2) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) }) Context("api.Spec common test", func() { var nilSpec *core.Zone testtool.TestDeepCopyObject(&s1, nilSpec) testtool.TestGetName(&s1, "zones") Context("GetPathMethod", func() { When("action is ActionRead", func() { testtool.TestGetPathMethod(&s1, api.ActionRead, http.MethodGet, "/zones/m1") }) When("action is ActionUpdate", func() { testtool.TestGetPathMethod(&s1, api.ActionUpdate, http.MethodPatch, "/zones/m1") }) When("action is other", func() { testtool.TestGetPathMethod(&s1, api.ActionApply, "", "") }) }) }) }) Describe("ZoneList", func() { var c core.ZoneList Context("List", func() { BeforeEach(func() { httpmock.RegisterResponder(http.MethodGet, "http://localhost/zones", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "2C18922432DC48D485613F5383A7ED8E", "results": [ { "id": "m1", "common_config_id": 1, "service_code": "dpm0000001", "state": 1, "favorite": 1, "name": "example.jp.", "network": "", "description": "zone 1", "zone_proxy_enabled": 0 }, { "id": "m2", "common_config_id": 2, "service_code": "dpm0000002", "state": 2, "favorite":2, "name": "168.192.in-addr.arpa.", "network": "192.168.0.0/16", "description": "zone 2", "zone_proxy_enabled": 1 } ] }`))) httpmock.RegisterResponder(http.MethodGet, "http://localhost/zones/count", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "9C518C729E5541D999389C686FE8987D", "result": { "count": 2 } }`))) }) AfterEach(func() { httpmock.Reset() }) When("returns list ", func() { BeforeEach(func() { c = core.ZoneList{} reqId, err = cl.List(context.Background(), &c, nil) }) It("returns normal", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal("2C18922432DC48D485613F5383A7ED8E")) Expect(c).To(Equal(slist)) }) }) }) Context("SetPathParams", func() { BeforeEach(func() { err = slist.SetPathParams() }) It("nothing todo", func() { Expect(err).To(Succeed()) }) }) Context("api.Spec common test", func() { var nilSpec *core.ZoneList testtool.TestDeepCopyObject(&slist, nilSpec) testtool.TestGetName(&slist, "zones") testtool.TestGetPathMethodForCountableList(&slist, "/zones") }) Context("api.ListSpec common test", func() { testtool.TestGetItems(&slist, &slist.Items) testtool.TestLen(&slist, 2) Context("Index", func() { When("index exist", func() { It("returns item", func() { Expect(slist.Index(0)).To(Equal(s1)) }) }) }) }) Context("api.CountableListSpec common test", func() { testtool.TestGetMaxLimit(&slist, 10000) testtool.TestClearItems(&slist) testtool.TestAddItem(&slist, s1) }) }) Describe("ZoneListSearchKeywords", func() { Context("GetValues", func() { testcase := []struct { keyword core.ZoneListSearchKeywords values url.Values }{ { core.ZoneListSearchKeywords{ CommonSearchParams: api.CommonSearchParams{ Type: api.SearchTypeAND, Offset: int32(10), Limit: int32(100), }, }, url.Values{ "type": []string{"AND"}, "offset": []string{"10"}, "limit": []string{"100"}, }, }, { core.ZoneListSearchKeywords{ CommonSearchParams: api.CommonSearchParams{ Type: api.SearchTypeOR, Offset: int32(10), Limit: int32(100), }, FullText: api.KeywordsString{"hogehoge", "ðŸ°"}, ServiceCode: api.KeywordsString{"mxxxxxx", "mxxxxxx1"}, Name: api.KeywordsString{"example.jp", "example.net"}, Network: api.KeywordsString{"192.168.0.0/24"}, State: api.KeywordsState{types.StateBeforeStart, types.StateRunning}, Favorite: api.KeywordsFavorite{types.FavoriteHighPriority, types.FavoriteLowPriority}, Description: api.KeywordsString{"ã‚ã‚ã‚", "ðŸº"}, CommonConfigID: api.KeywordsID{100, 200}, ZoneProxyEnabled: api.KeywordsBoolean{types.Enabled, types.Disabled}, }, /* _keywords_full_text[] _keywords_service_code[] _keywords_name[] _keywords_network[] _keywords_state[] _keywords_favorite[] _keywords_description[] _keywords_common_config_id[] _keywords_zone_proxy_enabled[] */ url.Values{ "type": []string{"OR"}, "offset": []string{"10"}, "limit": []string{"100"}, "_keywords_full_text[]": []string{"hogehoge", "ðŸ°"}, "_keywords_service_code[]": []string{"mxxxxxx", "mxxxxxx1"}, "_keywords_name[]": []string{"example.jp", "example.net"}, "_keywords_network[]": []string{"192.168.0.0/24"}, "_keywords_state[]": []string{"1", "2"}, "_keywords_favorite[]": []string{"1", "2"}, "_keywords_description[]": []string{"ã‚ã‚ã‚", "ðŸº"}, "_keywords_common_config_id[]": []string{"100", "200"}, "_keywords_zone_proxy_enabled[]": []string{"1", "0"}, }, }, } It("can convert url.Value", func() { for _, tc := range testcase { s, err := tc.keyword.GetValues() Expect(err).To(Succeed()) Expect(s).To(Equal(tc.values)) } }) }) }) }) golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/lb_domains/000077500000000000000000000000001437707610400212445ustar00rootroot00000000000000golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/lb_domains/ZZ_deepcopy_generated.go000066400000000000000000000634251437707610400260560ustar00rootroot00000000000000//go:build !ignore_autogenerated // +build !ignore_autogenerated /* MIT License Copyright (c) 2021 Manabu Sonoda 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. */ // Code generated by deepcopy-gen. DO NOT EDIT. package lb_domains import ( api "github.com/mimuret/golang-iij-dpf/pkg/api" core "github.com/mimuret/golang-iij-dpf/pkg/apis/dpf/v1/core" ) // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *AttributeMeta) DeepCopyInto(out *AttributeMeta) { *out = *in return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AttributeMeta. func (in *AttributeMeta) DeepCopy() *AttributeMeta { if in == nil { return nil } out := new(AttributeMeta) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Config) DeepCopyInto(out *Config) { *out = *in out.AttributeMeta = in.AttributeMeta if in.Monitorings != nil { in, out := &in.Monitorings, &out.Monitorings *out = make([]Monitoring, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } if in.Sites != nil { in, out := &in.Sites, &out.Sites *out = make([]Site, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } if in.Rules != nil { in, out := &in.Rules, &out.Rules *out = make([]Rule, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Config. func (in *Config) DeepCopy() *Config { if in == nil { return nil } out := new(Config) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new api.Object. func (in *Config) DeepCopyObject() api.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Endpoint) DeepCopyInto(out *Endpoint) { *out = *in out.SiteAttributeMeta = in.SiteAttributeMeta if in.Rdata != nil { in, out := &in.Rdata, &out.Rdata *out = make([]EndpointRdata, len(*in)) copy(*out, *in) } if in.Monitorings != nil { in, out := &in.Monitorings, &out.Monitorings *out = make([]MonitoringEndpoint, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Endpoint. func (in *Endpoint) DeepCopy() *Endpoint { if in == nil { return nil } out := new(Endpoint) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new api.Object. func (in *Endpoint) DeepCopyObject() api.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *EndpointList) DeepCopyInto(out *EndpointList) { *out = *in out.SiteAttributeMeta = in.SiteAttributeMeta if in.Items != nil { in, out := &in.Items, &out.Items *out = make([]Endpoint, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new EndpointList. func (in *EndpointList) DeepCopy() *EndpointList { if in == nil { return nil } out := new(EndpointList) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new api.Object. func (in *EndpointList) DeepCopyObject() api.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *EndpointManualFailback) DeepCopyInto(out *EndpointManualFailback) { *out = *in out.SiteAttributeMeta = in.SiteAttributeMeta return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new EndpointManualFailback. func (in *EndpointManualFailback) DeepCopy() *EndpointManualFailback { if in == nil { return nil } out := new(EndpointManualFailback) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new api.Object. func (in *EndpointManualFailback) DeepCopyObject() api.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *EndpointManualFailover) DeepCopyInto(out *EndpointManualFailover) { *out = *in out.SiteAttributeMeta = in.SiteAttributeMeta return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new EndpointManualFailover. func (in *EndpointManualFailover) DeepCopy() *EndpointManualFailover { if in == nil { return nil } out := new(EndpointManualFailover) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new api.Object. func (in *EndpointManualFailover) DeepCopyObject() api.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *EndpointRdata) DeepCopyInto(out *EndpointRdata) { *out = *in return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new EndpointRdata. func (in *EndpointRdata) DeepCopy() *EndpointRdata { if in == nil { return nil } out := new(EndpointRdata) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *LogList) DeepCopyInto(out *LogList) { *out = *in out.AttributeMeta = in.AttributeMeta out.Count = in.Count if in.Items != nil { in, out := &in.Items, &out.Items *out = make([]core.Log, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new LogList. func (in *LogList) DeepCopy() *LogList { if in == nil { return nil } out := new(LogList) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new api.Object. func (in *LogList) DeepCopyObject() api.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Monitoring) DeepCopyInto(out *Monitoring) { *out = *in out.AttributeMeta = in.AttributeMeta out.MonitoringCommon = in.MonitoringCommon if in.Props != nil { out.Props = in.Props.DeepCopyMonitoringPorps() } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Monitoring. func (in *Monitoring) DeepCopy() *Monitoring { if in == nil { return nil } out := new(Monitoring) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new api.Object. func (in *Monitoring) DeepCopyObject() api.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *MonitoringCommon) DeepCopyInto(out *MonitoringCommon) { *out = *in return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MonitoringCommon. func (in *MonitoringCommon) DeepCopy() *MonitoringCommon { if in == nil { return nil } out := new(MonitoringCommon) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *MonitoringEndpoint) DeepCopyInto(out *MonitoringEndpoint) { *out = *in if in.Monitoring != nil { in, out := &in.Monitoring, &out.Monitoring *out = new(Monitoring) (*in).DeepCopyInto(*out) } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MonitoringEndpoint. func (in *MonitoringEndpoint) DeepCopy() *MonitoringEndpoint { if in == nil { return nil } out := new(MonitoringEndpoint) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *MonitoringList) DeepCopyInto(out *MonitoringList) { *out = *in out.AttributeMeta = in.AttributeMeta if in.Items != nil { in, out := &in.Items, &out.Items *out = make([]Monitoring, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MonitoringList. func (in *MonitoringList) DeepCopy() *MonitoringList { if in == nil { return nil } out := new(MonitoringList) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new api.Object. func (in *MonitoringList) DeepCopyObject() api.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *MonitoringPorpsCommon) DeepCopyInto(out *MonitoringPorpsCommon) { *out = *in return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MonitoringPorpsCommon. func (in *MonitoringPorpsCommon) DeepCopy() *MonitoringPorpsCommon { if in == nil { return nil } out := new(MonitoringPorpsCommon) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *MonitoringPorpsHTTP) DeepCopyInto(out *MonitoringPorpsHTTP) { *out = *in out.MonitoringPorpsCommon = in.MonitoringPorpsCommon if in.StatusCode != nil { in, out := &in.StatusCode, &out.StatusCode *out = make([]string, len(*in)) copy(*out, *in) } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MonitoringPorpsHTTP. func (in *MonitoringPorpsHTTP) DeepCopy() *MonitoringPorpsHTTP { if in == nil { return nil } out := new(MonitoringPorpsHTTP) in.DeepCopyInto(out) return out } // DeepCopyMonitoringPorps is an autogenerated deepcopy function, copying the receiver, creating a new MonitoringPorps. func (in *MonitoringPorpsHTTP) DeepCopyMonitoringPorps() MonitoringPorps { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *MonitoringPorpsHeader) DeepCopyInto(out *MonitoringPorpsHeader) { *out = *in return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MonitoringPorpsHeader. func (in *MonitoringPorpsHeader) DeepCopy() *MonitoringPorpsHeader { if in == nil { return nil } out := new(MonitoringPorpsHeader) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *MonitoringPorpsPING) DeepCopyInto(out *MonitoringPorpsPING) { *out = *in out.MonitoringPorpsCommon = in.MonitoringPorpsCommon return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MonitoringPorpsPING. func (in *MonitoringPorpsPING) DeepCopy() *MonitoringPorpsPING { if in == nil { return nil } out := new(MonitoringPorpsPING) in.DeepCopyInto(out) return out } // DeepCopyMonitoringPorps is an autogenerated deepcopy function, copying the receiver, creating a new MonitoringPorps. func (in *MonitoringPorpsPING) DeepCopyMonitoringPorps() MonitoringPorps { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *MonitoringPorpsStatic) DeepCopyInto(out *MonitoringPorpsStatic) { *out = *in return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MonitoringPorpsStatic. func (in *MonitoringPorpsStatic) DeepCopy() *MonitoringPorpsStatic { if in == nil { return nil } out := new(MonitoringPorpsStatic) in.DeepCopyInto(out) return out } // DeepCopyMonitoringPorps is an autogenerated deepcopy function, copying the receiver, creating a new MonitoringPorps. func (in *MonitoringPorpsStatic) DeepCopyMonitoringPorps() MonitoringPorps { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *MonitoringPorpsTCP) DeepCopyInto(out *MonitoringPorpsTCP) { *out = *in out.MonitoringPorpsCommon = in.MonitoringPorpsCommon return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MonitoringPorpsTCP. func (in *MonitoringPorpsTCP) DeepCopy() *MonitoringPorpsTCP { if in == nil { return nil } out := new(MonitoringPorpsTCP) in.DeepCopyInto(out) return out } // DeepCopyMonitoringPorps is an autogenerated deepcopy function, copying the receiver, creating a new MonitoringPorps. func (in *MonitoringPorpsTCP) DeepCopyMonitoringPorps() MonitoringPorps { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Rule) DeepCopyInto(out *Rule) { *out = *in out.AttributeMeta = in.AttributeMeta if in.Methods != nil { in, out := &in.Methods, &out.Methods *out = make([]RuleMethod, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Rule. func (in *Rule) DeepCopy() *Rule { if in == nil { return nil } out := new(Rule) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new api.Object. func (in *Rule) DeepCopyObject() api.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *RuleAttributeMeta) DeepCopyInto(out *RuleAttributeMeta) { *out = *in out.AttributeMeta = in.AttributeMeta return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new RuleAttributeMeta. func (in *RuleAttributeMeta) DeepCopy() *RuleAttributeMeta { if in == nil { return nil } out := new(RuleAttributeMeta) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *RuleList) DeepCopyInto(out *RuleList) { *out = *in out.AttributeMeta = in.AttributeMeta out.Count = in.Count if in.Items != nil { in, out := &in.Items, &out.Items *out = make([]Rule, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new RuleList. func (in *RuleList) DeepCopy() *RuleList { if in == nil { return nil } out := new(RuleList) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new api.Object. func (in *RuleList) DeepCopyObject() api.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *RuleMethod) DeepCopyInto(out *RuleMethod) { *out = *in out.RuleAttributeMeta = in.RuleAttributeMeta if in.Priority != nil { in, out := &in.Priority, &out.Priority *out = new(uint) **out = **in } if in.Method != nil { out.Method = in.Method.DeepCopyRuleMethodProps() } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new RuleMethod. func (in *RuleMethod) DeepCopy() *RuleMethod { if in == nil { return nil } out := new(RuleMethod) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new api.Object. func (in *RuleMethod) DeepCopyObject() api.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *RuleMethodEntryA) DeepCopyInto(out *RuleMethodEntryA) { *out = *in out.RuleMethodPropsCommon = in.RuleMethodPropsCommon return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new RuleMethodEntryA. func (in *RuleMethodEntryA) DeepCopy() *RuleMethodEntryA { if in == nil { return nil } out := new(RuleMethodEntryA) in.DeepCopyInto(out) return out } // DeepCopyRuleMethodProps is an autogenerated deepcopy function, copying the receiver, creating a new RuleMethodProps. func (in *RuleMethodEntryA) DeepCopyRuleMethodProps() RuleMethodProps { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *RuleMethodEntryAAAA) DeepCopyInto(out *RuleMethodEntryAAAA) { *out = *in out.RuleMethodPropsCommon = in.RuleMethodPropsCommon return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new RuleMethodEntryAAAA. func (in *RuleMethodEntryAAAA) DeepCopy() *RuleMethodEntryAAAA { if in == nil { return nil } out := new(RuleMethodEntryAAAA) in.DeepCopyInto(out) return out } // DeepCopyRuleMethodProps is an autogenerated deepcopy function, copying the receiver, creating a new RuleMethodProps. func (in *RuleMethodEntryAAAA) DeepCopyRuleMethodProps() RuleMethodProps { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *RuleMethodEntryCNAME) DeepCopyInto(out *RuleMethodEntryCNAME) { *out = *in out.RuleMethodPropsCommon = in.RuleMethodPropsCommon return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new RuleMethodEntryCNAME. func (in *RuleMethodEntryCNAME) DeepCopy() *RuleMethodEntryCNAME { if in == nil { return nil } out := new(RuleMethodEntryCNAME) in.DeepCopyInto(out) return out } // DeepCopyRuleMethodProps is an autogenerated deepcopy function, copying the receiver, creating a new RuleMethodProps. func (in *RuleMethodEntryCNAME) DeepCopyRuleMethodProps() RuleMethodProps { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *RuleMethodExitSite) DeepCopyInto(out *RuleMethodExitSite) { *out = *in out.RuleMethodPropsCommon = in.RuleMethodPropsCommon return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new RuleMethodExitSite. func (in *RuleMethodExitSite) DeepCopy() *RuleMethodExitSite { if in == nil { return nil } out := new(RuleMethodExitSite) in.DeepCopyInto(out) return out } // DeepCopyRuleMethodProps is an autogenerated deepcopy function, copying the receiver, creating a new RuleMethodProps. func (in *RuleMethodExitSite) DeepCopyRuleMethodProps() RuleMethodProps { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *RuleMethodExitSorry) DeepCopyInto(out *RuleMethodExitSorry) { *out = *in out.RuleMethodPropsCommon = in.RuleMethodPropsCommon return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new RuleMethodExitSorry. func (in *RuleMethodExitSorry) DeepCopy() *RuleMethodExitSorry { if in == nil { return nil } out := new(RuleMethodExitSorry) in.DeepCopyInto(out) return out } // DeepCopyRuleMethodProps is an autogenerated deepcopy function, copying the receiver, creating a new RuleMethodProps. func (in *RuleMethodExitSorry) DeepCopyRuleMethodProps() RuleMethodProps { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *RuleMethodFailover) DeepCopyInto(out *RuleMethodFailover) { *out = *in out.RuleMethodPropsCommon = in.RuleMethodPropsCommon return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new RuleMethodFailover. func (in *RuleMethodFailover) DeepCopy() *RuleMethodFailover { if in == nil { return nil } out := new(RuleMethodFailover) in.DeepCopyInto(out) return out } // DeepCopyRuleMethodProps is an autogenerated deepcopy function, copying the receiver, creating a new RuleMethodProps. func (in *RuleMethodFailover) DeepCopyRuleMethodProps() RuleMethodProps { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *RuleMethodList) DeepCopyInto(out *RuleMethodList) { *out = *in out.RuleAttributeMeta = in.RuleAttributeMeta if in.Items != nil { in, out := &in.Items, &out.Items *out = make([]RuleMethod, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new RuleMethodList. func (in *RuleMethodList) DeepCopy() *RuleMethodList { if in == nil { return nil } out := new(RuleMethodList) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new api.Object. func (in *RuleMethodList) DeepCopyObject() api.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *RuleMethodPropsCommon) DeepCopyInto(out *RuleMethodPropsCommon) { *out = *in return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new RuleMethodPropsCommon. func (in *RuleMethodPropsCommon) DeepCopy() *RuleMethodPropsCommon { if in == nil { return nil } out := new(RuleMethodPropsCommon) in.DeepCopyInto(out) return out } // DeepCopyRuleMethodProps is an autogenerated deepcopy function, copying the receiver, creating a new RuleMethodProps. func (in *RuleMethodPropsCommon) DeepCopyRuleMethodProps() RuleMethodProps { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Site) DeepCopyInto(out *Site) { *out = *in out.AttributeMeta = in.AttributeMeta if in.Endpoints != nil { in, out := &in.Endpoints, &out.Endpoints *out = make([]Endpoint, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Site. func (in *Site) DeepCopy() *Site { if in == nil { return nil } out := new(Site) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new api.Object. func (in *Site) DeepCopyObject() api.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *SiteAttributeMeta) DeepCopyInto(out *SiteAttributeMeta) { *out = *in out.AttributeMeta = in.AttributeMeta return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SiteAttributeMeta. func (in *SiteAttributeMeta) DeepCopy() *SiteAttributeMeta { if in == nil { return nil } out := new(SiteAttributeMeta) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *SiteList) DeepCopyInto(out *SiteList) { *out = *in out.AttributeMeta = in.AttributeMeta out.Count = in.Count if in.Items != nil { in, out := &in.Items, &out.Items *out = make([]Site, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SiteList. func (in *SiteList) DeepCopy() *SiteList { if in == nil { return nil } out := new(SiteList) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new api.Object. func (in *SiteList) DeepCopyObject() api.Object { if c := in.DeepCopy(); c != nil { return c } return nil } golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/lb_domains/common.go000066400000000000000000000036171437707610400230720ustar00rootroot00000000000000package lb_domains import ( "fmt" "net/http" "github.com/mimuret/golang-iij-dpf/pkg/api" "github.com/mimuret/golang-iij-dpf/pkg/apis" "github.com/mimuret/golang-iij-dpf/pkg/schema" ) const groupName = "lb-domains.api.dns-platform.jp/v1" func register(items ...apis.Spec) { schema.NewRegister(groupName).Add(items...) } type Spec interface { api.Spec apis.Params GetLBDoaminID() string SetLBDoaminID(string) } type ChildSpec interface { Spec GetResourceName() string SetResourceName(string) } type ListSpec interface { api.ListSpec Spec } type CountableListSpec interface { api.CountableListSpec Spec } type AttributeMeta struct { LBDomainID string } func (s *AttributeMeta) GetGroup() string { return groupName } func (s *AttributeMeta) GetLBDoaminID() string { return s.LBDomainID } func (s *AttributeMeta) SetLBDoaminID(id string) { s.LBDomainID = id } func GetPathMethodForChildSpec(action api.Action, s ChildSpec) (string, string) { switch action { case api.ActionCreate: return action.ToMethod(), fmt.Sprintf("/lb_domains/%s/%s", s.GetLBDoaminID(), s.GetName()) case api.ActionRead, api.ActionUpdate, api.ActionDelete: return action.ToMethod(), fmt.Sprintf("/lb_domains/%s/%s/%s", s.GetLBDoaminID(), s.GetName(), s.GetResourceName()) } return "", "" } func GetPathMethodForListSpec(action api.Action, s ListSpec) (string, string) { if action == api.ActionList { return http.MethodGet, fmt.Sprintf("/lb_domains/%s/%s", s.GetLBDoaminID(), s.GetName()) } return "", "" } func GetPathMethodForCountableListSpec(action api.Action, s ListSpec) (string, string) { switch action { case api.ActionList: return http.MethodGet, fmt.Sprintf("/lb_domains/%s/%s", s.GetLBDoaminID(), s.GetName()) case api.ActionCount: if _, ok := s.(api.CountableListSpec); ok { return http.MethodGet, fmt.Sprintf("/lb_domains/%s/%s/count", s.GetLBDoaminID(), s.GetName()) } } return "", "" } golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/lb_domains/common_test.go000066400000000000000000000030221437707610400241170ustar00rootroot00000000000000package lb_domains_test import ( "github.com/mimuret/golang-iij-dpf/pkg/apis/dpf/v1/lb_domains" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("lb_domains", func() { Context("AttributeMeta", func() { var meta lb_domains.AttributeMeta BeforeEach(func() { meta = lb_domains.AttributeMeta{} }) Context("GetGroup", func() { It("returns lb_domains", func() { Expect(meta.GetGroup()).To(Equal("lb-domains.api.dns-platform.jp/v1")) }) }) Context("GetLBDoaminID", func() { When("default", func() { It("returns ", func() { Expect(meta.GetLBDoaminID()).To(Equal("")) }) }) When("default", func() { BeforeEach(func() { meta.LBDomainID = "id1" }) It("returns ContractID", func() { Expect(meta.GetLBDoaminID()).To(Equal("id1")) }) }) Context("SetLBDoaminID", func() { BeforeEach(func() { meta.SetLBDoaminID("id2") }) It("can set ContractID", func() { Expect(meta.GetLBDoaminID()).To(Equal("id2")) }) }) Context("DeepCopy", func() { var ( copy *lb_domains.AttributeMeta nilMeta *lb_domains.AttributeMeta ) When("AttributeMeta is not nil", func() { BeforeEach(func() { copy = meta.DeepCopy() }) It("returns copy ", func() { Expect(copy).To(Equal(&meta)) }) }) When("AttributeMeta is nil", func() { BeforeEach(func() { copy = nilMeta.DeepCopy() }) It("returns copy ", func() { Expect(copy).To(BeNil()) }) }) }) }) }) }) golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/lb_domains/config.go000066400000000000000000000024051437707610400230410ustar00rootroot00000000000000package lb_domains import ( "fmt" "net/http" "github.com/mimuret/golang-iij-dpf/pkg/api" "github.com/mimuret/golang-iij-dpf/pkg/apis" ) var _ Spec = &Config{} // +k8s:deepcopy-gen:interfaces=github.com/mimuret/golang-iij-dpf/pkg/api.Object type Config struct { AttributeMeta Monitorings []Monitoring `read:"monitorings" apply:"monitorings"` Sites []Site `read:"sites" apply:"sites"` Rules []Rule `read:"rules" apply:"rules"` } func (c *Config) Init() { for i := range c.Monitorings { c.Monitorings[i].AttributeMeta = c.AttributeMeta } for i := range c.Sites { c.Sites[i].AttributeMeta = c.AttributeMeta c.Sites[i].Init() } for i := range c.Rules { c.Rules[i].AttributeMeta = c.AttributeMeta c.Rules[i].Init() } } func (c *Config) GetName() string { return "sites" } func (c *Config) GetPathMethod(action api.Action) (string, string) { switch action { case api.ActionApply: return http.MethodPut, fmt.Sprintf("/lb_domains/%s/config", c.GetLBDoaminID()) case api.ActionRead: return action.ToMethod(), fmt.Sprintf("/lb_domains/%s/config", c.GetLBDoaminID()) } return "", "" } func (c *Config) SetPathParams(args ...interface{}) error { return apis.SetPathParams(args, &c.LBDomainID) } func init() { register(&Config{}) } golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/lb_domains/config_test.go000066400000000000000000000236221437707610400241040ustar00rootroot00000000000000package lb_domains_test import ( "context" _ "embed" "net/http" "github.com/jarcoal/httpmock" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/mimuret/golang-iij-dpf/pkg/apis/dpf/v1/lb_domains" "github.com/mimuret/golang-iij-dpf/pkg/testtool" ) //go:embed testdata/config_get.json var configReadJson []byte //go:embed testdata/config_put.json var configUpdateJson []byte var _ = Describe("Config", func() { var ( c lb_domains.Config cl *testtool.TestClient err error reqId string s1 lb_domains.Config ) BeforeEach(func() { cl = testtool.NewTestClient("", "http://localhost", nil) s1 = lb_domains.Config{ AttributeMeta: lb_domains.AttributeMeta{ LBDomainID: "b0000000000001", }, Sites: []lb_domains.Site{ { AttributeMeta: lb_domains.AttributeMeta{ LBDomainID: "b0000000000001", }, ResourceName: "site-a", Name: "site(A)", Description: "site(A) comment", RRType: lb_domains.SiteRRTypeA, LiveStatus: lb_domains.StatusDown, Endpoints: []lb_domains.Endpoint{ { SiteAttributeMeta: lb_domains.SiteAttributeMeta{ AttributeMeta: lb_domains.AttributeMeta{ LBDomainID: "b0000000000001", }, SiteResourceName: "site-a", }, ResourceName: "endpoint-1", Name: "host-1", MonitoringTarget: "www.example.jp.", Description: "endpoint#1", Weight: 1, ManualFaillback: false, ManualFaillOver: false, Enabled: false, LiveStatus: lb_domains.StatusUp, ReadyStatus: lb_domains.StatusDown, Rdata: []lb_domains.EndpointRdata{{Value: "192.168.0.1"}, {Value: "192.168.1.1"}}, Monitorings: []lb_domains.MonitoringEndpoint{ { MonitoringResourceName: "id1", Enabled: true, Monitoring: &lb_domains.Monitoring{ AttributeMeta: lb_domains.AttributeMeta{ LBDomainID: "b0000000000001", }, MonitoringCommon: lb_domains.MonitoringCommon{ ResourceName: "id1", Name: "monitoring-1", MType: lb_domains.MonitoringMtypePing, Description: "comment 1", }, Props: &lb_domains.MonitoringPorpsPING{ MonitoringPorpsCommon: lb_domains.MonitoringPorpsCommon{ Location: lb_domains.MonitoringPropsLocationAll, Interval: 30, Holdtime: 0, Timeout: 1, }, }, }, }, }, }, }, }, { AttributeMeta: lb_domains.AttributeMeta{ LBDomainID: "b0000000000001", }, ResourceName: "site-aaaa", Name: "site(AAAA)", Description: "site(AAAA) comment", RRType: lb_domains.SiteRRTypeAAAA, LiveStatus: lb_domains.StatusUp, Endpoints: []lb_domains.Endpoint{ { SiteAttributeMeta: lb_domains.SiteAttributeMeta{ AttributeMeta: lb_domains.AttributeMeta{ LBDomainID: "b0000000000001", }, SiteResourceName: "site-aaaa", }, ResourceName: "endpoint-2", Name: "host-2", MonitoringTarget: "2001:db8::1", Description: "endpoint#2", Weight: 255, ManualFaillback: true, ManualFaillOver: true, Enabled: true, LiveStatus: lb_domains.StatusDown, ReadyStatus: lb_domains.StatusDown, Rdata: []lb_domains.EndpointRdata{{Value: "2001:db8::1"}, {Value: "2001:db8::2"}}, Monitorings: []lb_domains.MonitoringEndpoint{ { MonitoringResourceName: "id1", Enabled: true, Monitoring: &lb_domains.Monitoring{ AttributeMeta: lb_domains.AttributeMeta{ LBDomainID: "b0000000000001", }, MonitoringCommon: lb_domains.MonitoringCommon{ ResourceName: "id1", Name: "monitoring-1", MType: lb_domains.MonitoringMtypePing, Description: "comment 1", }, Props: &lb_domains.MonitoringPorpsPING{ MonitoringPorpsCommon: lb_domains.MonitoringPorpsCommon{ Location: lb_domains.MonitoringPropsLocationAll, Interval: 30, Holdtime: 0, Timeout: 1, }, }, }, }, }, }, }, }, }, Monitorings: []lb_domains.Monitoring{ { AttributeMeta: lb_domains.AttributeMeta{ LBDomainID: "b0000000000001", }, MonitoringCommon: lb_domains.MonitoringCommon{ ResourceName: "id1", Name: "monitoring-1", MType: lb_domains.MonitoringMtypePing, Description: "comment 1", }, Props: &lb_domains.MonitoringPorpsPING{ MonitoringPorpsCommon: lb_domains.MonitoringPorpsCommon{ Location: lb_domains.MonitoringPropsLocationAll, Interval: 30, Holdtime: 0, Timeout: 1, }, }, }, }, Rules: []lb_domains.Rule{ { AttributeMeta: lb_domains.AttributeMeta{ LBDomainID: "b0000000000001", }, ResourceName: "rule-a", Name: "default", Description: "default rule", Methods: []lb_domains.RuleMethod{ { RuleAttributeMeta: lb_domains.RuleAttributeMeta{ AttributeMeta: lb_domains.AttributeMeta{ LBDomainID: "b0000000000001", }, RuleResourceName: "rule-a", }, Method: &lb_domains.RuleMethodEntryA{ lb_domains.RuleMethodPropsCommon{ ResourceName: "entry-a-1", MType: lb_domains.RuleMethodMTypeEntryA, Enabled: true, LiveStatus: lb_domains.StatusUp, ReadyStatus: lb_domains.StatusDown, }, }, }, { RuleAttributeMeta: lb_domains.RuleAttributeMeta{ AttributeMeta: lb_domains.AttributeMeta{ LBDomainID: "b0000000000001", }, RuleResourceName: "rule-a", }, Method: &lb_domains.RuleMethodEntryAAAA{ lb_domains.RuleMethodPropsCommon{ ResourceName: "entry-aaaa-1", MType: lb_domains.RuleMethodMTypeEntryAAAA, Enabled: true, LiveStatus: lb_domains.StatusUp, ReadyStatus: lb_domains.StatusDown, }, }, }, { RuleAttributeMeta: lb_domains.RuleAttributeMeta{ AttributeMeta: lb_domains.AttributeMeta{ LBDomainID: "b0000000000001", }, RuleResourceName: "rule-a", }, Method: &lb_domains.RuleMethodExitSite{ RuleMethodPropsCommon: lb_domains.RuleMethodPropsCommon{ ResourceName: "exit-a-1", MType: lb_domains.RuleMethodMTypeExitSite, Enabled: true, LiveStatus: lb_domains.StatusUp, ReadyStatus: lb_domains.StatusDown, }, ParentResourceName: "entry-a-1", SiteResourceName: "site-a", }, }, { RuleAttributeMeta: lb_domains.RuleAttributeMeta{ AttributeMeta: lb_domains.AttributeMeta{ LBDomainID: "b0000000000001", }, RuleResourceName: "rule-a", }, Method: &lb_domains.RuleMethodExitSite{ RuleMethodPropsCommon: lb_domains.RuleMethodPropsCommon{ ResourceName: "exit-aaaa-1", MType: lb_domains.RuleMethodMTypeExitSite, Enabled: true, LiveStatus: lb_domains.StatusUp, ReadyStatus: lb_domains.StatusDown, }, ParentResourceName: "entry-aaaa-1", SiteResourceName: "site-aaaa", }, }, }, }, }, } }) Describe("Config", func() { Context("Read", func() { BeforeEach(func() { httpmock.RegisterResponder(http.MethodGet, "http://localhost/lb_domains/b0000000000001/config", httpmock.NewBytesResponder(200, configReadJson)) }) AfterEach(func() { httpmock.Reset() }) When("returns LBDomain m1", func() { BeforeEach(func() { c = lb_domains.Config{ AttributeMeta: lb_domains.AttributeMeta{ LBDomainID: "b0000000000001", }, } reqId, err = cl.Read(context.Background(), &c) }) It("returns normal", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal("76D7462F50E3417C96898A827E0D1EC1")) Expect(c.Sites).To(Equal(s1.Sites)) Expect(c.Monitorings).To(Equal(s1.Monitorings)) Expect(c.Rules).To(Equal(s1.Rules)) }) }) }) Context("Apply", func() { id1, bs1 := testtool.CreateAsyncResponse() BeforeEach(func() { httpmock.RegisterResponder(http.MethodPut, "http://localhost/lb_domains/b0000000000001/config", httpmock.NewBytesResponder(202, bs1)) reqId, err = cl.Apply(context.Background(), &s1, nil) }) AfterEach(func() { httpmock.Reset() }) It("returns job_id", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal(id1)) }) It("post json", func() { Expect(cl.RequestBody["/lb_domains/b0000000000001/config"]).To(MatchJSON(configUpdateJson)) }) }) Context("SetPathParams", func() { When("no arguments, nothing to do", func() { BeforeEach(func() { err = s1.SetPathParams() }) It("returns error", func() { Expect(err).To(Succeed()) }) }) When("enough arguments", func() { BeforeEach(func() { err = s1.SetPathParams("b0000000000010") }) It("not returns error", func() { Expect(err).To(Succeed()) }) It("can set LBDomainID", func() { Expect(s1.LBDomainID).To(Equal("b0000000000010")) }) }) When("arguments has extra value", func() { BeforeEach(func() { err = s1.SetPathParams("b0000000000010", 2) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) When("arguments type missmatch", func() { BeforeEach(func() { err = s1.SetPathParams(2) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) }) }) }) golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/lb_domains/doc.go000066400000000000000000000000611437707610400223350ustar00rootroot00000000000000package lb_domains // +k8s:deepcopy-gen=package golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/lb_domains/endpoint.go000066400000000000000000000111221437707610400234100ustar00rootroot00000000000000package lb_domains import ( "fmt" "net/http" "github.com/mimuret/golang-iij-dpf/pkg/api" "github.com/mimuret/golang-iij-dpf/pkg/apis" ) var _ ChildSpec = &Site{} type SiteAttributeMeta struct { AttributeMeta SiteResourceName string } type MonitoringEndpoint struct { MonitoringResourceName string `update:"resource_name" create:"resource_name" apply:"resource_name"` Enabled bool `create:"enabled" update:"enabled" apply:"enabled"` Monitoring *Monitoring } func (m *MonitoringEndpoint) UnmarshalJSON(bs []byte) error { enabled := struct { Enabled bool `read:"enabled"` }{} var monitoring Monitoring if err := api.UnmarshalRead(bs, &enabled); err != nil { return fmt.Errorf("failed to parse MonitoringEndpoint") } if err := api.UnmarshalRead(bs, &monitoring); err != nil { return fmt.Errorf("failed to parse MonitoringEndpoint") } m.MonitoringResourceName = monitoring.ResourceName m.Enabled = enabled.Enabled m.Monitoring = &monitoring return nil } type EndpointRdata struct { Value string `read:"value" create:"value" update:"value" apply:"value"` } // +k8s:deepcopy-gen:interfaces=github.com/mimuret/golang-iij-dpf/pkg/api.Object type Endpoint struct { SiteAttributeMeta ResourceName string `read:"resource_name" create:"resource_name,omitempty" apply:"resource_name"` Name string `read:"name" create:"name" update:"name" apply:"name"` MonitoringTarget string `read:"monitoring_target" create:"monitoring_target" update:"monitoring_target" apply:"monitoring_target"` Description string `read:"description" create:"description" update:"description" apply:"description"` Weight uint8 `read:"weight" create:"weight" update:"weight" apply:"weight"` ManualFaillback bool `read:"manual_failback" create:"manual_failback" update:"manual_failback" apply:"manual_failback"` ManualFaillOver bool `read:"manual_failover" create:"manual_failover" update:"manual_failover" apply:"manual_failover"` Enabled bool `read:"enabled" create:"enabled" update:"enabled" apply:"enabled"` LiveStatus Status `read:"live_status"` ReadyStatus Status `read:"ready_status"` Rdata []EndpointRdata `read:"rdata" create:"rdata" update:"rdata" apply:"rdata"` Monitorings []MonitoringEndpoint `read:"monitorings" create:"monitorings" update:"monitorings" apply:"monitorings"` } func (c *Endpoint) Fix() { if c.Weight == 0 { c.Weight = uint8(1) } } func (c *Endpoint) Init() { for i := range c.Monitorings { if c.Monitorings[i].Monitoring != nil { c.Monitorings[i].Monitoring.AttributeMeta = c.AttributeMeta } } } func (c *Endpoint) GetName() string { return "endpoints" } func (c *Endpoint) GetResourceName() string { return c.ResourceName } func (c *Endpoint) SetResourceName(resourceName string) { c.ResourceName = resourceName } func (c *Endpoint) GetPathMethod(action api.Action) (string, string) { switch action { case api.ActionCreate: return action.ToMethod(), fmt.Sprintf("/lb_domains/%s/sites/%s/endpoints", c.GetLBDoaminID(), c.SiteResourceName) case api.ActionRead, api.ActionUpdate, api.ActionDelete: return action.ToMethod(), fmt.Sprintf("/lb_domains/%s/sites/%s/endpoints/%s", c.GetLBDoaminID(), c.SiteResourceName, c.ResourceName) } return "", "" } func (c *Endpoint) SetPathParams(args ...interface{}) error { return apis.SetPathParams(args, &c.LBDomainID, &c.SiteResourceName, &c.ResourceName) } var _ ListSpec = &EndpointList{} // +k8s:deepcopy-gen:interfaces=github.com/mimuret/golang-iij-dpf/pkg/api.Object type EndpointList struct { SiteAttributeMeta Items []Endpoint `read:"items"` } func (c *EndpointList) GetName() string { return "endpoints" } func (c *EndpointList) GetItems() interface{} { return &c.Items } func (c *EndpointList) Len() int { return len(c.Items) } func (c *EndpointList) Index(i int) interface{} { return c.Items[i] } func (c *EndpointList) GetPathMethod(action api.Action) (string, string) { if action == api.ActionList { return http.MethodGet, fmt.Sprintf("/lb_domains/%s/sites/%s/endpoints", c.GetLBDoaminID(), c.SiteResourceName) } return "", "" } func (c *EndpointList) Init() { for i := range c.Items { c.Items[i].SiteAttributeMeta = c.SiteAttributeMeta c.Items[i].Init() } } func (c *EndpointList) SetPathParams(args ...interface{}) error { return apis.SetPathParams(args, &c.LBDomainID, &c.SiteResourceName) } func init() { register(&Endpoint{}, &EndpointList{}) } golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/lb_domains/endpoint_manual_operation.go000066400000000000000000000031541437707610400270330ustar00rootroot00000000000000package lb_domains import ( "fmt" "net/http" "github.com/mimuret/golang-iij-dpf/pkg/api" "github.com/mimuret/golang-iij-dpf/pkg/apis" ) var _ ChildSpec = &Site{} // +k8s:deepcopy-gen:interfaces=github.com/mimuret/golang-iij-dpf/pkg/api.Object type EndpointManualFailover struct { SiteAttributeMeta EndpointResourceName string } func (c *EndpointManualFailover) GetName() string { return "failover" } func (c *EndpointManualFailover) GetPathMethod(action api.Action) (string, string) { if action == api.ActionApply { return http.MethodPost, fmt.Sprintf("/lb_domains/%s/sites/%s/endpoints/%s/failover", c.LBDomainID, c.SiteResourceName, c.EndpointResourceName) } return "", "" } func (c *EndpointManualFailover) SetPathParams(args ...interface{}) error { return apis.SetPathParams(args, &c.LBDomainID, &c.SiteResourceName, &c.EndpointResourceName) } // +k8s:deepcopy-gen:interfaces=github.com/mimuret/golang-iij-dpf/pkg/api.Object type EndpointManualFailback struct { SiteAttributeMeta EndpointResourceName string } func (c *EndpointManualFailback) GetName() string { return "failback" } func (c *EndpointManualFailback) GetPathMethod(action api.Action) (string, string) { if action == api.ActionApply { return http.MethodPost, fmt.Sprintf("/lb_domains/%s/sites/%s/endpoints/%s/failback", c.LBDomainID, c.SiteResourceName, c.EndpointResourceName) } return "", "" } func (c *EndpointManualFailback) SetPathParams(args ...interface{}) error { return apis.SetPathParams(args, &c.LBDomainID, &c.SiteResourceName, &c.EndpointResourceName) } func init() { register(&EndpointManualFailover{}, &EndpointManualFailback{}) } golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/lb_domains/endpoint_manual_operation_test.go000066400000000000000000000112741437707610400300740ustar00rootroot00000000000000package lb_domains_test import ( "context" "net/http" "github.com/jarcoal/httpmock" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/mimuret/golang-iij-dpf/pkg/apis/dpf/v1/lb_domains" "github.com/mimuret/golang-iij-dpf/pkg/testtool" ) var _ = Describe("EndpointManualFailover", func() { var ( cl *testtool.TestClient err error reqId string ) Describe("EndpointManualFailover", func() { var s1 lb_domains.EndpointManualFailover BeforeEach(func() { cl = testtool.NewTestClient("", "http://localhost", nil) s1 = lb_domains.EndpointManualFailover{ SiteAttributeMeta: lb_domains.SiteAttributeMeta{ AttributeMeta: lb_domains.AttributeMeta{ LBDomainID: "b0000000000001", }, SiteResourceName: "site-1", }, EndpointResourceName: "endpoint-1", } }) Context("Apply", func() { id1, bs1 := testtool.CreateAsyncResponse() BeforeEach(func() { httpmock.RegisterResponder(http.MethodPost, "http://localhost/lb_domains/b0000000000001/sites/site-1/endpoints/endpoint-1/failover", httpmock.NewBytesResponder(202, bs1)) reqId, err = cl.Apply(context.Background(), &s1, nil) }) AfterEach(func() { httpmock.Reset() }) It("returns job_id", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal(id1)) }) It("post json", func() { Expect(cl.RequestBody["/lb_domains/b0000000000001/sites/site-1/endpoints/endpoint-1/failover"]).To(MatchJSON(`{}`)) }) }) Context("SetPathParams", func() { When("no arguments, nothing to do", func() { BeforeEach(func() { err = s1.SetPathParams() }) It("returns error", func() { Expect(err).To(Succeed()) }) }) When("enough arguments", func() { BeforeEach(func() { err = s1.SetPathParams("b0000000000010", "site-1", "endpoint-1") }) It("not returns error", func() { Expect(err).To(Succeed()) }) It("can set LBDomainID", func() { Expect(s1.LBDomainID).To(Equal("b0000000000010")) Expect(s1.SiteResourceName).To(Equal("site-1")) Expect(s1.EndpointResourceName).To(Equal("endpoint-1")) }) }) When("arguments has extra value", func() { BeforeEach(func() { err = s1.SetPathParams("b0000000000010", "site-1", "endpoint-1", 1) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) When("arguments type missmatch", func() { BeforeEach(func() { err = s1.SetPathParams("b0000000000010", "site-1", 1) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) }) }) Describe("EndpointManualFailback", func() { var s1 lb_domains.EndpointManualFailback BeforeEach(func() { cl = testtool.NewTestClient("", "http://localhost", nil) s1 = lb_domains.EndpointManualFailback{ SiteAttributeMeta: lb_domains.SiteAttributeMeta{ AttributeMeta: lb_domains.AttributeMeta{ LBDomainID: "b0000000000001", }, SiteResourceName: "site-1", }, EndpointResourceName: "endpoint-1", } }) Context("Apply", func() { id1, bs1 := testtool.CreateAsyncResponse() BeforeEach(func() { httpmock.RegisterResponder(http.MethodPost, "http://localhost/lb_domains/b0000000000001/sites/site-1/endpoints/endpoint-1/failback", httpmock.NewBytesResponder(202, bs1)) reqId, err = cl.Apply(context.Background(), &s1, nil) }) AfterEach(func() { httpmock.Reset() }) It("returns job_id", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal(id1)) }) It("post json", func() { Expect(cl.RequestBody["/lb_domains/b0000000000001/sites/site-1/endpoints/endpoint-1/failback"]).To(MatchJSON(`{}`)) }) }) Context("SetPathParams", func() { When("no arguments, nothing to do", func() { BeforeEach(func() { err = s1.SetPathParams() }) It("returns error", func() { Expect(err).To(Succeed()) }) }) When("enough arguments", func() { BeforeEach(func() { err = s1.SetPathParams("b0000000000010", "site-1", "endpoint-1") }) It("not returns error", func() { Expect(err).To(Succeed()) }) It("can set LBDomainID", func() { Expect(s1.LBDomainID).To(Equal("b0000000000010")) Expect(s1.SiteResourceName).To(Equal("site-1")) Expect(s1.EndpointResourceName).To(Equal("endpoint-1")) }) }) When("arguments has extra value", func() { BeforeEach(func() { err = s1.SetPathParams("b0000000000010", "site-1", "endpoint-1", 1) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) When("arguments type missmatch", func() { BeforeEach(func() { err = s1.SetPathParams("b0000000000010", "site-1", 1) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) }) }) }) golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/lb_domains/endpoint_test.go000066400000000000000000000332061437707610400244560ustar00rootroot00000000000000package lb_domains_test import ( "context" "net/http" "github.com/jarcoal/httpmock" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" api "github.com/mimuret/golang-iij-dpf/pkg/api" "github.com/mimuret/golang-iij-dpf/pkg/apis/dpf/v1/lb_domains" "github.com/mimuret/golang-iij-dpf/pkg/testtool" ) var _ = Describe("Endpoint", func() { var ( c lb_domains.Endpoint cl *testtool.TestClient err error reqId string s1, s2 lb_domains.Endpoint slist lb_domains.EndpointList ) BeforeEach(func() { cl = testtool.NewTestClient("", "http://localhost", nil) s1 = lb_domains.Endpoint{ SiteAttributeMeta: lb_domains.SiteAttributeMeta{ AttributeMeta: lb_domains.AttributeMeta{ LBDomainID: "b0000000000001", }, SiteResourceName: "site-1", }, ResourceName: "endpoint-1", Name: "host-1", MonitoringTarget: "www.example.jp.", Description: "endpoint#1", Weight: 1, ManualFaillback: false, ManualFaillOver: false, Enabled: false, LiveStatus: lb_domains.StatusUp, ReadyStatus: lb_domains.StatusDown, Rdata: []lb_domains.EndpointRdata{{Value: "192.168.0.1"}, {Value: "192.168.1.1"}}, Monitorings: []lb_domains.MonitoringEndpoint{ { MonitoringResourceName: "id1", Enabled: true, Monitoring: &lb_domains.Monitoring{ AttributeMeta: lb_domains.AttributeMeta{ LBDomainID: "b0000000000001", }, MonitoringCommon: lb_domains.MonitoringCommon{ ResourceName: "id1", Name: "monitoring-1", MType: lb_domains.MonitoringMtypePing, Description: "comment 1", }, Props: &lb_domains.MonitoringPorpsPING{ MonitoringPorpsCommon: lb_domains.MonitoringPorpsCommon{ Location: lb_domains.MonitoringPropsLocationAll, Interval: 30, Holdtime: 0, Timeout: 1, }, }, }, }, }, } s2 = lb_domains.Endpoint{ SiteAttributeMeta: lb_domains.SiteAttributeMeta{ AttributeMeta: lb_domains.AttributeMeta{ LBDomainID: "b0000000000001", }, SiteResourceName: "site-1", }, ResourceName: "endpoint-2", Name: "host-2", MonitoringTarget: "2001:db8::1", Description: "endpoint#2", Weight: 255, ManualFaillback: true, ManualFaillOver: true, Enabled: true, LiveStatus: lb_domains.StatusDown, ReadyStatus: lb_domains.StatusDown, Rdata: []lb_domains.EndpointRdata{{Value: "192.168.0.2"}, {Value: "192.168.1.2"}}, Monitorings: []lb_domains.MonitoringEndpoint{}, } slist = lb_domains.EndpointList{ SiteAttributeMeta: lb_domains.SiteAttributeMeta{ AttributeMeta: lb_domains.AttributeMeta{ LBDomainID: "b0000000000001", }, SiteResourceName: "site-1", }, Items: []lb_domains.Endpoint{s1, s2}, } }) Describe("Endpoint", func() { Context("Read", func() { BeforeEach(func() { httpmock.RegisterResponder(http.MethodGet, "http://localhost/lb_domains/b0000000000001/sites/site-1/endpoints/endpoint-1", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "76D7462F50E3417C96898A827E0D1EC1", "result": { "resource_name": "endpoint-1", "name": "host-1", "monitoring_target": "www.example.jp.", "description": "endpoint#1", "weight": 1, "manual_failback": false, "manual_failover": false, "enabled": false, "live_status": "up", "ready_status": "down", "rdata": [ { "value": "192.168.0.1" }, { "value": "192.168.1.1" } ], "monitorings": [ { "resource_name": "id1", "enabled": true, "name": "monitoring-1", "mtype": "ping", "description": "comment 1", "props": { "location": "all", "interval": 30, "holdtime": 0, "timeout": 1 } } ] } }`))) httpmock.RegisterResponder(http.MethodGet, "http://localhost/lb_domains/b0000000000001/sites/site-1/endpoints/endpoint-2", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "B10F0042282A46C18BFB440B5B58BF8C", "result": { "resource_name": "endpoint-2", "name": "host-2", "monitoring_target": "2001:db8::1", "description": "endpoint#2", "weight": 255, "manual_failback": true, "manual_failover": true, "enabled": true, "live_status": "down", "ready_status": "down", "rdata": [ { "value": "192.168.0.2" }, { "value": "192.168.1.2" } ], "monitorings": [] } }`))) }) AfterEach(func() { httpmock.Reset() }) When("returns endpoint-1", func() { BeforeEach(func() { c = lb_domains.Endpoint{ SiteAttributeMeta: lb_domains.SiteAttributeMeta{ AttributeMeta: lb_domains.AttributeMeta{ LBDomainID: "b0000000000001", }, SiteResourceName: "site-1", }, ResourceName: "endpoint-1", } reqId, err = cl.Read(context.Background(), &c) }) It("returns normal", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal("76D7462F50E3417C96898A827E0D1EC1")) Expect(c).To(Equal(s1)) }) }) When("returns endpoint-2", func() { BeforeEach(func() { c = lb_domains.Endpoint{ SiteAttributeMeta: lb_domains.SiteAttributeMeta{ AttributeMeta: lb_domains.AttributeMeta{ LBDomainID: "b0000000000001", }, SiteResourceName: "site-1", }, ResourceName: "endpoint-2", } reqId, err = cl.Read(context.Background(), &c) }) It("returns normal", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal("B10F0042282A46C18BFB440B5B58BF8C")) Expect(c).To(Equal(s2)) }) }) }) Context("Create", func() { id1, bs1 := testtool.CreateAsyncResponse() BeforeEach(func() { httpmock.RegisterResponder(http.MethodPost, "http://localhost/lb_domains/b0000000000001/sites/site-1/endpoints", httpmock.NewBytesResponder(202, bs1)) reqId, err = cl.Create(context.Background(), &s1, nil) }) AfterEach(func() { httpmock.Reset() }) It("returns job_id", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal(id1)) }) It("post json", func() { Expect(cl.RequestBody["/lb_domains/b0000000000001/sites/site-1/endpoints"]).To(MatchJSON(`{ "resource_name": "endpoint-1", "name": "host-1", "monitoring_target": "www.example.jp.", "description": "endpoint#1", "weight": 1, "manual_failback": false, "manual_failover": false, "enabled": false, "rdata": [ { "value": "192.168.0.1" }, { "value": "192.168.1.1" } ], "monitorings": [ {"resource_name": "id1", "enabled": true} ] }`)) }) }) Context("Update", func() { id1, bs1 := testtool.CreateAsyncResponse() BeforeEach(func() { httpmock.RegisterResponder(http.MethodPatch, "http://localhost/lb_domains/b0000000000001/sites/site-1/endpoints/endpoint-1", httpmock.NewBytesResponder(202, bs1)) reqId, err = cl.Update(context.Background(), &s1, nil) }) AfterEach(func() { httpmock.Reset() }) It("returns job_id", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal(id1)) }) It("post json", func() { Expect(cl.RequestBody["/lb_domains/b0000000000001/sites/site-1/endpoints/endpoint-1"]).To(MatchJSON(`{ "name": "host-1", "monitoring_target": "www.example.jp.", "description": "endpoint#1", "weight": 1, "manual_failback": false, "manual_failover": false, "enabled": false, "rdata": [ { "value": "192.168.0.1" }, { "value": "192.168.1.1" } ], "monitorings": [ {"resource_name": "id1", "enabled": true} ] }`)) }) }) Context("SetPathParams", func() { When("no arguments, nothing to do", func() { BeforeEach(func() { err = s1.SetPathParams() }) It("returns error", func() { Expect(err).To(Succeed()) }) }) When("enough arguments", func() { BeforeEach(func() { err = s1.SetPathParams("b0000000000010", "site-10", "endpoint-10") }) It("not returns error", func() { Expect(err).To(Succeed()) }) It("can set LBDomainID", func() { Expect(s1.LBDomainID).To(Equal("b0000000000010")) Expect(s1.SiteResourceName).To(Equal("site-10")) Expect(s1.ResourceName).To(Equal("endpoint-10")) }) }) When("arguments has extra value", func() { BeforeEach(func() { err = s1.SetPathParams("b0000000000010", "site-10", "endpoint-10", 0) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) When("arguments type missmatch", func() { BeforeEach(func() { err = s1.SetPathParams("b0000000000010", "site-10", 0) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) }) Context("api.Spec common test", func() { var nilSpec *lb_domains.Endpoint testtool.TestDeepCopyObject(&s1, nilSpec) testtool.TestGetName(&s1, "endpoints") Context("GetPathMethod", func() { When("action is ActionRead", func() { testtool.TestGetPathMethod(&s1, api.ActionRead, http.MethodGet, "/lb_domains/b0000000000001/sites/site-1/endpoints/endpoint-1") }) When("action is ActionUpdate", func() { testtool.TestGetPathMethod(&s1, api.ActionUpdate, http.MethodPatch, "/lb_domains/b0000000000001/sites/site-1/endpoints/endpoint-1") }) When("action is ActionDelete", func() { testtool.TestGetPathMethod(&s1, api.ActionDelete, http.MethodDelete, "/lb_domains/b0000000000001/sites/site-1/endpoints/endpoint-1") }) When("action is ActionCreate", func() { testtool.TestGetPathMethod(&s1, api.ActionCreate, http.MethodPost, "/lb_domains/b0000000000001/sites/site-1/endpoints") }) When("action is other", func() { testtool.TestGetPathMethod(&s1, api.ActionApply, "", "") }) }) }) }) Describe("EndpointList", func() { var c lb_domains.EndpointList Context("List", func() { BeforeEach(func() { httpmock.RegisterResponder(http.MethodGet, "http://localhost/lb_domains/b0000000000001/sites/site-1/endpoints", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "2C18922432DC48D485613F5383A7ED8E", "results": [ { "resource_name": "endpoint-1", "name": "host-1", "monitoring_target": "www.example.jp.", "description": "endpoint#1", "weight": 1, "manual_failback": false, "manual_failover": false, "enabled": false, "live_status": "up", "ready_status": "down", "enabled": false, "rdata": [ { "value": "192.168.0.1" }, { "value": "192.168.1.1" } ], "monitorings": [ { "resource_name": "id1", "enabled": true, "name": "monitoring-1", "mtype": "ping", "description": "comment 1", "props": { "location": "all", "interval": 30, "holdtime": 0, "timeout": 1 } } ] }, { "resource_name": "endpoint-2", "name": "host-2", "monitoring_target": "2001:db8::1", "description": "endpoint#2", "weight": 255, "manual_failback": true, "manual_failover": true, "enabled": true, "live_status": "down", "ready_status": "down", "rdata": [ { "value": "192.168.0.2" }, { "value": "192.168.1.2" } ], "monitorings": [] } ] }`))) }) AfterEach(func() { httpmock.Reset() }) When("returns list ", func() { BeforeEach(func() { c = lb_domains.EndpointList{ SiteAttributeMeta: lb_domains.SiteAttributeMeta{ AttributeMeta: lb_domains.AttributeMeta{ LBDomainID: "b0000000000001", }, SiteResourceName: "site-1", }, } reqId, err = cl.List(context.Background(), &c, nil) }) It("returns normal", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal("2C18922432DC48D485613F5383A7ED8E")) Expect(c).To(Equal(slist)) }) }) }) Context("SetPathParams", func() { When("no arguments, nothing to do", func() { BeforeEach(func() { err = slist.SetPathParams() }) It("returns error", func() { Expect(err).To(Succeed()) }) }) When("enough arguments", func() { BeforeEach(func() { err = slist.SetPathParams("b0000000000010", "site-10") }) It("not returns error", func() { Expect(err).To(Succeed()) }) It("can set LBDomainID", func() { Expect(slist.LBDomainID).To(Equal("b0000000000010")) Expect(slist.SiteResourceName).To(Equal("site-10")) }) }) When("arguments has extra value", func() { BeforeEach(func() { err = slist.SetPathParams("b0000000000010", "site-10", 2) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) When("arguments type missmatch", func() { BeforeEach(func() { err = slist.SetPathParams("b0000000000010", 2) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) }) Context("api.Spec common test", func() { var nilSpec *lb_domains.EndpointList testtool.TestDeepCopyObject(&slist, nilSpec) testtool.TestGetName(&slist, "endpoints") }) Context("api.ListSpec common test", func() { testtool.TestGetItems(&slist, &slist.Items) testtool.TestLen(&slist, 2) Context("Index", func() { When("index exist", func() { It("returns item", func() { Expect(slist.Index(0)).To(Equal(s1)) }) }) }) }) }) }) golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/lb_domains/ginkgo_test.go000066400000000000000000000007601437707610400241130ustar00rootroot00000000000000package lb_domains_test import ( "testing" "github.com/jarcoal/httpmock" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/onsi/gomega/format" ) func TestGinkgo(t *testing.T) { format.MaxLength = 8000 format.MaxDepth = uint(20) RegisterFailHandler(Fail) RunSpecs(t, "lb_domains package test suite") } var _ = BeforeSuite(func() { httpmock.Activate() }) var _ = BeforeEach(func() { httpmock.Reset() }) var _ = AfterSuite(func() { httpmock.DeactivateAndReset() }) golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/lb_domains/log.go000066400000000000000000000023011437707610400223500ustar00rootroot00000000000000package lb_domains import ( "github.com/mimuret/golang-iij-dpf/pkg/api" "github.com/mimuret/golang-iij-dpf/pkg/apis" "github.com/mimuret/golang-iij-dpf/pkg/apis/dpf/v1/core" ) var _ CountableListSpec = &LogList{} // +k8s:deepcopy-gen:interfaces=github.com/mimuret/golang-iij-dpf/pkg/api.Object type LogList struct { AttributeMeta api.Count Items []core.Log `read:"items"` } func (c *LogList) GetName() string { return "logs" } func (c *LogList) GetItems() interface{} { return &c.Items } func (c *LogList) Len() int { return len(c.Items) } func (c *LogList) Index(i int) interface{} { return c.Items[i] } func (c *LogList) GetMaxLimit() int32 { return 100 } func (c *LogList) ClearItems() { c.Items = []core.Log{} } func (c *LogList) AddItem(v interface{}) bool { if a, ok := v.(core.Log); ok { c.Items = append(c.Items, a) return true } return false } func (c *LogList) GetPathMethod(action api.Action) (string, string) { return GetPathMethodForCountableListSpec(action, c) } func (c *LogList) Init() {} func (c *LogList) SetPathParams(args ...interface{}) error { return apis.SetPathParams(args, &c.LBDomainID) } func init() { register(&LogList{}) } golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/lb_domains/log_test.go000066400000000000000000000104641437707610400234200ustar00rootroot00000000000000package lb_domains_test import ( "context" "net/http" "time" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/jarcoal/httpmock" core "github.com/mimuret/golang-iij-dpf/pkg/apis/dpf/v1/core" "github.com/mimuret/golang-iij-dpf/pkg/apis/dpf/v1/lb_domains" "github.com/mimuret/golang-iij-dpf/pkg/testtool" "github.com/mimuret/golang-iij-dpf/pkg/types" ) var _ = Describe("logs", func() { var ( cl *testtool.TestClient err error reqId string s1, s2 core.Log atTime types.Time slist lb_domains.LogList ) BeforeEach(func() { atTime, err = types.ParseTime(time.RFC3339Nano, "2021-06-20T07:55:17.753Z") Expect(err).To((Succeed())) cl = testtool.NewTestClient("", "http://localhost", nil) s1 = core.Log{ Time: atTime, LogType: "service", Operator: "user1", Operation: "add_cc_primary", Target: "1", Status: core.LogStatusStart, } s2 = core.Log{ Time: atTime, LogType: "common_config", Operator: "user2", Operation: "create_tsig", Target: "2", Status: core.LogStatusSuccess, } slist = lb_domains.LogList{ AttributeMeta: lb_domains.AttributeMeta{ LBDomainID: "b0000000000000", }, Items: []core.Log{s1, s2}, } }) Describe("LogList", func() { var c lb_domains.LogList Context("List", func() { BeforeEach(func() { httpmock.RegisterResponder(http.MethodGet, "http://localhost/lb_domains/b0000000000000/logs", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "8026628BA5AD4ECA93F8506972DD50A7", "results": [ { "time": "2021-06-20T07:55:17.753Z", "log_type": "service", "operator": "user1", "operation": "add_cc_primary", "target": "1", "status": "start" }, { "time": "2021-06-20T07:55:17.753Z", "log_type": "common_config", "operator": "user2", "operation": "create_tsig", "target": "2", "status": "success" } ] }`))) httpmock.RegisterResponder(http.MethodGet, "http://localhost/lb_domains/b0000000000000/logs/count", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "8026628BA5AD4ECA93F8506972DD50A7", "result": { "count": 2 } }`))) }) AfterEach(func() { httpmock.Reset() }) When("returns list ", func() { BeforeEach(func() { c = lb_domains.LogList{ AttributeMeta: lb_domains.AttributeMeta{ LBDomainID: "b0000000000000", }, } reqId, err = cl.List(context.Background(), &c, nil) }) It("returns normal", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal("8026628BA5AD4ECA93F8506972DD50A7")) Expect(c).To(Equal(slist)) }) }) }) Context("SetPathParams", func() { When("no arguments, nothing to do", func() { BeforeEach(func() { err = slist.SetPathParams() }) It("returns error", func() { Expect(err).To(Succeed()) }) }) When("enough arguments", func() { BeforeEach(func() { err = slist.SetPathParams("b0000000000001") }) It("not returns error", func() { Expect(err).To(Succeed()) }) It("can set ZoneID", func() { Expect(slist.GetLBDoaminID()).To(Equal("b0000000000001")) }) }) When("arguments has extra value", func() { BeforeEach(func() { err = slist.SetPathParams("b0000000000001", 2) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) When("arguments type missmatch", func() { BeforeEach(func() { err = slist.SetPathParams(2) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) }) Context("api.Spec common test", func() { var nilSpec *lb_domains.LogList testtool.TestDeepCopyObject(&slist, nilSpec) testtool.TestGetName(&slist, "logs") testtool.TestGetPathMethodForCountableList(&slist, "/lb_domains/b0000000000000/logs") }) Context("api.ListSpec common test", func() { testtool.TestGetItems(&slist, &slist.Items) testtool.TestLen(&slist, 2) Context("Index", func() { When("index exist", func() { It("returns item", func() { Expect(slist.Index(0)).To(Equal(s1)) }) }) }) }) Context("api.CountableListSpec common test", func() { testtool.TestGetMaxLimit(&slist, 100) testtool.TestClearItems(&slist) testtool.TestAddItem(&slist, s1) }) }) }) golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/lb_domains/monitoring.go000066400000000000000000000067121437707610400237660ustar00rootroot00000000000000package lb_domains import ( "encoding/json" "fmt" "github.com/mimuret/golang-iij-dpf/pkg/api" "github.com/mimuret/golang-iij-dpf/pkg/apis" ) var _ ChildSpec = &Monitoring{} type MonitoringMtype string const ( MonitoringMtypePing MonitoringMtype = "ping" MonitoringMtypeTCP MonitoringMtype = "tcp" MonitoringMtypeHTTP MonitoringMtype = "http" MonitoringMtypeStatic MonitoringMtype = "static" ) type MonitoringPorps interface { GetMtype() MonitoringMtype DeepCopyMonitoringPorps() MonitoringPorps } type MonitoringCommon struct { ResourceName string `read:"resource_name" create:"resource_name" apply:"resource_name"` Name string `read:"name" create:"name" update:"name" apply:"name"` MType MonitoringMtype `read:"mtype" create:"mtype" apply:"mtype"` Description string `read:"description" create:"description" update:"description" apply:"description"` } // +k8s:deepcopy-gen:interfaces=github.com/mimuret/golang-iij-dpf/pkg/api.Object type Monitoring struct { AttributeMeta MonitoringCommon Props MonitoringPorps `create:"props" update:"props" apply:"props"` } func (m *Monitoring) Fix() { if m.Props != nil { m.MType = m.Props.GetMtype() } } func (m *Monitoring) SetProps(props MonitoringPorps) { m.MType = props.GetMtype() m.Props = props } func (m *Monitoring) UnmarshalJSON(bs []byte) error { c := struct { MonitoringCommon Props json.RawMessage `read:"props"` }{} if err := api.UnmarshalRead(bs, &c); err != nil { return fmt.Errorf("failed to parse Monitoring: %w", err) } var props MonitoringPorps switch c.MType { case MonitoringMtypePing: props = &MonitoringPorpsPING{} case MonitoringMtypeTCP: props = &MonitoringPorpsTCP{} case MonitoringMtypeHTTP: props = &MonitoringPorpsHTTP{} case MonitoringMtypeStatic: props = &MonitoringPorpsStatic{} default: return fmt.Errorf("unknown mtype `%s`", c.MType) } if err := api.UnmarshalRead(c.Props, props); err != nil { return fmt.Errorf("failed to parse props: %w", err) } m.MonitoringCommon = c.MonitoringCommon m.SetProps(props) return nil } func (c *Monitoring) GetName() string { return "monitorings" } func (c *Monitoring) GetResourceName() string { return c.ResourceName } func (c *Monitoring) SetResourceName(resourceName string) { c.ResourceName = resourceName } func (c *Monitoring) GetPathMethod(action api.Action) (string, string) { return GetPathMethodForChildSpec(action, c) } func (c *Monitoring) SetPathParams(args ...interface{}) error { return apis.SetPathParams(args, &c.LBDomainID, &c.ResourceName) } var _ ListSpec = &MonitoringList{} // +k8s:deepcopy-gen:interfaces=github.com/mimuret/golang-iij-dpf/pkg/api.Object type MonitoringList struct { AttributeMeta Items []Monitoring `read:"items"` } func (c *MonitoringList) GetName() string { return "monitorings" } func (c *MonitoringList) GetItems() interface{} { return &c.Items } func (c *MonitoringList) Len() int { return len(c.Items) } func (c *MonitoringList) Index(i int) interface{} { return c.Items[i] } func (c *MonitoringList) GetPathMethod(action api.Action) (string, string) { return GetPathMethodForListSpec(action, c) } func (c *MonitoringList) Init() { for i := range c.Items { c.Items[i].AttributeMeta = c.AttributeMeta } } func (c *MonitoringList) SetPathParams(args ...interface{}) error { return apis.SetPathParams(args, &c.LBDomainID) } func init() { register(&Monitoring{}, &MonitoringList{}) } golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/lb_domains/monitoring_props.go000066400000000000000000000066161437707610400252140ustar00rootroot00000000000000package lb_domains type MonitoringPropsLocation string const ( MonitoringPropsLocationAll MonitoringPropsLocation = "all" MonitoringPropsLocationJP MonitoringPropsLocation = "jp" MonitoringPropsLocationUS MonitoringPropsLocation = "us" ) type MonitoringPorpsCommon struct { Location MonitoringPropsLocation `read:"location" update:"location" create:"location,omitempty" apply:"location,omitempty"` Interval uint16 `read:"interval" update:"interval" create:"interval,omitempty" apply:"interval,omitempty"` Holdtime uint16 `read:"holdtime" update:"holdtime" create:"holdtime" apply:"holdtime"` Timeout uint16 `read:"timeout" update:"timeout" create:"timeout,omitempty" apply:"timeout,omitempty"` } var _ MonitoringPorps = &MonitoringPorpsPING{} // +k8s:deepcopy-gen:interfaces=github.com/mimuret/golang-iij-dpf/pkg/apis/dpf/v1/lb_domains.MonitoringPorps type MonitoringPorpsPING struct { MonitoringPorpsCommon } func (m *MonitoringPorpsPING) GetMtype() MonitoringMtype { return MonitoringMtypePing } var _ MonitoringPorps = &MonitoringPorpsTCP{} // +k8s:deepcopy-gen:interfaces=github.com/mimuret/golang-iij-dpf/pkg/apis/dpf/v1/lb_domains.MonitoringPorps type MonitoringPorpsTCP struct { MonitoringPorpsCommon Port uint16 `read:"port" update:"port" create:"port" apply:"port"` TLSEnabled bool `read:"tls_enabled" update:"tls_enabled" create:"tls_enabled" apply:"tls_enalbed"` TLSSNI string `read:"tls_sni" update:"tls_sni" create:"tls_sni,omitempty" apply:"tls_sni,omitempty"` } func (m *MonitoringPorpsTCP) GetMtype() MonitoringMtype { return MonitoringMtypeTCP } type MonitoringPorpsHeader struct { FieldName string `read:"field_name" update:"field_name" create:"field_name" apply:"field_name"` FieldValue string `read:"field_value" update:"field_value" create:"field_value" apply:"field_value"` } var _ MonitoringPorps = &MonitoringPorpsHTTP{} // +k8s:deepcopy-gen:interfaces=github.com/mimuret/golang-iij-dpf/pkg/apis/dpf/v1/lb_domains.MonitoringPorps type MonitoringPorpsHTTP struct { MonitoringPorpsCommon Port uint16 `read:"port" update:"port" create:"port,omitempty" apply:"port,omitempty"` TLSSNI string `read:"tls_sni" update:"tls_sni" create:"tls_sni,omitempty" apply:"tls_sni,omitempty"` ResponseMatch string `read:"response_match" update:"response_match" create:"response_match,omitempty" apply:"response_match,omitempty"` HTTPS bool `read:"https" update:"https" create:"https" apply:"https"` Path string `read:"path" update:"path" create:"path,omitempty" apply:"path,omitempty"` StatusCode []string `read:"status_codes" update:"status_codes" create:"status_codes,omitempty" apply:"status_codes,omitempty"` } func (m *MonitoringPorpsHTTP) GetMtype() MonitoringMtype { return MonitoringMtypeHTTP } type MonitoringPorpsStaticStatus string const ( MonitoringPorpsStaticStatusUp MonitoringPorpsStaticStatus = "up" MonitoringPorpsStaticStatusDown MonitoringPorpsStaticStatus = "down" MonitoringPorpsStaticStatusUnkown MonitoringPorpsStaticStatus = "unknown" ) // +k8s:deepcopy-gen:interfaces=github.com/mimuret/golang-iij-dpf/pkg/apis/dpf/v1/lb_domains.MonitoringPorps type MonitoringPorpsStatic struct { Result MonitoringPorpsStaticStatus `read:"result" update:"result" create:"result" apply:"result"` } func (m *MonitoringPorpsStatic) GetMtype() MonitoringMtype { return MonitoringMtypeStatic } golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/lb_domains/monitoring_props_http_test.go000066400000000000000000000072421437707610400273060ustar00rootroot00000000000000package lb_domains_test import ( "encoding/json" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" api "github.com/mimuret/golang-iij-dpf/pkg/api" "github.com/mimuret/golang-iij-dpf/pkg/apis/dpf/v1/lb_domains" ) var _ = Describe("MonitoringPorpsHTTP", func() { var ( bs []byte c lb_domains.MonitoringPorpsHTTP err error s1, s2, s3 lb_domains.MonitoringPorpsHTTP ) BeforeEach(func() { s1 = lb_domains.MonitoringPorpsHTTP{ MonitoringPorpsCommon: lb_domains.MonitoringPorpsCommon{ Location: lb_domains.MonitoringPropsLocationAll, Interval: 30, Holdtime: 0, Timeout: 1, }, Port: 443, TLSSNI: "example.jp", ResponseMatch: "successful", HTTPS: true, Path: "/ready", StatusCode: []string{"200"}, } s2 = lb_domains.MonitoringPorpsHTTP{ MonitoringPorpsCommon: lb_domains.MonitoringPorpsCommon{ Location: lb_domains.MonitoringPropsLocationJP, Interval: 600, Holdtime: 3600, Timeout: 30, }, Port: 80, TLSSNI: "", ResponseMatch: "", HTTPS: false, Path: "", StatusCode: []string{}, } s3 = lb_domains.MonitoringPorpsHTTP{ Port: 53, } }) Context("Read", func() { Context("s1", func() { BeforeEach(func() { err = api.UnmarshalRead(json.RawMessage(`{ "location": "all", "interval": 30, "holdtime": 0, "timeout": 1, "port": 443, "https": true, "tls_sni": "example.jp", "response_match": "successful", "path": "/ready", "status_codes": ["200"] }`), &c) }) It("succeed", func() { Expect(err).To(Succeed()) Expect(c).To(Equal(s1)) }) }) Context("s2", func() { BeforeEach(func() { err = api.UnmarshalRead(json.RawMessage(`{ "location": "jp", "interval": 600, "holdtime": 3600, "timeout": 30, "port": 80, "https": false, "tls_sni": "", "response_match": "", "path": "", "status_codes": [] }`), &c) }) It("succeed", func() { Expect(err).To(Succeed()) Expect(c).To(Equal(s2)) }) }) }) Context("Update", func() { Context("s1", func() { BeforeEach(func() { bs, err = api.MarshalUpdate(s1) }) It("succeed", func() { Expect(err).To(Succeed()) Expect(bs).To(MatchJSON(`{ "location": "all", "interval": 30, "holdtime": 0, "timeout": 1, "port": 443, "https": true, "tls_sni": "example.jp", "response_match": "successful", "path": "/ready", "status_codes": ["200"] }`)) }) }) Context("s3", func() { BeforeEach(func() { bs, err = api.MarshalUpdate(s3) }) It("succeed", func() { Expect(err).To(Succeed()) Expect(bs).To(MatchJSON(`{ "location": "", "interval": 0, "holdtime": 0, "timeout": 0, "port": 53, "https": false, "tls_sni": "", "response_match": "", "path": "", "status_codes": null }`)) }) }) }) Context("Create", func() { Context("s1", func() { BeforeEach(func() { bs, err = api.MarshalCreate(s1) }) It("succeed", func() { Expect(err).To(Succeed()) Expect(bs).To(MatchJSON(`{ "location": "all", "interval": 30, "holdtime": 0, "timeout": 1, "port": 443, "https": true, "tls_sni": "example.jp", "response_match": "successful", "path": "/ready", "status_codes": ["200"] }`)) }) }) Context("s3", func() { BeforeEach(func() { bs, err = api.MarshalCreate(s3) }) It("succeed", func() { Expect(err).To(Succeed()) Expect(bs).To(MatchJSON(`{ "holdtime": 0, "port": 53, "https": false }`)) }) }) }) }) golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/lb_domains/monitoring_props_ping_test.go000066400000000000000000000051251437707610400272620ustar00rootroot00000000000000package lb_domains_test import ( "encoding/json" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" api "github.com/mimuret/golang-iij-dpf/pkg/api" "github.com/mimuret/golang-iij-dpf/pkg/apis/dpf/v1/lb_domains" ) var _ = Describe("MonitoringPorpsPING", func() { var ( bs []byte c lb_domains.MonitoringPorpsPING err error s1, s2, s3 lb_domains.MonitoringPorpsPING ) BeforeEach(func() { s1 = lb_domains.MonitoringPorpsPING{ MonitoringPorpsCommon: lb_domains.MonitoringPorpsCommon{ Location: lb_domains.MonitoringPropsLocationAll, Interval: 30, Holdtime: 0, Timeout: 1, }, } s2 = lb_domains.MonitoringPorpsPING{ MonitoringPorpsCommon: lb_domains.MonitoringPorpsCommon{ Location: lb_domains.MonitoringPropsLocationJP, Interval: 600, Holdtime: 3600, Timeout: 30, }, } s3 = lb_domains.MonitoringPorpsPING{} }) Context("Read", func() { Context("s1", func() { BeforeEach(func() { err = api.UnmarshalRead(json.RawMessage(`{ "location": "all", "interval": 30, "holdtime": 0, "timeout": 1 }`), &c) }) It("succeed", func() { Expect(err).To(Succeed()) Expect(c).To(Equal(s1)) }) }) Context("s2", func() { BeforeEach(func() { err = api.UnmarshalRead(json.RawMessage(`{ "location": "jp", "interval": 600, "holdtime": 3600, "timeout": 30 }`), &c) }) It("succeed", func() { Expect(err).To(Succeed()) Expect(c).To(Equal(s2)) }) }) }) Context("Update", func() { Context("s1", func() { BeforeEach(func() { bs, err = api.MarshalUpdate(s1) }) It("succeed", func() { Expect(err).To(Succeed()) Expect(bs).To(MatchJSON(`{ "location": "all", "interval": 30, "holdtime": 0, "timeout": 1 }`)) }) }) Context("s3", func() { BeforeEach(func() { bs, err = api.MarshalUpdate(s3) }) It("succeed", func() { Expect(err).To(Succeed()) Expect(bs).To(MatchJSON(`{ "location": "", "interval": 0, "holdtime": 0, "timeout": 0 }`)) }) }) }) Context("Create", func() { Context("s1", func() { BeforeEach(func() { bs, err = api.MarshalCreate(s1) }) It("succeed", func() { Expect(err).To(Succeed()) Expect(bs).To(MatchJSON(`{ "location": "all", "interval": 30, "holdtime": 0, "timeout": 1 }`)) }) }) Context("s3", func() { BeforeEach(func() { bs, err = api.MarshalCreate(s3) }) It("succeed", func() { Expect(err).To(Succeed()) Expect(bs).To(MatchJSON(`{ "holdtime": 0 }`)) }) }) }) }) golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/lb_domains/monitoring_props_static_test.go000066400000000000000000000042011437707610400276060ustar00rootroot00000000000000package lb_domains_test import ( "encoding/json" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" api "github.com/mimuret/golang-iij-dpf/pkg/api" "github.com/mimuret/golang-iij-dpf/pkg/apis/dpf/v1/lb_domains" ) var _ = Describe("MonitoringPorpsStatic", func() { var ( bs []byte c lb_domains.MonitoringPorpsStatic err error s1, s2, s3 lb_domains.MonitoringPorpsStatic ) BeforeEach(func() { s1 = lb_domains.MonitoringPorpsStatic{ Result: lb_domains.MonitoringPorpsStaticStatusUp, } s2 = lb_domains.MonitoringPorpsStatic{ Result: lb_domains.MonitoringPorpsStaticStatusDown, } s3 = lb_domains.MonitoringPorpsStatic{ Result: lb_domains.MonitoringPorpsStaticStatusUnkown, } }) Context("Read", func() { Context("s1", func() { BeforeEach(func() { err = api.UnmarshalRead(json.RawMessage(`{ "result": "up" }`), &c) }) It("succeed", func() { Expect(err).To(Succeed()) Expect(c).To(Equal(s1)) }) }) Context("s2", func() { BeforeEach(func() { err = api.UnmarshalRead(json.RawMessage(`{ "result": "down" }`), &c) }) It("succeed", func() { Expect(err).To(Succeed()) Expect(c).To(Equal(s2)) }) }) }) Context("Update", func() { Context("s1", func() { BeforeEach(func() { bs, err = api.MarshalUpdate(s1) }) It("succeed", func() { Expect(err).To(Succeed()) Expect(bs).To(MatchJSON(`{ "result": "up" }`)) }) }) Context("s3", func() { BeforeEach(func() { bs, err = api.MarshalUpdate(s3) }) It("succeed", func() { Expect(err).To(Succeed()) Expect(bs).To(MatchJSON(`{ "result": "unknown" }`)) }) }) }) Context("Create", func() { Context("s1", func() { BeforeEach(func() { bs, err = api.MarshalCreate(s1) }) It("succeed", func() { Expect(err).To(Succeed()) Expect(bs).To(MatchJSON(`{ "result": "up" }`)) }) }) Context("s3", func() { BeforeEach(func() { bs, err = api.MarshalCreate(s3) }) It("succeed", func() { Expect(err).To(Succeed()) Expect(bs).To(MatchJSON(`{ "result": "unknown" }`)) }) }) }) }) golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/lb_domains/monitoring_props_tcp_test.go000066400000000000000000000061531437707610400271150ustar00rootroot00000000000000package lb_domains_test import ( "encoding/json" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" api "github.com/mimuret/golang-iij-dpf/pkg/api" "github.com/mimuret/golang-iij-dpf/pkg/apis/dpf/v1/lb_domains" ) var _ = Describe("MonitoringPorpsTCP", func() { var ( bs []byte c lb_domains.MonitoringPorpsTCP err error s1, s2, s3 lb_domains.MonitoringPorpsTCP ) BeforeEach(func() { s1 = lb_domains.MonitoringPorpsTCP{ MonitoringPorpsCommon: lb_domains.MonitoringPorpsCommon{ Location: lb_domains.MonitoringPropsLocationAll, Interval: 30, Holdtime: 0, Timeout: 1, }, Port: 443, TLSEnabled: true, TLSSNI: "example.jp", } s2 = lb_domains.MonitoringPorpsTCP{ MonitoringPorpsCommon: lb_domains.MonitoringPorpsCommon{ Location: lb_domains.MonitoringPropsLocationJP, Interval: 600, Holdtime: 3600, Timeout: 30, }, Port: 80, TLSEnabled: false, TLSSNI: "", } s3 = lb_domains.MonitoringPorpsTCP{ Port: 53, } }) Context("Read", func() { Context("s1", func() { BeforeEach(func() { err = api.UnmarshalRead(json.RawMessage(`{ "location": "all", "interval": 30, "holdtime": 0, "timeout": 1, "port": 443, "tls_enabled": true, "tls_sni": "example.jp" }`), &c) }) It("succeed", func() { Expect(err).To(Succeed()) Expect(c).To(Equal(s1)) }) }) Context("s2", func() { BeforeEach(func() { err = api.UnmarshalRead(json.RawMessage(`{ "location": "jp", "interval": 600, "holdtime": 3600, "timeout": 30, "port": 80, "tls_enabled": false, "tls_sni": "" }`), &c) }) It("succeed", func() { Expect(err).To(Succeed()) Expect(c).To(Equal(s2)) }) }) }) Context("Update", func() { Context("s1", func() { BeforeEach(func() { bs, err = api.MarshalUpdate(s1) }) It("succeed", func() { Expect(err).To(Succeed()) Expect(bs).To(MatchJSON(`{ "location": "all", "interval": 30, "holdtime": 0, "timeout": 1, "port": 443, "tls_enabled": true, "tls_sni": "example.jp" }`)) }) }) Context("s3", func() { BeforeEach(func() { bs, err = api.MarshalUpdate(s3) }) It("succeed", func() { Expect(err).To(Succeed()) Expect(bs).To(MatchJSON(`{ "location": "", "interval": 0, "holdtime": 0, "timeout": 0, "port": 53, "tls_enabled": false, "tls_sni": "" }`)) }) }) }) Context("Create", func() { Context("s1", func() { BeforeEach(func() { bs, err = api.MarshalCreate(s1) }) It("succeed", func() { Expect(err).To(Succeed()) Expect(bs).To(MatchJSON(`{ "location": "all", "interval": 30, "holdtime": 0, "timeout": 1, "port": 443, "tls_enabled": true, "tls_sni": "example.jp" }`)) }) }) Context("s3", func() { BeforeEach(func() { bs, err = api.MarshalCreate(s3) }) It("succeed", func() { Expect(err).To(Succeed()) Expect(bs).To(MatchJSON(`{ "holdtime": 0, "port": 53, "tls_enabled": false }`)) }) }) }) }) golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/lb_domains/monitoring_test.go000066400000000000000000000235621437707610400250270ustar00rootroot00000000000000package lb_domains_test import ( "context" "net/http" "github.com/jarcoal/httpmock" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" api "github.com/mimuret/golang-iij-dpf/pkg/api" "github.com/mimuret/golang-iij-dpf/pkg/apis/dpf/v1/lb_domains" "github.com/mimuret/golang-iij-dpf/pkg/testtool" ) var _ = Describe("Monitoring", func() { var ( c lb_domains.Monitoring cl *testtool.TestClient err error reqId string s1, s2 lb_domains.Monitoring slist lb_domains.MonitoringList ) BeforeEach(func() { cl = testtool.NewTestClient("", "http://localhost", nil) s1 = lb_domains.Monitoring{ AttributeMeta: lb_domains.AttributeMeta{ LBDomainID: "b0000000000001", }, MonitoringCommon: lb_domains.MonitoringCommon{ ResourceName: "id1", Name: "monitoring-1", MType: lb_domains.MonitoringMtypePing, Description: "comment 1", }, Props: &lb_domains.MonitoringPorpsPING{ MonitoringPorpsCommon: lb_domains.MonitoringPorpsCommon{ Location: lb_domains.MonitoringPropsLocationAll, Interval: 30, Holdtime: 0, Timeout: 1, }, }, } s2 = lb_domains.Monitoring{ AttributeMeta: lb_domains.AttributeMeta{ LBDomainID: "b0000000000001", }, MonitoringCommon: lb_domains.MonitoringCommon{ ResourceName: "id2", Name: "monitoring-2", MType: lb_domains.MonitoringMtypeStatic, Description: "comment 2", }, Props: &lb_domains.MonitoringPorpsStatic{ Result: lb_domains.MonitoringPorpsStaticStatusUp, }, } slist = lb_domains.MonitoringList{ AttributeMeta: lb_domains.AttributeMeta{ LBDomainID: "b0000000000001", }, Items: []lb_domains.Monitoring{s1, s2}, } }) Describe("Monitoring", func() { Context("Read", func() { BeforeEach(func() { httpmock.RegisterResponder(http.MethodGet, "http://localhost/lb_domains/b0000000000001/monitorings/id1", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "76D7462F50E3417C96898A827E0D1EC1", "result": { "resource_name": "id1", "name": "monitoring-1", "mtype": "ping", "description": "comment 1", "props": { "location": "all", "interval": 30, "holdtime": 0, "timeout": 1 } } }`))) httpmock.RegisterResponder(http.MethodGet, "http://localhost/lb_domains/b0000000000001/monitorings/id2", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "B10F0042282A46C18BFB440B5B58BF8C", "result": { "resource_name": "id2", "name": "monitoring-2", "mtype": "static", "description": "comment 2", "props": { "result": "up" } } }`))) }) AfterEach(func() { httpmock.Reset() }) When("returns LBDomain m1", func() { BeforeEach(func() { c = lb_domains.Monitoring{ AttributeMeta: lb_domains.AttributeMeta{ LBDomainID: "b0000000000001", }, MonitoringCommon: lb_domains.MonitoringCommon{ ResourceName: "id1", }, } reqId, err = cl.Read(context.Background(), &c) }) It("returns normal", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal("76D7462F50E3417C96898A827E0D1EC1")) Expect(c).To(Equal(s1)) }) }) When("returns LBDomain m2", func() { BeforeEach(func() { c = lb_domains.Monitoring{ AttributeMeta: lb_domains.AttributeMeta{ LBDomainID: "b0000000000001", }, MonitoringCommon: lb_domains.MonitoringCommon{ ResourceName: "id2", }, } reqId, err = cl.Read(context.Background(), &c) }) It("returns normal", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal("B10F0042282A46C18BFB440B5B58BF8C")) Expect(c).To(Equal(s2)) }) }) }) Context("Create", func() { id1, bs1 := testtool.CreateAsyncResponse() BeforeEach(func() { httpmock.RegisterResponder(http.MethodPost, "http://localhost/lb_domains/b0000000000001/monitorings", httpmock.NewBytesResponder(202, bs1)) reqId, err = cl.Create(context.Background(), &s1, nil) }) AfterEach(func() { httpmock.Reset() }) It("returns job_id", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal(id1)) }) It("post json", func() { Expect(cl.RequestBody["/lb_domains/b0000000000001/monitorings"]).To(MatchJSON(`{ "resource_name": "id1", "name": "monitoring-1", "mtype": "ping", "description": "comment 1", "props": { "location": "all", "interval": 30, "holdtime": 0, "timeout": 1 } }`)) }) }) Context("Update", func() { id1, bs1 := testtool.CreateAsyncResponse() BeforeEach(func() { httpmock.RegisterResponder(http.MethodPatch, "http://localhost/lb_domains/b0000000000001/monitorings/id1", httpmock.NewBytesResponder(202, bs1)) reqId, err = cl.Update(context.Background(), &s1, nil) }) AfterEach(func() { httpmock.Reset() }) It("returns job_id", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal(id1)) }) It("post json", func() { Expect(cl.RequestBody["/lb_domains/b0000000000001/monitorings/id1"]).To(MatchJSON(`{ "name": "monitoring-1", "description": "comment 1", "props": { "location": "all", "interval": 30, "holdtime": 0, "timeout": 1 } }`)) }) }) Context("SetPathParams", func() { When("no arguments, nothing to do", func() { BeforeEach(func() { err = s1.SetPathParams() }) It("returns error", func() { Expect(err).To(Succeed()) }) }) When("enough arguments", func() { BeforeEach(func() { err = s1.SetPathParams("b0000000000010", "id1") }) It("not returns error", func() { Expect(err).To(Succeed()) }) It("can set LBDomainID", func() { Expect(s1.LBDomainID).To(Equal("b0000000000010")) Expect(s1.ResourceName).To(Equal("id1")) }) }) When("arguments has extra value", func() { BeforeEach(func() { err = s1.SetPathParams("b0000000000010", "id1", 2) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) When("arguments type missmatch", func() { BeforeEach(func() { err = s1.SetPathParams(2, "id1") }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) }) Context("api.Spec common test", func() { var nilSpec *lb_domains.Monitoring testtool.TestDeepCopyObject(&s1, nilSpec) testtool.TestGetName(&s1, "monitorings") Context("GetPathMethod", func() { When("action is ActionRead", func() { testtool.TestGetPathMethod(&s1, api.ActionRead, http.MethodGet, "/lb_domains/b0000000000001/monitorings/id1") }) When("action is ActionUpdate", func() { testtool.TestGetPathMethod(&s1, api.ActionUpdate, http.MethodPatch, "/lb_domains/b0000000000001/monitorings/id1") }) When("action is ActionDelete", func() { testtool.TestGetPathMethod(&s1, api.ActionDelete, http.MethodDelete, "/lb_domains/b0000000000001/monitorings/id1") }) When("action is ActionCreate", func() { testtool.TestGetPathMethod(&s1, api.ActionCreate, http.MethodPost, "/lb_domains/b0000000000001/monitorings") }) When("action is other", func() { testtool.TestGetPathMethod(&s1, api.ActionApply, "", "") }) }) }) }) Describe("MonitoringList", func() { var c lb_domains.MonitoringList Context("List", func() { BeforeEach(func() { httpmock.RegisterResponder(http.MethodGet, "http://localhost/lb_domains/b0000000000001/monitorings", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "2C18922432DC48D485613F5383A7ED8E", "results": [ { "resource_name": "id1", "name": "monitoring-1", "mtype": "ping", "description": "comment 1", "props": { "location": "all", "interval": 30, "holdtime": 0, "timeout": 1 } }, { "resource_name": "id2", "name": "monitoring-2", "mtype": "static", "description": "comment 2", "props": { "result": "up" } } ] }`))) }) AfterEach(func() { httpmock.Reset() }) When("returns list ", func() { BeforeEach(func() { c = lb_domains.MonitoringList{ AttributeMeta: lb_domains.AttributeMeta{ LBDomainID: "b0000000000001", }, } reqId, err = cl.List(context.Background(), &c, nil) }) It("returns normal", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal("2C18922432DC48D485613F5383A7ED8E")) Expect(c).To(Equal(slist)) }) }) }) Context("SetPathParams", func() { When("no arguments, nothing to do", func() { BeforeEach(func() { err = slist.SetPathParams() }) It("returns error", func() { Expect(err).To(Succeed()) }) }) When("enough arguments", func() { BeforeEach(func() { err = slist.SetPathParams("b0000000000010") }) It("not returns error", func() { Expect(err).To(Succeed()) }) It("can set LBDomainID", func() { Expect(slist.LBDomainID).To(Equal("b0000000000010")) }) }) When("arguments has extra value", func() { BeforeEach(func() { err = slist.SetPathParams("b0000000000010", 2) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) When("arguments type missmatch", func() { BeforeEach(func() { err = slist.SetPathParams(2) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) }) Context("api.Spec common test", func() { var nilSpec *lb_domains.MonitoringList testtool.TestDeepCopyObject(&slist, nilSpec) testtool.TestGetName(&slist, "monitorings") }) Context("api.ListSpec common test", func() { testtool.TestGetItems(&slist, &slist.Items) testtool.TestLen(&slist, 2) Context("Index", func() { When("index exist", func() { It("returns item", func() { Expect(slist.Index(0)).To(Equal(s1)) }) }) }) }) }) }) golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/lb_domains/rule.go000066400000000000000000000047361437707610400225540ustar00rootroot00000000000000package lb_domains import ( "github.com/mimuret/golang-iij-dpf/pkg/api" "github.com/mimuret/golang-iij-dpf/pkg/apis" ) type RuleRRType string const ( RuleRRTypeA RuleRRType = "A" RuleRRTypeAAAA RuleRRType = "AAAA" RuleRRTypeCNAME RuleRRType = "CNAME" ) var _ ChildSpec = &Rule{} // +k8s:deepcopy-gen:interfaces=github.com/mimuret/golang-iij-dpf/pkg/api.Object type Rule struct { AttributeMeta ResourceName string `read:"resource_name" create:"resource_name,omitempty" apply:"resource_name"` Name string `read:"name" create:"name" update:"name" apply:"name"` Description string `read:"description" create:"description" update:"description" apply:"description"` Methods []RuleMethod `read:"methods" apply:"methods"` } func (c *Rule) Init() { for i := range c.Methods { c.Methods[i].AttributeMeta = c.AttributeMeta c.Methods[i].RuleResourceName = c.ResourceName } } func (c *Rule) GetName() string { return "rules" } func (c *Rule) GetResourceName() string { return c.ResourceName } func (c *Rule) SetResourceName(resourceName string) { c.ResourceName = resourceName } func (c *Rule) GetPathMethod(action api.Action) (string, string) { return GetPathMethodForChildSpec(action, c) } func (c *Rule) SetPathParams(args ...interface{}) error { return apis.SetPathParams(args, &c.LBDomainID, &c.ResourceName) } var _ ListSpec = &RuleList{} // +k8s:deepcopy-gen:interfaces=github.com/mimuret/golang-iij-dpf/pkg/api.Object type RuleList struct { AttributeMeta api.Count Items []Rule `read:"items"` } func (c *RuleList) GetName() string { return "rules" } func (c *RuleList) GetItems() interface{} { return &c.Items } func (c *RuleList) Len() int { return len(c.Items) } func (c *RuleList) Index(i int) interface{} { return c.Items[i] } func (c *RuleList) GetMaxLimit() int32 { return 10000 } func (c *RuleList) ClearItems() { c.Items = []Rule{} } func (c *RuleList) AddItem(v interface{}) bool { if a, ok := v.(Rule); ok { c.Items = append(c.Items, a) return true } return false } func (c *RuleList) GetPathMethod(action api.Action) (string, string) { return GetPathMethodForListSpec(action, c) } func (c *RuleList) Init() { for i := range c.Items { c.Items[i].AttributeMeta = c.AttributeMeta c.Items[i].Init() } } func (c *RuleList) SetPathParams(args ...interface{}) error { return apis.SetPathParams(args, &c.LBDomainID) } func init() { register(&Rule{}, &RuleList{}) } golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/lb_domains/rule_method.go000066400000000000000000000076111437707610400241070ustar00rootroot00000000000000package lb_domains import ( "encoding/json" "fmt" "net/http" "github.com/mimuret/golang-iij-dpf/pkg/api" "github.com/mimuret/golang-iij-dpf/pkg/apis" ) var _ Spec = &RuleMethod{} type RuleAttributeMeta struct { AttributeMeta RuleResourceName string } type RuleMethodProps interface { Fix() GetMType() RuleMethodMType GetMethodResourceName() string SetMethodResourceName(string) DeepCopyRuleMethodProps() RuleMethodProps } // +k8s:deepcopy-gen:interfaces=github.com/mimuret/golang-iij-dpf/pkg/api.Object type RuleMethod struct { RuleAttributeMeta Priority *uint `create:"priority,omitempty" update:"priority,omitempty" apply:"priority,omitempty"` Method RuleMethodProps `create:"method" update:"method" apply:"method"` } func (c *RuleMethod) Fix() { if c.Method != nil { c.Method.Fix() } } func (c *RuleMethod) UnmarshalJSON(bs []byte) error { r := struct { Priority *uint `read:"priority"` Method json.RawMessage `read:"method"` }{} if err := api.UnmarshalRead(bs, &r); err != nil { return fmt.Errorf("failed to parse RuleMethod: %w", err) } propsCommon := &RuleMethodPropsCommon{} if err := api.UnmarshalRead(r.Method, propsCommon); err != nil { return fmt.Errorf("failed to parse Method: %w", err) } var props RuleMethodProps switch propsCommon.MType { case "entry_a": props = &RuleMethodEntryA{} case "entry_aaaa": props = &RuleMethodEntryAAAA{} case "entry_cname": props = &RuleMethodEntryCNAME{} case "exit_site": props = &RuleMethodExitSite{} case "exit_sorry": props = &RuleMethodExitSorry{} case "failover": props = &RuleMethodFailover{} default: return fmt.Errorf("unknown mtype `%s`", propsCommon.MType) } if err := api.UnmarshalRead(r.Method, props); err != nil { return fmt.Errorf("failed to parse props: %w", err) } c.Priority = r.Priority c.Method = props return nil } func (c *RuleMethod) GetName() string { return "rule_methods" } func (c *RuleMethod) GetMethodResourceName() string { return c.Method.GetMethodResourceName() } func (c *RuleMethod) SetMethodResourceName(resourceName string) { c.Method.SetMethodResourceName(resourceName) } func (c *RuleMethod) GetPathMethod(action api.Action) (string, string) { switch action { case api.ActionCreate: return action.ToMethod(), fmt.Sprintf("/lb_domains/%s/rules/%s/rule_methods", c.GetLBDoaminID(), c.RuleResourceName) case api.ActionRead, api.ActionUpdate, api.ActionDelete: return action.ToMethod(), fmt.Sprintf("/lb_domains/%s/rules/%s/rule_methods/%s", c.GetLBDoaminID(), c.RuleResourceName, c.Method.GetMethodResourceName()) } return "", "" } func (c *RuleMethod) SetPathParams(args ...interface{}) error { var methodResourceName string if err := apis.SetPathParams(args, &c.LBDomainID, &c.RuleResourceName, &methodResourceName); err != nil { return err } c.SetMethodResourceName(methodResourceName) return nil } var _ ListSpec = &MonitoringList{} // +k8s:deepcopy-gen:interfaces=github.com/mimuret/golang-iij-dpf/pkg/api.Object type RuleMethodList struct { RuleAttributeMeta Items []RuleMethod `read:"items"` } func (c *RuleMethodList) GetName() string { return "rule_methods" } func (c *RuleMethodList) GetItems() interface{} { return &c.Items } func (c *RuleMethodList) Len() int { return len(c.Items) } func (c *RuleMethodList) Index(i int) interface{} { return c.Items[i] } func (c *RuleMethodList) GetPathMethod(action api.Action) (string, string) { if action == api.ActionList { return http.MethodGet, fmt.Sprintf("/lb_domains/%s/rules/%s/rule_methods", c.GetLBDoaminID(), c.RuleResourceName) } return "", "" } func (c *RuleMethodList) Init() { for i := range c.Items { c.Items[i].RuleAttributeMeta = c.RuleAttributeMeta } } func (c *RuleMethodList) SetPathParams(args ...interface{}) error { return apis.SetPathParams(args, &c.LBDomainID, &c.RuleResourceName) } func init() { register(&RuleMethod{}, &RuleMethodList{}) } golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/lb_domains/rule_method_props.go000066400000000000000000000074401437707610400253320ustar00rootroot00000000000000package lb_domains type RuleMethodMType string const ( RuleMethodMTypeEntryA RuleMethodMType = "entry_a" RuleMethodMTypeEntryAAAA RuleMethodMType = "entry_aaaa" RuleMethodMTypeEntryCNAME RuleMethodMType = "entry_cname" RuleMethodMTypeExitSite RuleMethodMType = "exit_site" RuleMethodMTypeExitSorry RuleMethodMType = "exit_sorry" RuleMethodMTypeFailover RuleMethodMType = "exit_failover" ) // +k8s:deepcopy-gen:interfaces=github.com/mimuret/golang-iij-dpf/pkg/apis/dpf/v1/lb_domains.RuleMethodProps type RuleMethodPropsCommon struct { ResourceName string `read:"resource_name" create:"resource_name" apply:"resource_name"` MType RuleMethodMType `read:"mtype" create:"mtype" apply:"mtype"` Enabled bool `read:"enabled" create:"enabled" update:"enabled" apply:"enabled"` LiveStatus Status `read:"live_status"` ReadyStatus Status `read:"ready_status"` } func (r *RuleMethodPropsCommon) Fix() {} func (r *RuleMethodPropsCommon) GetMType() RuleMethodMType { return r.MType } func (r *RuleMethodPropsCommon) GetMethodResourceName() string { return r.ResourceName } func (r *RuleMethodPropsCommon) SetMethodResourceName(resourceName string) { r.ResourceName = resourceName } var _ RuleMethodProps = &RuleMethodEntryA{} // +k8s:deepcopy-gen:interfaces=github.com/mimuret/golang-iij-dpf/pkg/apis/dpf/v1/lb_domains.RuleMethodProps type RuleMethodEntryA struct { RuleMethodPropsCommon } func (m *RuleMethodEntryA) Fix() { m.RuleMethodPropsCommon.MType = RuleMethodMTypeEntryA } var _ RuleMethodProps = &RuleMethodEntryAAAA{} // +k8s:deepcopy-gen:interfaces=github.com/mimuret/golang-iij-dpf/pkg/apis/dpf/v1/lb_domains.RuleMethodProps type RuleMethodEntryAAAA struct { RuleMethodPropsCommon } func (m *RuleMethodEntryAAAA) Fix() { m.RuleMethodPropsCommon.MType = RuleMethodMTypeEntryAAAA } var _ RuleMethodProps = &RuleMethodEntryCNAME{} // +k8s:deepcopy-gen:interfaces=github.com/mimuret/golang-iij-dpf/pkg/apis/dpf/v1/lb_domains.RuleMethodProps type RuleMethodEntryCNAME struct { RuleMethodPropsCommon } func (m *RuleMethodEntryCNAME) Fix() { m.RuleMethodPropsCommon.MType = RuleMethodMTypeEntryCNAME } var _ RuleMethodProps = &RuleMethodExitSite{} // +k8s:deepcopy-gen:interfaces=github.com/mimuret/golang-iij-dpf/pkg/apis/dpf/v1/lb_domains.RuleMethodProps type RuleMethodExitSite struct { RuleMethodPropsCommon ParentResourceName string `read:"parent_resource_name" create:"parent_resource_name" apply:"parent_resource_name"` SiteResourceName string `read:"site_resource_name" create:"site_resource_name" apply:"site_resource_name"` } func (m *RuleMethodExitSite) GetParentResourceName() string { return m.ParentResourceName } func (m *RuleMethodExitSite) Fix() { m.RuleMethodPropsCommon.MType = RuleMethodMTypeExitSite } var _ RuleMethodProps = &RuleMethodExitSorry{} // +k8s:deepcopy-gen:interfaces=github.com/mimuret/golang-iij-dpf/pkg/apis/dpf/v1/lb_domains.RuleMethodProps type RuleMethodExitSorry struct { RuleMethodPropsCommon ParentResourceName string `read:"parent_resource_name" create:"parent_resource_name" apply:"parent_resource_name"` } func (m *RuleMethodExitSorry) GetParentResourceName() string { return m.ParentResourceName } func (m *RuleMethodExitSorry) Fix() { m.RuleMethodPropsCommon.MType = RuleMethodMTypeExitSorry } var _ RuleMethodProps = &RuleMethodFailover{} // +k8s:deepcopy-gen:interfaces=github.com/mimuret/golang-iij-dpf/pkg/apis/dpf/v1/lb_domains.RuleMethodProps type RuleMethodFailover struct { RuleMethodPropsCommon ParentResourceName string `read:"parent_resource_name" create:"parent_resource_name" apply:"parent_resource_name"` } func (m *RuleMethodFailover) GetParentResourceName() string { return m.ParentResourceName } func (m *RuleMethodFailover) Fix() { m.RuleMethodPropsCommon.MType = RuleMethodMTypeFailover } golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/lb_domains/rule_method_test.go000066400000000000000000000247601437707610400251520ustar00rootroot00000000000000package lb_domains_test import ( "context" "net/http" "github.com/jarcoal/httpmock" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" api "github.com/mimuret/golang-iij-dpf/pkg/api" "github.com/mimuret/golang-iij-dpf/pkg/apis/dpf/v1/lb_domains" "github.com/mimuret/golang-iij-dpf/pkg/testtool" ) var _ = Describe("RuleMethod", func() { var ( c lb_domains.RuleMethod cl *testtool.TestClient err error reqId string s1, s2 lb_domains.RuleMethod priorityS1 uint slist lb_domains.RuleMethodList ) BeforeEach(func() { cl = testtool.NewTestClient("", "http://localhost", nil) priorityS1 = 10 s1 = lb_domains.RuleMethod{ RuleAttributeMeta: lb_domains.RuleAttributeMeta{ AttributeMeta: lb_domains.AttributeMeta{ LBDomainID: "b0000000000001", }, RuleResourceName: "rule-1", }, Priority: &priorityS1, Method: &lb_domains.RuleMethodEntryA{ lb_domains.RuleMethodPropsCommon{ ResourceName: "method-1", MType: lb_domains.RuleMethodMTypeEntryA, Enabled: true, LiveStatus: lb_domains.StatusUp, ReadyStatus: lb_domains.StatusDown, }, }, } s2 = lb_domains.RuleMethod{ RuleAttributeMeta: lb_domains.RuleAttributeMeta{ AttributeMeta: lb_domains.AttributeMeta{ LBDomainID: "b0000000000001", }, RuleResourceName: "rule-1", }, Method: &lb_domains.RuleMethodEntryA{ lb_domains.RuleMethodPropsCommon{ ResourceName: "method-2", MType: lb_domains.RuleMethodMTypeEntryA, Enabled: true, LiveStatus: lb_domains.StatusUp, ReadyStatus: lb_domains.StatusUp, }, }, } slist = lb_domains.RuleMethodList{ RuleAttributeMeta: lb_domains.RuleAttributeMeta{ AttributeMeta: lb_domains.AttributeMeta{ LBDomainID: "b0000000000001", }, RuleResourceName: "rule-1", }, Items: []lb_domains.RuleMethod{s1, s2}, } }) Describe("RuleMethod", func() { Context("Read", func() { BeforeEach(func() { httpmock.RegisterResponder(http.MethodGet, "http://localhost/lb_domains/b0000000000001/rules/rule-1/rule_methods/method-1", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "76D7462F50E3417C96898A827E0D1EC1", "result": { "priority": 10, "method": { "resource_name": "method-1", "mtype": "entry_a", "enabled": true, "live_status": "up", "ready_status": "down" } } }`))) httpmock.RegisterResponder(http.MethodGet, "http://localhost/lb_domains/b0000000000001/rules/rule-1/rule_methods/method-2", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "B10F0042282A46C18BFB440B5B58BF8C", "result": { "method": { "resource_name": "method-2", "mtype": "entry_a", "enabled": true, "live_status": "up", "ready_status": "up" } } }`))) }) AfterEach(func() { httpmock.Reset() }) When("returns LBDomain m1", func() { BeforeEach(func() { c = lb_domains.RuleMethod{ RuleAttributeMeta: lb_domains.RuleAttributeMeta{ AttributeMeta: lb_domains.AttributeMeta{ LBDomainID: "b0000000000001", }, RuleResourceName: "rule-1", }, Method: &lb_domains.RuleMethodPropsCommon{ ResourceName: "method-1", }, } reqId, err = cl.Read(context.Background(), &c) }) It("returns normal", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal("76D7462F50E3417C96898A827E0D1EC1")) Expect(c).To(Equal(s1)) }) }) When("returns LBDomain m2", func() { BeforeEach(func() { c = lb_domains.RuleMethod{ RuleAttributeMeta: lb_domains.RuleAttributeMeta{ AttributeMeta: lb_domains.AttributeMeta{ LBDomainID: "b0000000000001", }, RuleResourceName: "rule-1", }, Method: &lb_domains.RuleMethodPropsCommon{ ResourceName: "method-2", }, } reqId, err = cl.Read(context.Background(), &c) }) It("returns normal", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal("B10F0042282A46C18BFB440B5B58BF8C")) Expect(c).To(Equal(s2)) }) }) }) Context("Create", func() { id1, bs1 := testtool.CreateAsyncResponse() BeforeEach(func() { httpmock.RegisterResponder(http.MethodPost, "http://localhost/lb_domains/b0000000000001/rules/rule-1/rule_methods", httpmock.NewBytesResponder(202, bs1)) reqId, err = cl.Create(context.Background(), &s1, nil) }) AfterEach(func() { httpmock.Reset() }) It("returns job_id", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal(id1)) }) It("patch json", func() { Expect(cl.RequestBody["/lb_domains/b0000000000001/rules/rule-1/rule_methods"]).To(MatchJSON(`{ "priority": 10, "method": { "resource_name": "method-1", "mtype": "entry_a", "enabled": true } }`)) }) }) Context("Update", func() { id1, bs1 := testtool.CreateAsyncResponse() BeforeEach(func() { httpmock.RegisterResponder(http.MethodPatch, "http://localhost/lb_domains/b0000000000001/rules/rule-1/rule_methods/method-1", httpmock.NewBytesResponder(202, bs1)) reqId, err = cl.Update(context.Background(), &s1, nil) }) AfterEach(func() { httpmock.Reset() }) It("returns job_id", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal(id1)) }) It("patch json", func() { Expect(cl.RequestBody["/lb_domains/b0000000000001/rules/rule-1/rule_methods/method-1"]).To(MatchJSON(`{ "priority": 10, "method": { "enabled": true } }`)) }) }) Context("SetPathParams", func() { When("no arguments, nothing to do", func() { BeforeEach(func() { err = s1.SetPathParams() }) It("returns error", func() { Expect(err).To(Succeed()) }) }) When("enough arguments", func() { BeforeEach(func() { err = s1.SetPathParams("b0000000000010", "rule-10", "method-10") }) It("not returns error", func() { Expect(err).To(Succeed()) }) It("can set LBDomainID", func() { Expect(s1.LBDomainID).To(Equal("b0000000000010")) Expect(s1.RuleResourceName).To(Equal("rule-10")) Expect(s1.GetMethodResourceName()).To(Equal("method-10")) }) }) When("arguments has extra value", func() { BeforeEach(func() { err = s1.SetPathParams("b0000000000010", "rule-10", "method-10", 1) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) When("arguments type missmatch", func() { BeforeEach(func() { err = s1.SetPathParams("b0000000000010", "rule-10", 1) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) }) Context("api.Spec common test", func() { var nilSpec *lb_domains.RuleMethod testtool.TestDeepCopyObject(&s1, nilSpec) testtool.TestGetName(&s1, "rule_methods") Context("GetPathMethod", func() { When("action is ActionRead", func() { testtool.TestGetPathMethod(&s1, api.ActionRead, http.MethodGet, "/lb_domains/b0000000000001/rules/rule-1/rule_methods/method-1") }) When("action is ActionUpdate", func() { testtool.TestGetPathMethod(&s1, api.ActionUpdate, http.MethodPatch, "/lb_domains/b0000000000001/rules/rule-1/rule_methods/method-1") }) When("action is ActionDelete", func() { testtool.TestGetPathMethod(&s1, api.ActionDelete, http.MethodDelete, "/lb_domains/b0000000000001/rules/rule-1/rule_methods/method-1") }) When("action is ActionCreate", func() { testtool.TestGetPathMethod(&s1, api.ActionCreate, http.MethodPost, "/lb_domains/b0000000000001/rules/rule-1/rule_methods") }) When("action is other", func() { testtool.TestGetPathMethod(&s1, api.ActionApply, "", "") }) }) }) }) Describe("RuleMethodList", func() { var c lb_domains.RuleMethodList Context("List", func() { BeforeEach(func() { httpmock.RegisterResponder(http.MethodGet, "http://localhost/lb_domains/b0000000000001/rules/rule-1/rule_methods", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "2C18922432DC48D485613F5383A7ED8E", "results": [ { "priority": 10, "method": { "resource_name": "method-1", "mtype": "entry_a", "enabled": true, "live_status": "up", "ready_status": "down" } }, { "method": { "resource_name": "method-2", "mtype": "entry_a", "enabled": true, "live_status": "up", "ready_status": "up" } } ] }`))) }) AfterEach(func() { httpmock.Reset() }) When("returns list ", func() { BeforeEach(func() { c = lb_domains.RuleMethodList{ RuleAttributeMeta: lb_domains.RuleAttributeMeta{ AttributeMeta: lb_domains.AttributeMeta{ LBDomainID: "b0000000000001", }, RuleResourceName: "rule-1", }, } reqId, err = cl.List(context.Background(), &c, nil) }) It("returns normal", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal("2C18922432DC48D485613F5383A7ED8E")) Expect(c).To(Equal(slist)) }) }) }) Context("SetPathParams", func() { When("no arguments, nothing to do", func() { BeforeEach(func() { err = slist.SetPathParams() }) It("returns error", func() { Expect(err).To(Succeed()) }) }) When("enough arguments", func() { BeforeEach(func() { err = slist.SetPathParams("b0000000000010", "rule-10") }) It("not returns error", func() { Expect(err).To(Succeed()) }) It("can set LBDomainID", func() { Expect(slist.LBDomainID).To(Equal("b0000000000010")) Expect(slist.RuleResourceName).To(Equal("rule-10")) }) }) When("arguments has extra value", func() { BeforeEach(func() { err = slist.SetPathParams("b0000000000010", "rule-1", 2) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) When("arguments type missmatch", func() { BeforeEach(func() { err = slist.SetPathParams("b0000000000010", 2) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) }) Context("api.Spec common test", func() { var nilSpec *lb_domains.RuleMethodList testtool.TestDeepCopyObject(&slist, nilSpec) testtool.TestGetName(&slist, "rule_methods") }) Context("api.ListSpec common test", func() { testtool.TestGetItems(&slist, &slist.Items) testtool.TestLen(&slist, 2) Context("Index", func() { When("index exist", func() { It("returns item", func() { Expect(slist.Index(0)).To(Equal(s1)) }) }) }) }) }) }) golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/lb_domains/rule_test.go000066400000000000000000000211161437707610400236020ustar00rootroot00000000000000package lb_domains_test import ( "context" "net/http" "github.com/jarcoal/httpmock" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" api "github.com/mimuret/golang-iij-dpf/pkg/api" "github.com/mimuret/golang-iij-dpf/pkg/apis/dpf/v1/lb_domains" "github.com/mimuret/golang-iij-dpf/pkg/testtool" ) var _ = Describe("Rule", func() { var ( c lb_domains.Rule cl *testtool.TestClient err error reqId string s1, s2 lb_domains.Rule slist lb_domains.RuleList ) BeforeEach(func() { cl = testtool.NewTestClient("", "http://localhost", nil) s1 = lb_domains.Rule{ AttributeMeta: lb_domains.AttributeMeta{ LBDomainID: "b0000000000001", }, ResourceName: "rule-1", Name: "rule#1", Description: "rule 1 comment", Methods: []lb_domains.RuleMethod{}, } s2 = lb_domains.Rule{ AttributeMeta: lb_domains.AttributeMeta{ LBDomainID: "b0000000000001", }, ResourceName: "rule-2", Name: "rule#2", Description: "rule 2 comment", Methods: []lb_domains.RuleMethod{}, } slist = lb_domains.RuleList{ AttributeMeta: lb_domains.AttributeMeta{ LBDomainID: "b0000000000001", }, Items: []lb_domains.Rule{s1, s2}, } }) Describe("Rule", func() { Context("Read", func() { BeforeEach(func() { httpmock.RegisterResponder(http.MethodGet, "http://localhost/lb_domains/b0000000000001/rules/rule-1", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "76D7462F50E3417C96898A827E0D1EC1", "result": { "resource_name": "rule-1", "name": "rule#1", "description": "rule 1 comment", "methods": [] } }`))) httpmock.RegisterResponder(http.MethodGet, "http://localhost/lb_domains/b0000000000001/rules/rule-2", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "B10F0042282A46C18BFB440B5B58BF8C", "result": { "resource_name": "rule-2", "name": "rule#2", "description": "rule 2 comment", "methods": [] } }`))) }) AfterEach(func() { httpmock.Reset() }) When("returns LBDomain m1", func() { BeforeEach(func() { c = lb_domains.Rule{ AttributeMeta: lb_domains.AttributeMeta{ LBDomainID: "b0000000000001", }, ResourceName: "rule-1", } reqId, err = cl.Read(context.Background(), &c) }) It("returns normal", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal("76D7462F50E3417C96898A827E0D1EC1")) Expect(c).To(Equal(s1)) }) }) When("returns LBDomain m2", func() { BeforeEach(func() { c = lb_domains.Rule{ AttributeMeta: lb_domains.AttributeMeta{ LBDomainID: "b0000000000001", }, ResourceName: "rule-2", } reqId, err = cl.Read(context.Background(), &c) }) It("returns normal", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal("B10F0042282A46C18BFB440B5B58BF8C")) Expect(c).To(Equal(s2)) }) }) }) Context("Create", func() { id1, bs1 := testtool.CreateAsyncResponse() BeforeEach(func() { httpmock.RegisterResponder(http.MethodPost, "http://localhost/lb_domains/b0000000000001/rules", httpmock.NewBytesResponder(202, bs1)) reqId, err = cl.Create(context.Background(), &s1, nil) }) AfterEach(func() { httpmock.Reset() }) It("returns job_id", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal(id1)) }) It("post json", func() { Expect(cl.RequestBody["/lb_domains/b0000000000001/rules"]).To(MatchJSON(`{ "resource_name": "rule-1", "name": "rule#1", "description": "rule 1 comment" }`)) }) }) Context("Update", func() { id1, bs1 := testtool.CreateAsyncResponse() BeforeEach(func() { httpmock.RegisterResponder(http.MethodPatch, "http://localhost/lb_domains/b0000000000001/rules/rule-1", httpmock.NewBytesResponder(202, bs1)) reqId, err = cl.Update(context.Background(), &s1, nil) }) AfterEach(func() { httpmock.Reset() }) It("returns job_id", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal(id1)) }) It("post json", func() { Expect(cl.RequestBody["/lb_domains/b0000000000001/rules/rule-1"]).To(MatchJSON(`{ "name": "rule#1", "description": "rule 1 comment" }`)) }) }) Context("SetPathParams", func() { When("no arguments, nothing to do", func() { BeforeEach(func() { err = s1.SetPathParams() }) It("returns error", func() { Expect(err).To(Succeed()) }) }) When("enough arguments", func() { BeforeEach(func() { err = s1.SetPathParams("b0000000000010", "id1") }) It("not returns error", func() { Expect(err).To(Succeed()) }) It("can set LBDomainID", func() { Expect(s1.LBDomainID).To(Equal("b0000000000010")) Expect(s1.ResourceName).To(Equal("id1")) }) }) When("arguments has extra value", func() { BeforeEach(func() { err = s1.SetPathParams("b0000000000010", "id1", 2) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) When("arguments type missmatch (LBDomainID)", func() { BeforeEach(func() { err = s1.SetPathParams(2, "id1") }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) }) Context("api.Spec common test", func() { var nilSpec *lb_domains.Rule testtool.TestDeepCopyObject(&s1, nilSpec) testtool.TestGetName(&s1, "rules") Context("GetPathMethod", func() { When("action is ActionRead", func() { testtool.TestGetPathMethod(&s1, api.ActionRead, http.MethodGet, "/lb_domains/b0000000000001/rules/rule-1") }) When("action is ActionUpdate", func() { testtool.TestGetPathMethod(&s1, api.ActionUpdate, http.MethodPatch, "/lb_domains/b0000000000001/rules/rule-1") }) When("action is ActionDelete", func() { testtool.TestGetPathMethod(&s1, api.ActionDelete, http.MethodDelete, "/lb_domains/b0000000000001/rules/rule-1") }) When("action is ActionCreate", func() { testtool.TestGetPathMethod(&s1, api.ActionCreate, http.MethodPost, "/lb_domains/b0000000000001/rules") }) When("action is other", func() { testtool.TestGetPathMethod(&s1, api.ActionApply, "", "") }) }) }) }) Describe("RuleList", func() { var c lb_domains.RuleList Context("List", func() { BeforeEach(func() { httpmock.RegisterResponder(http.MethodGet, "http://localhost/lb_domains/b0000000000001/rules", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "2C18922432DC48D485613F5383A7ED8E", "results": [ { "resource_name": "rule-1", "name": "rule#1", "description": "rule 1 comment", "Methods": [] }, { "resource_name": "rule-2", "name": "rule#2", "description": "rule 2 comment", "Methods": [] } ] }`))) }) AfterEach(func() { httpmock.Reset() }) When("returns list ", func() { BeforeEach(func() { c = lb_domains.RuleList{ AttributeMeta: lb_domains.AttributeMeta{ LBDomainID: "b0000000000001", }, } reqId, err = cl.List(context.Background(), &c, nil) }) It("returns normal", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal("2C18922432DC48D485613F5383A7ED8E")) Expect(c).To(Equal(slist)) }) }) }) Context("SetPathParams", func() { When("no arguments, nothing to do", func() { BeforeEach(func() { err = slist.SetPathParams() }) It("returns error", func() { Expect(err).To(Succeed()) }) }) When("enough arguments", func() { BeforeEach(func() { err = slist.SetPathParams("b0000000000010") }) It("not returns error", func() { Expect(err).To(Succeed()) }) It("can set LBDomainID", func() { Expect(slist.LBDomainID).To(Equal("b0000000000010")) }) }) When("arguments has extra value", func() { BeforeEach(func() { err = slist.SetPathParams("b0000000000010", 2) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) When("arguments type missmatch (LBDomainID)", func() { BeforeEach(func() { err = slist.SetPathParams(2) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) }) Context("api.Spec common test", func() { var nilSpec *lb_domains.RuleList testtool.TestDeepCopyObject(&slist, nilSpec) testtool.TestGetName(&slist, "rules") }) Context("api.ListSpec common test", func() { testtool.TestGetItems(&slist, &slist.Items) testtool.TestLen(&slist, 2) Context("Index", func() { When("index exist", func() { It("returns item", func() { Expect(slist.Index(0)).To(Equal(s1)) }) }) }) }) }) }) golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/lb_domains/site.go000066400000000000000000000045411437707610400225430ustar00rootroot00000000000000package lb_domains import ( "github.com/mimuret/golang-iij-dpf/pkg/api" "github.com/mimuret/golang-iij-dpf/pkg/apis" ) type SiteRRType string const ( SiteRRTypeA SiteRRType = "A" SiteRRTypeAAAA SiteRRType = "AAAA" SiteRRTypeCNAME SiteRRType = "CNAME" ) var _ ChildSpec = &Site{} // +k8s:deepcopy-gen:interfaces=github.com/mimuret/golang-iij-dpf/pkg/api.Object type Site struct { AttributeMeta ResourceName string `read:"resource_name" create:"resource_name,omitempty" apply:"resource_name"` Name string `read:"name" create:"name" update:"name" apply:"name"` RRType SiteRRType `read:"rrtype" create:"rrtype" apply:"rrtype"` Description string `read:"description" create:"description" update:"description" apply:"description"` LiveStatus Status `read:"live_status"` Endpoints []Endpoint `read:"endpoints" apply:"endpoints"` } func (c *Site) Init() { for i := range c.Endpoints { c.Endpoints[i].AttributeMeta = c.AttributeMeta c.Endpoints[i].SiteResourceName = c.ResourceName c.Endpoints[i].Init() } } func (c *Site) GetName() string { return "sites" } func (c *Site) GetResourceName() string { return c.ResourceName } func (c *Site) SetResourceName(resourceName string) { c.ResourceName = resourceName } func (c *Site) GetPathMethod(action api.Action) (string, string) { return GetPathMethodForChildSpec(action, c) } func (c *Site) SetPathParams(args ...interface{}) error { return apis.SetPathParams(args, &c.LBDomainID, &c.ResourceName) } var _ ListSpec = &SiteList{} // +k8s:deepcopy-gen:interfaces=github.com/mimuret/golang-iij-dpf/pkg/api.Object type SiteList struct { AttributeMeta api.Count Items []Site `read:"items"` } func (c *SiteList) GetName() string { return "sites" } func (c *SiteList) GetItems() interface{} { return &c.Items } func (c *SiteList) Len() int { return len(c.Items) } func (c *SiteList) Index(i int) interface{} { return c.Items[i] } func (c *SiteList) GetPathMethod(action api.Action) (string, string) { return GetPathMethodForListSpec(action, c) } func (c *SiteList) Init() { for i := range c.Items { c.Items[i].AttributeMeta = c.AttributeMeta c.Items[i].Init() } } func (c *SiteList) SetPathParams(args ...interface{}) error { return apis.SetPathParams(args, &c.LBDomainID) } func init() { register(&Site{}, &SiteList{}) } golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/lb_domains/site_test.go000066400000000000000000000217171437707610400236060ustar00rootroot00000000000000package lb_domains_test import ( "context" "net/http" "github.com/jarcoal/httpmock" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" api "github.com/mimuret/golang-iij-dpf/pkg/api" "github.com/mimuret/golang-iij-dpf/pkg/apis/dpf/v1/lb_domains" "github.com/mimuret/golang-iij-dpf/pkg/testtool" ) var _ = Describe("Site", func() { var ( c lb_domains.Site cl *testtool.TestClient err error reqId string s1, s2 lb_domains.Site slist lb_domains.SiteList ) BeforeEach(func() { cl = testtool.NewTestClient("", "http://localhost", nil) s1 = lb_domains.Site{ AttributeMeta: lb_domains.AttributeMeta{ LBDomainID: "b0000000000001", }, ResourceName: "site-1", Name: "site-a", Description: "site A comment", RRType: lb_domains.SiteRRTypeA, LiveStatus: lb_domains.StatusDown, Endpoints: []lb_domains.Endpoint{}, } s2 = lb_domains.Site{ AttributeMeta: lb_domains.AttributeMeta{ LBDomainID: "b0000000000001", }, ResourceName: "rule-2", Name: "site-aaaa", Description: "site AAAA comment", RRType: lb_domains.SiteRRTypeAAAA, LiveStatus: lb_domains.StatusUp, Endpoints: []lb_domains.Endpoint{}, } slist = lb_domains.SiteList{ AttributeMeta: lb_domains.AttributeMeta{ LBDomainID: "b0000000000001", }, Items: []lb_domains.Site{s1, s2}, } }) Describe("Site", func() { Context("Read", func() { BeforeEach(func() { httpmock.RegisterResponder(http.MethodGet, "http://localhost/lb_domains/b0000000000001/sites/site-1", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "76D7462F50E3417C96898A827E0D1EC1", "result": { "resource_name": "site-1", "name": "site-a", "description": "site A comment", "rrtype": "A", "live_status": "down", "endpoints": [] } }`))) httpmock.RegisterResponder(http.MethodGet, "http://localhost/lb_domains/b0000000000001/sites/rule-2", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "B10F0042282A46C18BFB440B5B58BF8C", "result": { "resource_name": "rule-2", "name": "site-aaaa", "description": "site AAAA comment", "rrtype": "AAAA", "live_status": "up", "endpoints": [] } }`))) }) AfterEach(func() { httpmock.Reset() }) When("returns LBDomain m1", func() { BeforeEach(func() { c = lb_domains.Site{ AttributeMeta: lb_domains.AttributeMeta{ LBDomainID: "b0000000000001", }, ResourceName: "site-1", } reqId, err = cl.Read(context.Background(), &c) }) It("returns normal", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal("76D7462F50E3417C96898A827E0D1EC1")) Expect(c).To(Equal(s1)) }) }) When("returns LBDomain m2", func() { BeforeEach(func() { c = lb_domains.Site{ AttributeMeta: lb_domains.AttributeMeta{ LBDomainID: "b0000000000001", }, ResourceName: "rule-2", } reqId, err = cl.Read(context.Background(), &c) }) It("returns normal", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal("B10F0042282A46C18BFB440B5B58BF8C")) Expect(c).To(Equal(s2)) }) }) }) Context("Create", func() { id1, bs1 := testtool.CreateAsyncResponse() BeforeEach(func() { httpmock.RegisterResponder(http.MethodPost, "http://localhost/lb_domains/b0000000000001/sites", httpmock.NewBytesResponder(202, bs1)) reqId, err = cl.Create(context.Background(), &s1, nil) }) AfterEach(func() { httpmock.Reset() }) It("returns job_id", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal(id1)) }) It("post json", func() { Expect(cl.RequestBody["/lb_domains/b0000000000001/sites"]).To(MatchJSON(`{ "resource_name": "site-1", "name": "site-a", "rrtype": "A", "description": "site A comment" }`)) }) }) Context("Update", func() { id1, bs1 := testtool.CreateAsyncResponse() BeforeEach(func() { httpmock.RegisterResponder(http.MethodPatch, "http://localhost/lb_domains/b0000000000001/sites/site-1", httpmock.NewBytesResponder(202, bs1)) reqId, err = cl.Update(context.Background(), &s1, nil) }) AfterEach(func() { httpmock.Reset() }) It("returns job_id", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal(id1)) }) It("post json", func() { Expect(cl.RequestBody["/lb_domains/b0000000000001/sites/site-1"]).To(MatchJSON(`{ "name": "site-a", "description": "site A comment" }`)) }) }) Context("SetPathParams", func() { When("no arguments, nothing to do", func() { BeforeEach(func() { err = s1.SetPathParams() }) It("returns error", func() { Expect(err).To(Succeed()) }) }) When("enough arguments", func() { BeforeEach(func() { err = s1.SetPathParams("b0000000000010", "id1") }) It("not returns error", func() { Expect(err).To(Succeed()) }) It("can set LBDomainID", func() { Expect(s1.LBDomainID).To(Equal("b0000000000010")) Expect(s1.ResourceName).To(Equal("id1")) }) }) When("arguments has extra value", func() { BeforeEach(func() { err = s1.SetPathParams("b0000000000010", "id1", 2) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) When("arguments type missmatch", func() { BeforeEach(func() { err = s1.SetPathParams(2, "id1") }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) }) Context("api.Spec common test", func() { var nilSpec *lb_domains.Site testtool.TestDeepCopyObject(&s1, nilSpec) testtool.TestGetName(&s1, "sites") Context("GetPathMethod", func() { When("action is ActionRead", func() { testtool.TestGetPathMethod(&s1, api.ActionRead, http.MethodGet, "/lb_domains/b0000000000001/sites/site-1") }) When("action is ActionUpdate", func() { testtool.TestGetPathMethod(&s1, api.ActionUpdate, http.MethodPatch, "/lb_domains/b0000000000001/sites/site-1") }) When("action is ActionDelete", func() { testtool.TestGetPathMethod(&s1, api.ActionDelete, http.MethodDelete, "/lb_domains/b0000000000001/sites/site-1") }) When("action is ActionCreate", func() { testtool.TestGetPathMethod(&s1, api.ActionCreate, http.MethodPost, "/lb_domains/b0000000000001/sites") }) When("action is other", func() { testtool.TestGetPathMethod(&s1, api.ActionApply, "", "") }) }) }) }) Describe("SiteList", func() { var c lb_domains.SiteList Context("List", func() { BeforeEach(func() { httpmock.RegisterResponder(http.MethodGet, "http://localhost/lb_domains/b0000000000001/sites", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "2C18922432DC48D485613F5383A7ED8E", "results": [ { "resource_name": "site-1", "name": "site-a", "description": "site A comment", "rrtype": "A", "live_status": "down", "endpoints": [] }, { "resource_name": "rule-2", "name": "site-aaaa", "description": "site AAAA comment", "rrtype": "AAAA", "live_status": "up", "endpoints": [] } ] }`))) }) AfterEach(func() { httpmock.Reset() }) When("returns list ", func() { BeforeEach(func() { c = lb_domains.SiteList{ AttributeMeta: lb_domains.AttributeMeta{ LBDomainID: "b0000000000001", }, } reqId, err = cl.List(context.Background(), &c, nil) }) It("returns normal", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal("2C18922432DC48D485613F5383A7ED8E")) Expect(c).To(Equal(slist)) }) }) }) Context("SetPathParams", func() { When("no arguments, nothing to do", func() { BeforeEach(func() { err = slist.SetPathParams() }) It("returns error", func() { Expect(err).To(Succeed()) }) }) When("enough arguments", func() { BeforeEach(func() { err = slist.SetPathParams("b0000000000010") }) It("not returns error", func() { Expect(err).To(Succeed()) }) It("can set LBDomainID", func() { Expect(slist.LBDomainID).To(Equal("b0000000000010")) }) }) When("arguments has extra value", func() { BeforeEach(func() { err = slist.SetPathParams("b0000000000010", 2) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) When("arguments type missmatch", func() { BeforeEach(func() { err = slist.SetPathParams(2) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) }) Context("api.Spec common test", func() { var nilSpec *lb_domains.SiteList testtool.TestDeepCopyObject(&slist, nilSpec) testtool.TestGetName(&slist, "sites") }) Context("api.ListSpec common test", func() { testtool.TestGetItems(&slist, &slist.Items) testtool.TestLen(&slist, 2) Context("Index", func() { When("index exist", func() { It("returns item", func() { Expect(slist.Index(0)).To(Equal(s1)) }) }) }) }) }) }) golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/lb_domains/status.go000066400000000000000000000001321437707610400231120ustar00rootroot00000000000000package lb_domains type Status string const ( StatusUp = "up" StatusDown = "down" ) golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/lb_domains/testdata/000077500000000000000000000000001437707610400230555ustar00rootroot00000000000000golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/lb_domains/testdata/config_get.json000066400000000000000000000101551437707610400260560ustar00rootroot00000000000000{ "request_id": "76D7462F50E3417C96898A827E0D1EC1", "result": { "sites": [ { "resource_name": "site-a", "name": "site(A)", "description": "site(A) comment", "rrtype": "A", "live_status": "down", "endpoints": [ { "resource_name": "endpoint-1", "name": "host-1", "monitoring_target": "www.example.jp.", "description": "endpoint#1", "weight": 1, "manual_failback": false, "manual_failover": false, "enabled": false, "live_status": "up", "ready_status": "down", "rdata": [ { "value": "192.168.0.1" }, { "value": "192.168.1.1" } ], "monitorings": [ { "resource_name": "id1", "enabled": true, "name": "monitoring-1", "mtype": "ping", "description": "comment 1", "props": { "location": "all", "interval": 30, "holdtime": 0, "timeout": 1 } } ] } ] }, { "resource_name": "site-aaaa", "name": "site(AAAA)", "description": "site(AAAA) comment", "rrtype": "AAAA", "live_status": "up", "endpoints": [ { "resource_name": "endpoint-2", "name": "host-2", "monitoring_target": "2001:db8::1", "description": "endpoint#2", "weight": 255, "manual_failback": true, "manual_failover": true, "enabled": true, "live_status": "down", "ready_status": "down", "rdata": [ { "value": "2001:db8::1" }, { "value": "2001:db8::2" } ], "monitorings": [ { "resource_name": "id1", "enabled": true, "name": "monitoring-1", "mtype": "ping", "description": "comment 1", "props": { "location": "all", "interval": 30, "holdtime": 0, "timeout": 1 } } ] } ] } ], "monitorings": [ { "resource_name": "id1", "name": "monitoring-1", "mtype": "ping", "description": "comment 1", "props": { "location": "all", "interval": 30, "holdtime": 0, "timeout": 1 } } ], "rules": [ { "resource_name": "rule-a", "name": "default", "description": "default rule", "methods": [ { "method": { "resource_name": "entry-a-1", "mtype": "entry_a", "enabled": true, "live_status": "up", "ready_status": "down" } }, { "method": { "resource_name": "entry-aaaa-1", "mtype": "entry_aaaa", "enabled": true, "live_status": "up", "ready_status": "down" } }, { "method": { "resource_name": "exit-a-1", "parent_resource_name": "entry-a-1", "site_resource_name": "site-a", "mtype": "exit_site", "enabled": true, "live_status": "up", "ready_status": "down" } }, { "method": { "resource_name": "exit-aaaa-1", "parent_resource_name": "entry-aaaa-1", "site_resource_name": "site-aaaa", "mtype": "exit_site", "enabled": true, "live_status": "up", "ready_status": "down" } } ] } ] } }golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/lb_domains/testdata/config_put.json000066400000000000000000000053651437707610400261160ustar00rootroot00000000000000{ "sites": [ { "resource_name": "site-a", "name": "site(A)", "description": "site(A) comment", "rrtype": "A", "endpoints": [ { "resource_name": "endpoint-1", "name": "host-1", "monitoring_target": "www.example.jp.", "description": "endpoint#1", "weight": 1, "manual_failback": false, "manual_failover": false, "enabled": false, "rdata": [ { "value": "192.168.0.1" }, { "value": "192.168.1.1" } ], "monitorings": [ { "resource_name": "id1", "enabled": true } ] } ] }, { "resource_name": "site-aaaa", "name": "site(AAAA)", "description": "site(AAAA) comment", "rrtype": "AAAA", "endpoints": [ { "resource_name": "endpoint-2", "name": "host-2", "monitoring_target": "2001:db8::1", "description": "endpoint#2", "weight": 255, "manual_failback": true, "manual_failover": true, "enabled": true, "rdata": [ { "value": "2001:db8::1" }, { "value": "2001:db8::2" } ], "monitorings": [ { "resource_name": "id1", "enabled": true } ] } ] } ], "monitorings": [ { "resource_name": "id1", "name": "monitoring-1", "mtype": "ping", "description": "comment 1", "props": { "location": "all", "interval": 30, "holdtime": 0, "timeout": 1 } } ], "rules": [ { "resource_name": "rule-a", "name": "default", "description": "default rule", "methods": [ { "method": { "resource_name": "entry-a-1", "mtype": "entry_a", "enabled": true } }, { "method": { "resource_name": "entry-aaaa-1", "mtype": "entry_aaaa", "enabled": true } }, { "method": { "resource_name": "exit-a-1", "parent_resource_name": "entry-a-1", "site_resource_name": "site-a", "mtype": "exit_site", "enabled": true } }, { "method": { "resource_name": "exit-aaaa-1", "parent_resource_name": "entry-aaaa-1", "site_resource_name": "site-aaaa", "mtype": "exit_site", "enabled": true } } ] } ] }golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/var.go000066400000000000000000000000501437707610400202470ustar00rootroot00000000000000package dpfv1 const Version = "dpf/v1" golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/zones/000077500000000000000000000000001437707610400202735ustar00rootroot00000000000000golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/zones/ZZ_deepcopy_generated.go000066400000000000000000000455121437707610400251020ustar00rootroot00000000000000//go:build !ignore_autogenerated // +build !ignore_autogenerated /* MIT License Copyright (c) 2021 Manabu Sonoda 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. */ // Code generated by deepcopy-gen. DO NOT EDIT. package zones import ( net "net" api "github.com/mimuret/golang-iij-dpf/pkg/api" core "github.com/mimuret/golang-iij-dpf/pkg/apis/dpf/v1/core" ) // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *AttributeMeta) DeepCopyInto(out *AttributeMeta) { *out = *in return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AttributeMeta. func (in *AttributeMeta) DeepCopy() *AttributeMeta { if in == nil { return nil } out := new(AttributeMeta) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Contract) DeepCopyInto(out *Contract) { *out = *in out.AttributeMeta = in.AttributeMeta out.Contract = in.Contract return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Contract. func (in *Contract) DeepCopy() *Contract { if in == nil { return nil } out := new(Contract) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new api.Object. func (in *Contract) DeepCopyObject() api.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *CurrentRecordList) DeepCopyInto(out *CurrentRecordList) { *out = *in out.AttributeMeta = in.AttributeMeta out.Count = in.Count if in.Items != nil { in, out := &in.Items, &out.Items *out = make([]Record, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CurrentRecordList. func (in *CurrentRecordList) DeepCopy() *CurrentRecordList { if in == nil { return nil } out := new(CurrentRecordList) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new api.Object. func (in *CurrentRecordList) DeepCopyObject() api.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *DefaultTTL) DeepCopyInto(out *DefaultTTL) { *out = *in out.AttributeMeta = in.AttributeMeta return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DefaultTTL. func (in *DefaultTTL) DeepCopy() *DefaultTTL { if in == nil { return nil } out := new(DefaultTTL) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new api.Object. func (in *DefaultTTL) DeepCopyObject() api.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *DefaultTTLDiff) DeepCopyInto(out *DefaultTTLDiff) { *out = *in if in.New != nil { in, out := &in.New, &out.New *out = new(DefaultTTL) **out = **in } if in.Old != nil { in, out := &in.Old, &out.Old *out = new(DefaultTTL) **out = **in } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DefaultTTLDiff. func (in *DefaultTTLDiff) DeepCopy() *DefaultTTLDiff { if in == nil { return nil } out := new(DefaultTTLDiff) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *DefaultTTLDiffList) DeepCopyInto(out *DefaultTTLDiffList) { *out = *in out.AttributeMeta = in.AttributeMeta if in.Items != nil { in, out := &in.Items, &out.Items *out = make([]DefaultTTLDiff, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DefaultTTLDiffList. func (in *DefaultTTLDiffList) DeepCopy() *DefaultTTLDiffList { if in == nil { return nil } out := new(DefaultTTLDiffList) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new api.Object. func (in *DefaultTTLDiffList) DeepCopyObject() api.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Dnssec) DeepCopyInto(out *Dnssec) { *out = *in out.AttributeMeta = in.AttributeMeta return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Dnssec. func (in *Dnssec) DeepCopy() *Dnssec { if in == nil { return nil } out := new(Dnssec) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new api.Object. func (in *Dnssec) DeepCopyObject() api.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *DnssecKskRollover) DeepCopyInto(out *DnssecKskRollover) { *out = *in out.AttributeMeta = in.AttributeMeta return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DnssecKskRollover. func (in *DnssecKskRollover) DeepCopy() *DnssecKskRollover { if in == nil { return nil } out := new(DnssecKskRollover) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new api.Object. func (in *DnssecKskRollover) DeepCopyObject() api.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *DsRecord) DeepCopyInto(out *DsRecord) { *out = *in in.TransitAt.DeepCopyInto(&out.TransitAt) return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DsRecord. func (in *DsRecord) DeepCopy() *DsRecord { if in == nil { return nil } out := new(DsRecord) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *DsRecordList) DeepCopyInto(out *DsRecordList) { *out = *in out.AttributeMeta = in.AttributeMeta if in.Items != nil { in, out := &in.Items, &out.Items *out = make([]DsRecord, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DsRecordList. func (in *DsRecordList) DeepCopy() *DsRecordList { if in == nil { return nil } out := new(DsRecordList) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new api.Object. func (in *DsRecordList) DeepCopyObject() api.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *History) DeepCopyInto(out *History) { *out = *in in.CommittedAt.DeepCopyInto(&out.CommittedAt) return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new History. func (in *History) DeepCopy() *History { if in == nil { return nil } out := new(History) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *HistoryList) DeepCopyInto(out *HistoryList) { *out = *in out.AttributeMeta = in.AttributeMeta out.Count = in.Count if in.Items != nil { in, out := &in.Items, &out.Items *out = make([]History, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new HistoryList. func (in *HistoryList) DeepCopy() *HistoryList { if in == nil { return nil } out := new(HistoryList) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new api.Object. func (in *HistoryList) DeepCopyObject() api.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *HistoryText) DeepCopyInto(out *HistoryText) { *out = *in out.AttributeMeta = in.AttributeMeta in.History.DeepCopyInto(&out.History) return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new HistoryText. func (in *HistoryText) DeepCopy() *HistoryText { if in == nil { return nil } out := new(HistoryText) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new api.Object. func (in *HistoryText) DeepCopyObject() api.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *LogList) DeepCopyInto(out *LogList) { *out = *in out.AttributeMeta = in.AttributeMeta out.Count = in.Count if in.Items != nil { in, out := &in.Items, &out.Items *out = make([]core.Log, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new LogList. func (in *LogList) DeepCopy() *LogList { if in == nil { return nil } out := new(LogList) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new api.Object. func (in *LogList) DeepCopyObject() api.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ManagedDnsList) DeepCopyInto(out *ManagedDnsList) { *out = *in out.AttributeMeta = in.AttributeMeta if in.Items != nil { in, out := &in.Items, &out.Items *out = make([]string, len(*in)) copy(*out, *in) } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ManagedDnsList. func (in *ManagedDnsList) DeepCopy() *ManagedDnsList { if in == nil { return nil } out := new(ManagedDnsList) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new api.Object. func (in *ManagedDnsList) DeepCopyObject() api.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Record) DeepCopyInto(out *Record) { *out = *in out.AttributeMeta = in.AttributeMeta if in.RData != nil { in, out := &in.RData, &out.RData *out = make(RecordRDATASlice, len(*in)) copy(*out, *in) } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Record. func (in *Record) DeepCopy() *Record { if in == nil { return nil } out := new(Record) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new api.Object. func (in *Record) DeepCopyObject() api.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *RecordDiff) DeepCopyInto(out *RecordDiff) { *out = *in if in.New != nil { in, out := &in.New, &out.New *out = new(Record) (*in).DeepCopyInto(*out) } if in.Old != nil { in, out := &in.Old, &out.Old *out = new(Record) (*in).DeepCopyInto(*out) } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new RecordDiff. func (in *RecordDiff) DeepCopy() *RecordDiff { if in == nil { return nil } out := new(RecordDiff) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *RecordDiffList) DeepCopyInto(out *RecordDiffList) { *out = *in out.AttributeMeta = in.AttributeMeta out.Count = in.Count if in.Items != nil { in, out := &in.Items, &out.Items *out = make([]RecordDiff, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new RecordDiffList. func (in *RecordDiffList) DeepCopy() *RecordDiffList { if in == nil { return nil } out := new(RecordDiffList) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new api.Object. func (in *RecordDiffList) DeepCopyObject() api.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *RecordList) DeepCopyInto(out *RecordList) { *out = *in out.AttributeMeta = in.AttributeMeta out.Count = in.Count if in.Items != nil { in, out := &in.Items, &out.Items *out = make([]Record, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new RecordList. func (in *RecordList) DeepCopy() *RecordList { if in == nil { return nil } out := new(RecordList) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new api.Object. func (in *RecordList) DeepCopyObject() api.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *RecordRDATA) DeepCopyInto(out *RecordRDATA) { *out = *in return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new RecordRDATA. func (in *RecordRDATA) DeepCopy() *RecordRDATA { if in == nil { return nil } out := new(RecordRDATA) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in RecordRDATASlice) DeepCopyInto(out *RecordRDATASlice) { { in := &in *out = make(RecordRDATASlice, len(*in)) copy(*out, *in) return } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new RecordRDATASlice. func (in RecordRDATASlice) DeepCopy() RecordRDATASlice { if in == nil { return nil } out := new(RecordRDATASlice) in.DeepCopyInto(out) return *out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ZoneApply) DeepCopyInto(out *ZoneApply) { *out = *in out.AttributeMeta = in.AttributeMeta return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ZoneApply. func (in *ZoneApply) DeepCopy() *ZoneApply { if in == nil { return nil } out := new(ZoneApply) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new api.Object. func (in *ZoneApply) DeepCopyObject() api.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ZoneProxy) DeepCopyInto(out *ZoneProxy) { *out = *in out.AttributeMeta = in.AttributeMeta return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ZoneProxy. func (in *ZoneProxy) DeepCopy() *ZoneProxy { if in == nil { return nil } out := new(ZoneProxy) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new api.Object. func (in *ZoneProxy) DeepCopyObject() api.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ZoneProxyHealthCheck) DeepCopyInto(out *ZoneProxyHealthCheck) { *out = *in if in.Address != nil { in, out := &in.Address, &out.Address *out = make(net.IP, len(*in)) copy(*out, *in) } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ZoneProxyHealthCheck. func (in *ZoneProxyHealthCheck) DeepCopy() *ZoneProxyHealthCheck { if in == nil { return nil } out := new(ZoneProxyHealthCheck) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ZoneProxyHealthCheckList) DeepCopyInto(out *ZoneProxyHealthCheckList) { *out = *in out.AttributeMeta = in.AttributeMeta if in.Items != nil { in, out := &in.Items, &out.Items *out = make([]ZoneProxyHealthCheck, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ZoneProxyHealthCheckList. func (in *ZoneProxyHealthCheckList) DeepCopy() *ZoneProxyHealthCheckList { if in == nil { return nil } out := new(ZoneProxyHealthCheckList) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new api.Object. func (in *ZoneProxyHealthCheckList) DeepCopyObject() api.Object { if c := in.DeepCopy(); c != nil { return c } return nil } golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/zones/common.go000066400000000000000000000026251437707610400221170ustar00rootroot00000000000000package zones import ( "fmt" "net/http" "github.com/mimuret/golang-iij-dpf/pkg/api" "github.com/mimuret/golang-iij-dpf/pkg/apis" "github.com/mimuret/golang-iij-dpf/pkg/schema" ) const groupName = "zones.api.dns-platform.jp/v1" func register(items ...apis.Spec) { schema.NewRegister(groupName).Add(items...) } type Spec interface { apis.Spec SetZoneID(string) GetZoneID() string } type ChildSpec interface { Spec GetID() int64 SetID(int64) } type ListSpec interface { api.ListSpec Spec } type CountableListSpec interface { api.CountableListSpec Spec } type AttributeMeta struct { ZoneID string `read:"-"` } // for ctl func (s *AttributeMeta) GetGroup() string { return groupName } func (s *AttributeMeta) SetZoneID(id string) { s.ZoneID = id } func (s *AttributeMeta) GetZoneID() string { return s.ZoneID } func GetPathMethodForListSpec(action api.Action, s ListSpec) (string, string) { switch action { case api.ActionList: return http.MethodGet, fmt.Sprintf("/zones/%s/%s", s.GetZoneID(), s.GetName()) case api.ActionCount: if _, ok := s.(api.CountableListSpec); ok { return http.MethodGet, fmt.Sprintf("/zones/%s/%s/count", s.GetZoneID(), s.GetName()) } } return "", "" } func GetReadPathMethodForSpec(action api.Action, s Spec) (string, string) { if action == api.ActionRead { return http.MethodGet, fmt.Sprintf("/zones/%s/%s", s.GetZoneID(), s.GetName()) } return "", "" } golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/zones/common_test.go000066400000000000000000000027011437707610400231510ustar00rootroot00000000000000package zones_test import ( "github.com/mimuret/golang-iij-dpf/pkg/apis/dpf/v1/zones" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("zones", func() { Context("AttributeMeta", func() { var meta zones.AttributeMeta BeforeEach(func() { meta = zones.AttributeMeta{} }) Context("GetGroup", func() { It("returns zones", func() { Expect(meta.GetGroup()).To(Equal("zones.api.dns-platform.jp/v1")) }) }) Context("GetZoneID", func() { When("default", func() { It("returns ", func() { Expect(meta.GetZoneID()).To(Equal("")) }) }) When("default", func() { BeforeEach(func() { meta.ZoneID = "id1" }) It("returns ZoneID", func() { Expect(meta.GetZoneID()).To(Equal("id1")) }) }) Context("SetZoneID", func() { BeforeEach(func() { meta.SetZoneID("id2") }) It("can set ZoneID", func() { Expect(meta.GetZoneID()).To(Equal("id2")) }) }) Context("DeepCopy", func() { var ( copy *zones.AttributeMeta nilMeta *zones.AttributeMeta ) When("AttributeMeta is not nil", func() { BeforeEach(func() { copy = meta.DeepCopy() }) It("returns copy ", func() { Expect(copy).To(Equal(&meta)) }) }) When("AttributeMeta is nil", func() { BeforeEach(func() { copy = nilMeta.DeepCopy() }) It("returns copy ", func() { Expect(copy).To(BeNil()) }) }) }) }) }) }) golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/zones/contract.go000066400000000000000000000012301437707610400224330ustar00rootroot00000000000000package zones import ( "github.com/mimuret/golang-iij-dpf/pkg/api" "github.com/mimuret/golang-iij-dpf/pkg/apis" "github.com/mimuret/golang-iij-dpf/pkg/apis/dpf/v1/core" ) var _ Spec = &Contract{} // +k8s:deepcopy-gen:interfaces=github.com/mimuret/golang-iij-dpf/pkg/api.Object type Contract struct { AttributeMeta core.Contract } func (c *Contract) GetName() string { return "contract" } func (c *Contract) GetPathMethod(action api.Action) (string, string) { return GetReadPathMethodForSpec(action, c) } func (c *Contract) SetPathParams(args ...interface{}) error { return apis.SetPathParams(args, &c.ZoneID) } func init() { register(&Contract{}) } golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/zones/contract_test.go000066400000000000000000000062401437707610400235000ustar00rootroot00000000000000package zones_test import ( "context" "net/http" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/jarcoal/httpmock" "github.com/mimuret/golang-iij-dpf/pkg/api" "github.com/mimuret/golang-iij-dpf/pkg/apis/dpf/v1/core" "github.com/mimuret/golang-iij-dpf/pkg/apis/dpf/v1/zones" "github.com/mimuret/golang-iij-dpf/pkg/testtool" "github.com/mimuret/golang-iij-dpf/pkg/types" ) var _ = Describe("contracts", func() { var ( c zones.Contract cl *testtool.TestClient err error reqId string s1 zones.Contract ) BeforeEach(func() { cl = testtool.NewTestClient("", "http://localhost", nil) s1 = zones.Contract{ AttributeMeta: zones.AttributeMeta{ ZoneID: "m1", }, Contract: core.Contract{ ID: "f1", ServiceCode: "dpf0000001", State: types.StateBeforeStart, Favorite: types.FavoriteHighPriority, Plan: core.PlanBasic, Description: "contract 1", }, } }) Describe("Contract", func() { Context("Read", func() { BeforeEach(func() { httpmock.RegisterResponder(http.MethodGet, "http://localhost/zones/m1/contract", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "A4FBAF142456476BBBA919737A4C7663", "result": { "id": "f1", "service_code": "dpf0000001", "state": 1, "favorite": 1, "plan": 1, "description": "contract 1" } }`))) }) AfterEach(func() { httpmock.Reset() }) When("returns CommonConfig id1", func() { BeforeEach(func() { c = zones.Contract{ AttributeMeta: zones.AttributeMeta{ ZoneID: "m1", }, } reqId, err = cl.Read(context.Background(), &c) }) It("returns normal", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal("A4FBAF142456476BBBA919737A4C7663")) Expect(c).To(Equal(s1)) }) }) }) Context("SetPathParams", func() { When("no arguments, nothing to do", func() { BeforeEach(func() { err = s1.SetPathParams() }) It("returns error", func() { Expect(err).To(Succeed()) }) }) When("enough arguments", func() { BeforeEach(func() { err = s1.SetPathParams("m10") }) It("not returns error", func() { Expect(err).To(Succeed()) }) It("can set ContractID", func() { Expect(s1.GetZoneID()).To(Equal("m10")) }) }) When("arguments has extra value", func() { BeforeEach(func() { err = s1.SetPathParams("m10", 2) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) When("arguments type missmatch (ZoneID)", func() { BeforeEach(func() { err = s1.SetPathParams(2) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) }) Context("api.Spec common test", func() { var nilSpec *zones.Contract testtool.TestDeepCopyObject(&s1, nilSpec) testtool.TestGetName(&s1, "contract") Context("GetPathMethod", func() { When("action is ActionRead", func() { testtool.TestGetPathMethod(&s1, api.ActionRead, http.MethodGet, "/zones/m1/contract") }) When("action is other", func() { testtool.TestGetPathMethod(&s1, api.ActionApply, "", "") }) }) }) }) }) golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/zones/default_ttl.go000066400000000000000000000050121437707610400231270ustar00rootroot00000000000000package zones import ( "fmt" "github.com/mimuret/golang-iij-dpf/pkg/api" "github.com/mimuret/golang-iij-dpf/pkg/apis" ) type DefaultTTLState int const ( DefaultTTLStateApplied DefaultTTLState = 0 DefaultTTLStateToBeUpdate DefaultTTLState = 3 DefaultTTLStateBeforeUpdate DefaultTTLState = 5 ) func (c DefaultTTLState) String() string { defaultTTLStateToString := map[DefaultTTLState]string{ DefaultTTLStateApplied: "Applied", DefaultTTLStateToBeUpdate: "ToBeUpdate", DefaultTTLStateBeforeUpdate: "BeforeUpdate", } return defaultTTLStateToString[c] } var _ Spec = &DefaultTTL{} // +k8s:deepcopy-gen:interfaces=github.com/mimuret/golang-iij-dpf/pkg/api.Object type DefaultTTL struct { AttributeMeta Value int64 `read:"value" update:"value"` State DefaultTTLState `read:"state"` Operator string `read:"operator"` } func (c *DefaultTTL) GetName() string { return "default_ttl" } func (c *DefaultTTL) GetPathMethod(action api.Action) (string, string) { switch action { case api.ActionRead, api.ActionUpdate: return action.ToMethod(), fmt.Sprintf("/zones/%s/default_ttl", c.GetZoneID()) case api.ActionCancel: return action.ToMethod(), fmt.Sprintf("/zones/%s/default_ttl/changes", c.GetZoneID()) } return "", "" } func (c *DefaultTTL) SetPathParams(args ...interface{}) error { return apis.SetPathParams(args, &c.ZoneID) } type DefaultTTLDiff struct { New *DefaultTTL `read:"new"` Old *DefaultTTL `read:"old"` } var _ ListSpec = &DefaultTTLDiffList{} // +k8s:deepcopy-gen:interfaces=github.com/mimuret/golang-iij-dpf/pkg/api.Object type DefaultTTLDiffList struct { AttributeMeta Items []DefaultTTLDiff `read:"items"` } func (c *DefaultTTLDiffList) GetName() string { return "default_ttl/diffs" } func (c *DefaultTTLDiffList) GetItems() interface{} { return &c.Items } func (c *DefaultTTLDiffList) Len() int { return len(c.Items) } func (c *DefaultTTLDiffList) Index(i int) interface{} { return c.Items[i] } func (c *DefaultTTLDiffList) GetPathMethod(action api.Action) (string, string) { return GetPathMethodForListSpec(action, c) } func (c *DefaultTTLDiffList) Init() { for i := range c.Items { if c.Items[i].New != nil { c.Items[i].New.AttributeMeta = c.AttributeMeta } if c.Items[i].Old != nil { c.Items[i].Old.AttributeMeta = c.AttributeMeta } } } func (c *DefaultTTLDiffList) SetPathParams(args ...interface{}) error { return apis.SetPathParams(args, &c.ZoneID) } func init() { register(&DefaultTTL{}) register(&DefaultTTLDiffList{}) } golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/zones/default_ttl_test.go000066400000000000000000000164141437707610400241760ustar00rootroot00000000000000package zones_test import ( "context" "net/http" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/jarcoal/httpmock" "github.com/mimuret/golang-iij-dpf/pkg/api" "github.com/mimuret/golang-iij-dpf/pkg/apis/dpf/v1/zones" "github.com/mimuret/golang-iij-dpf/pkg/testtool" ) var _ = Describe("default_ttl", func() { var ( c zones.DefaultTTL cl *testtool.TestClient err error reqId string s1, s2 zones.DefaultTTL zdiff zones.DefaultTTLDiff slist zones.DefaultTTLDiffList ) BeforeEach(func() { cl = testtool.NewTestClient("", "http://localhost", nil) s1 = zones.DefaultTTL{ AttributeMeta: zones.AttributeMeta{ ZoneID: "m1", }, Value: 3600, State: zones.DefaultTTLStateApplied, Operator: "user1", } s2 = zones.DefaultTTL{ AttributeMeta: zones.AttributeMeta{ ZoneID: "m1", }, Value: 300, State: zones.DefaultTTLStateApplied, Operator: "user2", } zdiff = zones.DefaultTTLDiff{ New: &s1, Old: &s2, } slist = zones.DefaultTTLDiffList{ AttributeMeta: zones.AttributeMeta{ ZoneID: "m1", }, Items: []zones.DefaultTTLDiff{zdiff}, } }) Describe("DefaultTTL", func() { Context("Read", func() { BeforeEach(func() { httpmock.RegisterResponder(http.MethodGet, "http://localhost/zones/m1/default_ttl", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "19AB6F91095C4E4E83659AD75ADFE0E3", "result": { "value": 3600, "state": 0, "operator": "user1" } }`))) }) AfterEach(func() { httpmock.Reset() }) When("returns CommonConfig id1", func() { BeforeEach(func() { c = zones.DefaultTTL{ AttributeMeta: zones.AttributeMeta{ ZoneID: "m1", }, } reqId, err = cl.Read(context.Background(), &c) }) It("returns normal", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal("19AB6F91095C4E4E83659AD75ADFE0E3")) Expect(c).To(Equal(s1)) }) }) }) Context("Update", func() { id1, bs1 := testtool.CreateAsyncResponse() BeforeEach(func() { httpmock.RegisterResponder(http.MethodPatch, "http://localhost/zones/m1/default_ttl", httpmock.NewBytesResponder(202, bs1)) reqId, err = cl.Update(context.Background(), &s1, nil) }) AfterEach(func() { httpmock.Reset() }) It("returns job_id", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal(id1)) }) It("post json", func() { Expect(cl.RequestBody["/zones/m1/default_ttl"]).To(MatchJSON(`{ "value": 3600 }`)) }) }) Context("Cancel", func() { id1, bs1 := testtool.CreateAsyncResponse() BeforeEach(func() { httpmock.RegisterResponder(http.MethodDelete, "http://localhost/zones/m1/default_ttl/changes", httpmock.NewBytesResponder(202, bs1)) reqId, err = cl.Cancel(context.Background(), &s1) }) AfterEach(func() { httpmock.Reset() }) It("returns job_id", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal(id1)) }) It("body is empty", func() { Expect(cl.RequestBody["/zones/m1/default_ttl"]).To(Equal("")) }) }) Context("SetPathParams", func() { When("no arguments, nothing to do", func() { BeforeEach(func() { err = s1.SetPathParams() }) It("returns error", func() { Expect(err).To(Succeed()) }) }) When("enough arguments", func() { BeforeEach(func() { err = s1.SetPathParams("m10") }) It("not returns error", func() { Expect(err).To(Succeed()) }) It("can set ContractID", func() { Expect(s1.GetZoneID()).To(Equal("m10")) }) }) When("arguments has extra value", func() { BeforeEach(func() { err = s1.SetPathParams("m10", 2) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) When("arguments type missmatch (ZoneID)", func() { BeforeEach(func() { err = s1.SetPathParams(2) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) }) Context("api.Spec common test", func() { var nilSpec *zones.DefaultTTL testtool.TestDeepCopyObject(&s1, nilSpec) testtool.TestGetName(&s1, "default_ttl") Context("GetPathMethod", func() { When("action is ActionRead", func() { testtool.TestGetPathMethod(&s1, api.ActionRead, http.MethodGet, "/zones/m1/default_ttl") }) When("action is ActionUpdate", func() { testtool.TestGetPathMethod(&s1, api.ActionUpdate, http.MethodPatch, "/zones/m1/default_ttl") }) When("action is ActionCancel", func() { testtool.TestGetPathMethod(&s1, api.ActionCancel, http.MethodDelete, "/zones/m1/default_ttl/changes") }) When("action is other", func() { testtool.TestGetPathMethod(&s1, api.ActionApply, "", "") }) }) }) }) Describe("DefaultTTLDiffList", func() { var c zones.DefaultTTLDiffList Context("Read", func() { BeforeEach(func() { httpmock.RegisterResponder(http.MethodGet, "http://localhost/zones/m1/default_ttl/diffs", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "6FB71A568C66435BB1B7DCBC6911D881", "results": [ { "new": { "value": 3600, "state": 0, "operator": "user1" }, "old": { "value": 300, "state": 0, "operator": "user2" } }] }`))) }) AfterEach(func() { httpmock.Reset() }) When("returns diff", func() { BeforeEach(func() { c = zones.DefaultTTLDiffList{ AttributeMeta: zones.AttributeMeta{ ZoneID: "m1", }, } reqId, err = cl.List(context.Background(), &c, nil) }) It("returns normal", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal("6FB71A568C66435BB1B7DCBC6911D881")) Expect(c).To(Equal(slist)) }) }) }) Context("SetPathParams", func() { BeforeEach(func() { err = slist.SetPathParams() }) It("nothing todo", func() { Expect(err).To(Succeed()) }) }) Context("api.Spec common test", func() { var nilSpec *zones.DefaultTTLDiffList testtool.TestDeepCopyObject(&slist, nilSpec) testtool.TestGetName(&slist, "default_ttl/diffs") testtool.TestGetPathMethodForList(&slist, "/zones/m1/default_ttl/diffs") }) Context("api.ListSpec common test", func() { testtool.TestGetItems(&slist, &slist.Items) testtool.TestLen(&slist, 1) Context("Index", func() { When("index exist", func() { It("returns item", func() { Expect(slist.Index(0)).To(Equal(zdiff)) }) }) }) }) }) Context("DefaultTTLState", func() { Context("String", func() { Expect(zones.DefaultTTLStateApplied.String()).To(Equal("Applied")) Expect(zones.DefaultTTLStateToBeUpdate.String()).To(Equal("ToBeUpdate")) Expect(zones.DefaultTTLStateBeforeUpdate.String()).To(Equal("BeforeUpdate")) }) }) Context("DefaultTTLDiff", func() { var s, copy, nilSpec *zones.DefaultTTLDiff BeforeEach(func() { s = &zones.DefaultTTLDiff{} }) Context("DeepCopy", func() { When("object is not nil", func() { BeforeEach(func() { copy = s.DeepCopy() }) It("returns copy", func() { Expect(copy).NotTo(BeNil()) Expect(copy).To(Equal(s)) }) }) When("object is not nil", func() { BeforeEach(func() { copy = nilSpec.DeepCopy() }) It("returns nil", func() { Expect(copy).To(BeNil()) }) }) }) }) }) golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/zones/dnssec.go000066400000000000000000000045311437707610400221040ustar00rootroot00000000000000package zones import ( "fmt" "github.com/mimuret/golang-iij-dpf/pkg/api" "github.com/mimuret/golang-iij-dpf/pkg/apis" "github.com/mimuret/golang-iij-dpf/pkg/types" ) type DnssecState int const ( DnssecStateZoneClosed DnssecState = 0 DnssecStateEnabling DnssecState = 1 DnssecStateEnable DnssecState = 2 DnssecStateDisabling DnssecState = 3 DnssecStateDisable DnssecState = 4 ) func (c DnssecState) String() string { dnssecStateToString := map[DnssecState]string{ DnssecStateZoneClosed: "ZoneClosed", DnssecStateEnabling: "Enabling", DnssecStateEnable: "Enable", DnssecStateDisabling: "Disabling", DnssecStateDisable: "Disable", } return dnssecStateToString[c] } type DSState int const ( DSStateClose DSState = 0 DSStateBeforeRegistration DSState = 1 DSStateWaitClearCacheForRegistration DSState = 2 DSStateDisclose DSState = 3 DSStateBeforeChange DSState = 4 DSStateWaitClearCacheForChanged DSState = 5 DSStateBeforeDelete DSState = 6 DSStateWaitClearCacheForDelete DSState = 7 ) func (c DSState) String() string { dsStateToSString := map[DSState]string{ DSStateClose: "Close", DSStateBeforeRegistration: "BeforeRegistration", DSStateWaitClearCacheForRegistration: "WaitRegistration", DSStateDisclose: "Disclose", DSStateBeforeChange: "BeforeChange", DSStateWaitClearCacheForChanged: "WaitChange", DSStateBeforeDelete: "BeforeDelete", DSStateWaitClearCacheForDelete: "WaitDelete", } return dsStateToSString[c] } var _ Spec = &Dnssec{} // +k8s:deepcopy-gen:interfaces=github.com/mimuret/golang-iij-dpf/pkg/api.Object type Dnssec struct { AttributeMeta Enabled types.Boolean `read:"enabled" update:"enabled"` State DnssecState `read:"state"` DsState DSState `read:"ds_state"` } func (c *Dnssec) GetName() string { return "dnssec" } func (c *Dnssec) GetPathMethod(action api.Action) (string, string) { switch action { case api.ActionRead, api.ActionUpdate: return action.ToMethod(), fmt.Sprintf("/zones/%s/dnssec", c.GetZoneID()) } return "", "" } func (c *Dnssec) SetPathParams(args ...interface{}) error { return apis.SetPathParams(args, &c.ZoneID) } func init() { register(&Dnssec{}) } golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/zones/dnssec_key_rollover.go000066400000000000000000000014011437707610400246710ustar00rootroot00000000000000package zones import ( "fmt" "net/http" "github.com/mimuret/golang-iij-dpf/pkg/api" "github.com/mimuret/golang-iij-dpf/pkg/apis" ) var _ Spec = &DnssecKskRollover{} // +k8s:deepcopy-gen:interfaces=github.com/mimuret/golang-iij-dpf/pkg/api.Object type DnssecKskRollover struct { AttributeMeta } func (c *DnssecKskRollover) GetName() string { return "dnssec/ksk_rollover" } func (c *DnssecKskRollover) GetPathMethod(action api.Action) (string, string) { if action == api.ActionApply { return http.MethodPatch, fmt.Sprintf("/zones/%s/dnssec/ksk_rollover", c.GetZoneID()) } return "", "" } func (c *DnssecKskRollover) SetPathParams(args ...interface{}) error { return apis.SetPathParams(args, &c.ZoneID) } func init() { register(&DnssecKskRollover{}) } golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/zones/dnssec_key_rollover_test.go000066400000000000000000000051071437707610400257370ustar00rootroot00000000000000package zones_test import ( "context" "net/http" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/jarcoal/httpmock" "github.com/mimuret/golang-iij-dpf/pkg/api" "github.com/mimuret/golang-iij-dpf/pkg/apis/dpf/v1/zones" "github.com/mimuret/golang-iij-dpf/pkg/testtool" ) var _ = Describe("dnssec/ksk_rollover", func() { var ( cl *testtool.TestClient err error reqId string s1 zones.DnssecKskRollover ) BeforeEach(func() { cl = testtool.NewTestClient("", "http://localhost", nil) s1 = zones.DnssecKskRollover{ AttributeMeta: zones.AttributeMeta{ ZoneID: "m1", }, } }) Describe("DnssecKskRollover", func() { Context("Apply", func() { id1, bs1 := testtool.CreateAsyncResponse() BeforeEach(func() { httpmock.RegisterResponder(http.MethodPatch, "http://localhost/zones/m1/dnssec/ksk_rollover", httpmock.NewBytesResponder(202, bs1)) reqId, err = cl.Apply(context.Background(), &s1, nil) }) AfterEach(func() { httpmock.Reset() }) It("returns job_id", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal(id1)) }) It("post json", func() { Expect(cl.RequestBody["/zones/m1/dnssec/ksk_rollover"]).To(MatchJSON(`{}`)) }) }) Context("SetPathParams", func() { When("no arguments, nothing to do", func() { BeforeEach(func() { err = s1.SetPathParams() }) It("returns error", func() { Expect(err).To(Succeed()) }) }) When("enough arguments", func() { BeforeEach(func() { err = s1.SetPathParams("m10") }) It("not returns error", func() { Expect(err).To(Succeed()) }) It("can set ContractID", func() { Expect(s1.GetZoneID()).To(Equal("m10")) }) }) When("arguments has extra value", func() { BeforeEach(func() { err = s1.SetPathParams("m10", 2) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) When("arguments type missmatch (ZoneID)", func() { BeforeEach(func() { err = s1.SetPathParams(2) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) }) Context("api.Spec common test", func() { var nilSpec *zones.DnssecKskRollover testtool.TestDeepCopyObject(&s1, nilSpec) testtool.TestGetName(&s1, "dnssec/ksk_rollover") Context("GetPathMethod", func() { When("action is ActionApply", func() { testtool.TestGetPathMethod(&s1, api.ActionApply, http.MethodPatch, "/zones/m1/dnssec/ksk_rollover") }) When("action is other", func() { testtool.TestGetPathMethod(&s1, api.ActionUpdate, "", "") }) }) }) }) }) golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/zones/dnssec_test.go000066400000000000000000000111521437707610400231400ustar00rootroot00000000000000package zones_test import ( "context" "net/http" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/jarcoal/httpmock" "github.com/mimuret/golang-iij-dpf/pkg/api" "github.com/mimuret/golang-iij-dpf/pkg/apis/dpf/v1/zones" "github.com/mimuret/golang-iij-dpf/pkg/testtool" "github.com/mimuret/golang-iij-dpf/pkg/types" ) var _ = Describe("dnssec", func() { var ( c zones.Dnssec cl *testtool.TestClient err error reqId string s1, s2 zones.Dnssec ) BeforeEach(func() { cl = testtool.NewTestClient("", "http://localhost", nil) s1 = zones.Dnssec{ AttributeMeta: zones.AttributeMeta{ ZoneID: "m1", }, Enabled: types.Enabled, State: zones.DnssecStateEnable, DsState: zones.DSStateDisclose, } s2 = zones.Dnssec{ AttributeMeta: zones.AttributeMeta{ ZoneID: "m2", }, Enabled: types.Disabled, State: zones.DnssecStateEnable, DsState: zones.DSStateDisclose, } }) Describe("Dnssec", func() { Context("Read", func() { BeforeEach(func() { httpmock.RegisterResponder(http.MethodGet, "http://localhost/zones/m1/dnssec", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "533F010C0DEC4B71891D1491C5308A10", "result": { "enabled": 1, "state": 2, "ds_state": 3 } }`))) }) AfterEach(func() { httpmock.Reset() }) When("returns m1", func() { BeforeEach(func() { c = zones.Dnssec{ AttributeMeta: zones.AttributeMeta{ ZoneID: "m1", }, } reqId, err = cl.Read(context.Background(), &c) }) It("returns normal", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal("533F010C0DEC4B71891D1491C5308A10")) Expect(c).To(Equal(s1)) }) }) }) Context("Update", func() { var ( id1, bs1 = testtool.CreateAsyncResponse() id2, bs2 = testtool.CreateAsyncResponse() ) BeforeEach(func() { httpmock.RegisterResponder(http.MethodPatch, "http://localhost/zones/m1/dnssec", httpmock.NewBytesResponder(202, bs1)) httpmock.RegisterResponder(http.MethodPatch, "http://localhost/zones/m2/dnssec", httpmock.NewBytesResponder(202, bs2)) }) AfterEach(func() { httpmock.Reset() }) When("enable", func() { BeforeEach(func() { reqId, err = cl.Update(context.Background(), &s1, nil) }) It("returns job_id", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal(id1)) }) It("post json", func() { Expect(cl.RequestBody["/zones/m1/dnssec"]).To(MatchJSON(`{ "enabled": 1 }`)) }) }) When("disable", func() { BeforeEach(func() { reqId, err = cl.Update(context.Background(), &s2, nil) }) It("returns job_id", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal(id2)) }) It("post json", func() { Expect(cl.RequestBody["/zones/m2/dnssec"]).To(MatchJSON(`{ "enabled": 0 }`)) }) }) }) Context("SetPathParams", func() { When("no arguments, nothing to do", func() { BeforeEach(func() { err = s1.SetPathParams() }) It("returns error", func() { Expect(err).To(Succeed()) }) }) When("enough arguments", func() { BeforeEach(func() { err = s1.SetPathParams("m10") }) It("not returns error", func() { Expect(err).To(Succeed()) }) It("can set ContractID", func() { Expect(s1.GetZoneID()).To(Equal("m10")) }) }) When("arguments has extra value", func() { BeforeEach(func() { err = s1.SetPathParams("m10", 2) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) When("arguments type missmatch (ZoneID)", func() { BeforeEach(func() { err = s1.SetPathParams(2) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) }) Context("api.Spec common test", func() { var nilSpec *zones.Dnssec testtool.TestDeepCopyObject(&s1, nilSpec) testtool.TestGetName(&s1, "dnssec") Context("GetPathMethod", func() { When("action is ActionRead", func() { testtool.TestGetPathMethod(&s1, api.ActionRead, http.MethodGet, "/zones/m1/dnssec") }) When("action is ActionUpdate", func() { testtool.TestGetPathMethod(&s1, api.ActionUpdate, http.MethodPatch, "/zones/m1/dnssec") }) When("action is other", func() { testtool.TestGetPathMethod(&s1, api.ActionApply, "", "") }) }) }) }) Context("DnssecStateToString", func() { Context("String", func() { Expect(zones.DnssecStateEnable.String()).To(Equal("Enable")) }) }) Context("DSStateToSString", func() { Context("String", func() { Expect(zones.DSStateClose.String()).To(Equal("Close")) }) }) }) golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/zones/doc.go000066400000000000000000000000541437707610400213660ustar00rootroot00000000000000package zones // +k8s:deepcopy-gen=package golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/zones/ds_record.go000066400000000000000000000020451437707610400225670ustar00rootroot00000000000000package zones import ( "github.com/mimuret/golang-iij-dpf/pkg/api" "github.com/mimuret/golang-iij-dpf/pkg/apis" "github.com/mimuret/golang-iij-dpf/pkg/types" ) var _ ListSpec = &DsRecordList{} type DsRecord struct { RRSet string `read:"rrset"` TransitAt types.Time `read:"transited_at"` } // +k8s:deepcopy-gen:interfaces=github.com/mimuret/golang-iij-dpf/pkg/api.Object type DsRecordList struct { AttributeMeta Items []DsRecord `read:"items"` } func (c *DsRecordList) GetName() string { return "ds_records" } func (c *DsRecordList) GetItems() interface{} { return &c.Items } func (c *DsRecordList) Len() int { return len(c.Items) } func (c *DsRecordList) Index(i int) interface{} { return c.Items[i] } func (c *DsRecordList) GetPathMethod(action api.Action) (string, string) { return GetPathMethodForListSpec(action, c) } func (c *DsRecordList) SetPathParams(args ...interface{}) error { return apis.SetPathParams(args, &c.ZoneID) } func (c *DsRecordList) Init() {} func init() { register(&DsRecordList{}) } golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/zones/ds_record_test.go000066400000000000000000000101351437707610400236250ustar00rootroot00000000000000package zones_test import ( "context" "net/http" "time" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/jarcoal/httpmock" "github.com/mimuret/golang-iij-dpf/pkg/apis/dpf/v1/zones" "github.com/mimuret/golang-iij-dpf/pkg/testtool" "github.com/mimuret/golang-iij-dpf/pkg/types" ) var _ = Describe("ds_records", func() { var ( c zones.DsRecordList cl *testtool.TestClient err error reqId string s1, s2 zones.DsRecord slist zones.DsRecordList ) BeforeEach(func() { atTime, err := types.ParseTime(time.RFC3339Nano, "2021-06-20T10:23:51.071Z") Expect(err).To(Succeed()) cl = testtool.NewTestClient("", "http://localhost", nil) s1 = zones.DsRecord{ RRSet: "46369 8 2 39F054DCB3EC1E93D8AE6D8F1AAAD91794055EA36895045FAF6F65F0 2FEBC579", TransitAt: atTime, } s2 = zones.DsRecord{ RRSet: "57367 8 2 C069902A17BC8E19F1D5809272219B694C09EC5BCF4AAD4911FC765B 1C233A69", TransitAt: atTime, } slist = zones.DsRecordList{ AttributeMeta: zones.AttributeMeta{ ZoneID: "m1", }, Items: []zones.DsRecord{s1, s2}, } }) Describe("DsRecordList", func() { Context("List", func() { BeforeEach(func() { httpmock.RegisterResponder(http.MethodGet, "http://localhost/zones/m1/ds_records", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "CD445FC65BBA4977B78B347A87633947", "results": [ { "rrset": "46369 8 2 39F054DCB3EC1E93D8AE6D8F1AAAD91794055EA36895045FAF6F65F0 2FEBC579", "transited_at": "2021-06-20T10:23:51.071Z" }, { "rrset": "57367 8 2 C069902A17BC8E19F1D5809272219B694C09EC5BCF4AAD4911FC765B 1C233A69", "transited_at": "2021-06-20T10:23:51.071Z" } ] }`))) }) AfterEach(func() { httpmock.Reset() }) When("returns m1", func() { BeforeEach(func() { c = zones.DsRecordList{ AttributeMeta: zones.AttributeMeta{ ZoneID: "m1", }, } reqId, err = cl.List(context.Background(), &c, nil) }) It("returns normal", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal("CD445FC65BBA4977B78B347A87633947")) Expect(c).To(Equal(slist)) }) }) }) Context("SetPathParams", func() { When("no arguments, nothing to do", func() { BeforeEach(func() { err = slist.SetPathParams() }) It("returns error", func() { Expect(err).To(Succeed()) }) }) When("enough arguments", func() { BeforeEach(func() { err = slist.SetPathParams("m10") }) It("not returns error", func() { Expect(err).To(Succeed()) }) It("can set ContractID", func() { Expect(slist.GetZoneID()).To(Equal("m10")) }) }) When("arguments has extra value", func() { BeforeEach(func() { err = slist.SetPathParams("m10", 2) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) When("arguments type missmatch (ZoneID)", func() { BeforeEach(func() { err = slist.SetPathParams(2) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) }) Context("api.Spec common test", func() { var nilSpec *zones.DsRecordList testtool.TestDeepCopyObject(&slist, nilSpec) testtool.TestGetName(&slist, "ds_records") testtool.TestGetPathMethodForList(&slist, "/zones/m1/ds_records") }) Context("api.ListSpec common test", func() { testtool.TestGetItems(&slist, &slist.Items) testtool.TestLen(&slist, 2) Context("Index", func() { When("index exist", func() { It("returns item", func() { Expect(slist.Index(0)).To(Equal(s1)) }) }) }) }) }) Describe("DsRecord", func() { var s, copy, nilSpec *zones.DsRecord BeforeEach(func() { s = &zones.DsRecord{} }) Context("DeepCopy", func() { When("object is not nil", func() { BeforeEach(func() { copy = s.DeepCopy() }) It("returns copy", func() { Expect(copy).NotTo(BeNil()) Expect(copy).To(Equal(s)) }) }) When("object is not nil", func() { BeforeEach(func() { copy = nilSpec.DeepCopy() }) It("returns nil", func() { Expect(copy).To(BeNil()) }) }) }) }) }) golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/zones/ginkgo_test.go000066400000000000000000000006201437707610400231350ustar00rootroot00000000000000package zones_test import ( "testing" "github.com/jarcoal/httpmock" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) func TestGinkgo(t *testing.T) { RegisterFailHandler(Fail) RunSpecs(t, "zones package test suite") } var _ = BeforeSuite(func() { httpmock.Activate() }) var _ = BeforeEach(func() { httpmock.Reset() }) var _ = AfterSuite(func() { httpmock.DeactivateAndReset() }) golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/zones/history.go000066400000000000000000000036501437707610400223270ustar00rootroot00000000000000package zones import ( "net/url" "github.com/google/go-querystring/query" "github.com/mimuret/golang-iij-dpf/pkg/api" "github.com/mimuret/golang-iij-dpf/pkg/apis" "github.com/mimuret/golang-iij-dpf/pkg/types" ) type History struct { ID int64 `read:"id"` CommittedAt types.Time `read:"committed_at"` Description string `read:"description"` Operator string `read:"operator"` } var _ CountableListSpec = &HistoryList{} // +k8s:deepcopy-gen:interfaces=github.com/mimuret/golang-iij-dpf/pkg/api.Object type HistoryList struct { AttributeMeta api.Count Items []History `read:"items"` } func (c *HistoryList) GetName() string { return "zone_histories" } func (c *HistoryList) GetItems() interface{} { return &c.Items } func (c *HistoryList) Len() int { return len(c.Items) } func (c *HistoryList) Index(i int) interface{} { return c.Items[i] } func (c *HistoryList) GetMaxLimit() int32 { return 100 } func (c *HistoryList) ClearItems() { c.Items = []History{} } func (c *HistoryList) AddItem(v interface{}) bool { if a, ok := v.(History); ok { c.Items = append(c.Items, a) return true } return false } func (c *HistoryList) GetPathMethod(action api.Action) (string, string) { return GetPathMethodForListSpec(action, c) } func (c *HistoryList) SetPathParams(args ...interface{}) error { return apis.SetPathParams(args, &c.ZoneID) } func (c *HistoryList) Init() {} var _ api.SearchParams = &HistoryListSearchKeywords{} // +k8s:deepcopy-gen=false type HistoryListSearchKeywords struct { api.CommonSearchParams FullText api.KeywordsString `url:"_keywords_full_text[],omitempty"` Description api.KeywordsString `url:"_keywords_description[],omitempty"` Operator api.KeywordsString `url:"_keywords_operator[],omitempty"` } func (s *HistoryListSearchKeywords) GetValues() (url.Values, error) { return query.Values(s) } func init() { register(&HistoryList{}) } golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/zones/history_test.go000066400000000000000000000137171437707610400233730ustar00rootroot00000000000000package zones_test import ( "context" "net/http" "net/url" "time" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/jarcoal/httpmock" api "github.com/mimuret/golang-iij-dpf/pkg/api" "github.com/mimuret/golang-iij-dpf/pkg/apis/dpf/v1/zones" "github.com/mimuret/golang-iij-dpf/pkg/testtool" "github.com/mimuret/golang-iij-dpf/pkg/types" ) var _ = Describe("history text", func() { var ( c zones.HistoryList cl *testtool.TestClient err error reqId string s1, s2 zones.History slist zones.HistoryList ) BeforeEach(func() { atTime, err := types.ParseTime(time.RFC3339Nano, "2021-06-20T10:50:37.396Z") Expect(err).To(Succeed()) cl = testtool.NewTestClient("", "http://localhost", nil) s1 = zones.History{ ID: 1, CommittedAt: atTime, Description: "commit 1", Operator: "user1", } s2 = zones.History{ ID: 2, CommittedAt: atTime, Description: "commit 2", Operator: "user2", } slist = zones.HistoryList{ AttributeMeta: zones.AttributeMeta{ ZoneID: "m1", }, Items: []zones.History{s1, s2}, } }) Describe("HistoryList", func() { Context("List", func() { BeforeEach(func() { httpmock.RegisterResponder(http.MethodGet, "http://localhost/zones/m1/zone_histories", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "71B4D2B268744DBB8C3220C3A38C29E5", "results": [ { "id": 1, "committed_at": "2021-06-20T10:50:37.396Z", "description": "commit 1", "operator": "user1" }, { "id": 2, "committed_at": "2021-06-20T10:50:37.396Z", "description": "commit 2", "operator": "user2" } ] }`))) httpmock.RegisterResponder(http.MethodGet, "http://localhost/zones/m1/zone_histories/count", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "8BAB2071CF2C4509A93E485D7F368A71", "result": { "count": 2 } }`))) }) AfterEach(func() { httpmock.Reset() }) When("returns m1", func() { BeforeEach(func() { c = zones.HistoryList{ AttributeMeta: zones.AttributeMeta{ ZoneID: "m1", }, } reqId, err = cl.List(context.Background(), &c, nil) }) It("returns normal", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal("71B4D2B268744DBB8C3220C3A38C29E5")) Expect(c).To(Equal(slist)) }) }) }) Context("SetPathParams", func() { When("no arguments, nothing to do", func() { BeforeEach(func() { err = slist.SetPathParams() }) It("returns error", func() { Expect(err).To(Succeed()) }) }) When("enough arguments", func() { BeforeEach(func() { err = slist.SetPathParams("m10") }) It("not returns error", func() { Expect(err).To(Succeed()) }) It("can set ContractID", func() { Expect(slist.GetZoneID()).To(Equal("m10")) }) }) When("arguments has extra value", func() { BeforeEach(func() { err = slist.SetPathParams("m10", 2) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) When("arguments type missmatch (ZoneID)", func() { BeforeEach(func() { err = slist.SetPathParams(2) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) }) Context("api.Spec common test", func() { var nilSpec *zones.HistoryList testtool.TestDeepCopyObject(&slist, nilSpec) testtool.TestGetName(&slist, "zone_histories") testtool.TestGetPathMethodForCountableList(&slist, "/zones/m1/zone_histories") }) Context("api.ListSpec common test", func() { testtool.TestGetItems(&slist, &slist.Items) testtool.TestLen(&slist, 2) Context("Index", func() { When("index exist", func() { It("returns item", func() { Expect(slist.Index(0)).To(Equal(s1)) }) }) }) }) Context("api.CountableListSpec common test", func() { testtool.TestGetMaxLimit(&slist, 100) testtool.TestClearItems(&slist) testtool.TestAddItem(&slist, s1) }) }) Context("HistoryListSearchKeywords", func() { testcase := []struct { keyword zones.HistoryListSearchKeywords values url.Values }{ { zones.HistoryListSearchKeywords{ CommonSearchParams: api.CommonSearchParams{ Type: api.SearchTypeAND, Offset: int32(10), Limit: int32(100), }, }, url.Values{ "type": []string{"AND"}, "offset": []string{"10"}, "limit": []string{"100"}, }, }, { zones.HistoryListSearchKeywords{ CommonSearchParams: api.CommonSearchParams{ Type: api.SearchTypeOR, Offset: int32(10), Limit: int32(100), }, FullText: api.KeywordsString{"hogehoge", "ðŸ°"}, Description: api.KeywordsString{"ðŸ‡", "ðŸº"}, Operator: api.KeywordsString{"rabbit@example.jp", "SA0000000"}, }, /* _keywords_full_text[] _keywords_description[] _keywords_operator[] */ url.Values{ "type": []string{"OR"}, "offset": []string{"10"}, "limit": []string{"100"}, "_keywords_full_text[]": []string{"hogehoge", "ðŸ°"}, "_keywords_description[]": []string{"ðŸ‡", "ðŸº"}, "_keywords_operator[]": []string{"rabbit@example.jp", "SA0000000"}, }, }, } It("can convert url.Value", func() { for _, tc := range testcase { s, err := tc.keyword.GetValues() Expect(err).To(Succeed()) Expect(s).To(Equal(tc.values)) } }) }) Describe("History", func() { var s, copy, nilSpec *zones.History BeforeEach(func() { s = &zones.History{} }) Context("DeepCopy", func() { When("object is not nil", func() { BeforeEach(func() { copy = s.DeepCopy() }) It("returns copy", func() { Expect(copy).NotTo(BeNil()) Expect(copy).To(Equal(s)) }) }) When("object is not nil", func() { BeforeEach(func() { copy = nilSpec.DeepCopy() }) It("returns nil", func() { Expect(copy).To(BeNil()) }) }) }) }) }) golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/zones/history_text.go000066400000000000000000000014331437707610400233700ustar00rootroot00000000000000package zones import ( "fmt" "github.com/mimuret/golang-iij-dpf/pkg/api" "github.com/mimuret/golang-iij-dpf/pkg/apis" ) var _ Spec = &HistoryText{} // +k8s:deepcopy-gen:interfaces=github.com/mimuret/golang-iij-dpf/pkg/api.Object type HistoryText struct { AttributeMeta History Text string `read:"text"` } func (c *HistoryText) GetName() string { return fmt.Sprintf("zone_histories/%d/text", c.ID) } func (c *HistoryText) GetPathMethod(action api.Action) (string, string) { if action == api.ActionRead { return action.ToMethod(), fmt.Sprintf("/zones/%s/zone_histories/%d/text", c.GetZoneID(), c.ID) } return "", "" } func (c *HistoryText) SetPathParams(args ...interface{}) error { return apis.SetPathParams(args, &c.ZoneID, &c.ID) } func init() { register(&HistoryText{}) } golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/zones/history_text_test.go000066400000000000000000000114371437707610400244340ustar00rootroot00000000000000package zones_test import ( "context" "net/http" "time" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/jarcoal/httpmock" api "github.com/mimuret/golang-iij-dpf/pkg/api" "github.com/mimuret/golang-iij-dpf/pkg/apis/dpf/v1/zones" "github.com/mimuret/golang-iij-dpf/pkg/testtool" "github.com/mimuret/golang-iij-dpf/pkg/types" ) var _ = Describe("history", func() { var ( c zones.HistoryText cl *testtool.TestClient err error reqId string s1, s2 zones.HistoryText ) BeforeEach(func() { atTime, err := types.ParseTime(time.RFC3339Nano, "2021-06-20T10:50:37.396Z") Expect(err).To(Succeed()) cl = testtool.NewTestClient("", "http://localhost", nil) s1 = zones.HistoryText{ AttributeMeta: zones.AttributeMeta{ ZoneID: "m1", }, History: zones.History{ ID: 1, CommittedAt: atTime, Description: "commit 1", Operator: "user1", }, Text: "zone data 1", } s2 = zones.HistoryText{ AttributeMeta: zones.AttributeMeta{ ZoneID: "m1", }, History: zones.History{ ID: 2, CommittedAt: atTime, Description: "commit 2", Operator: "user2", }, Text: "zone data 2", } }) Describe("DsRecordList", func() { Context("Read", func() { BeforeEach(func() { httpmock.RegisterResponder(http.MethodGet, "http://localhost/zones/m1/zone_histories/1/text", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "CC2BBC44169940CE96D7E8A99FA98958", "result": { "id": 1, "committed_at": "2021-06-20T10:50:37.396Z", "description": "commit 1", "operator": "user1", "text": "zone data 1" } }`))) httpmock.RegisterResponder(http.MethodGet, "http://localhost/zones/m1/zone_histories/2/text", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "CFBD5CBBE7C147C9BD2549551F018D11", "result": { "id": 2, "committed_at": "2021-06-20T10:50:37.396Z", "description": "commit 2", "operator": "user2", "text": "zone data 2" } }`))) }) AfterEach(func() { httpmock.Reset() }) When("returns id1", func() { BeforeEach(func() { c = zones.HistoryText{ AttributeMeta: zones.AttributeMeta{ ZoneID: "m1", }, History: zones.History{ ID: 1, }, } reqId, err = cl.Read(context.Background(), &c) }) It("returns normal", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal("CC2BBC44169940CE96D7E8A99FA98958")) Expect(c).To(Equal(s1)) }) }) When("returns id2", func() { BeforeEach(func() { c = zones.HistoryText{ AttributeMeta: zones.AttributeMeta{ ZoneID: "m1", }, History: zones.History{ ID: 2, }, } reqId, err = cl.Read(context.Background(), &c) }) It("returns normal", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal("CFBD5CBBE7C147C9BD2549551F018D11")) Expect(c).To(Equal(s2)) }) }) }) Context("SetPathParams", func() { When("no arguments, nothing to do", func() { BeforeEach(func() { err = s1.SetPathParams() }) It("returns error", func() { Expect(err).To(Succeed()) }) }) When("enough arguments", func() { BeforeEach(func() { err = s1.SetPathParams("m10", 10) }) It("not returns error", func() { Expect(err).To(Succeed()) }) It("can set ContractID", func() { Expect(s1.GetZoneID()).To(Equal("m10")) }) It("can set HistoryId", func() { Expect(s1.ID).To(Equal(int64(10))) }) }) When("not enough arguments", func() { BeforeEach(func() { err = s1.SetPathParams("m10") }) It("not returns error", func() { Expect(err).To(HaveOccurred()) }) }) When("arguments has extra value", func() { BeforeEach(func() { err = s1.SetPathParams("m10", 2, 1) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) When("arguments type missmatch (ZoneID)", func() { BeforeEach(func() { err = s1.SetPathParams(2) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) When("arguments type missmatch (HistoryId)", func() { BeforeEach(func() { err = s1.SetPathParams("m1", "h1") }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) }) Context("api.Spec common test", func() { var nilSpec *zones.HistoryText testtool.TestDeepCopyObject(&s1, nilSpec) testtool.TestGetName(&s1, "zone_histories/1/text") Context("GetPathMethod", func() { When("action is ActionRead", func() { testtool.TestGetPathMethod(&s1, api.ActionRead, http.MethodGet, "/zones/m1/zone_histories/1/text") }) When("action is other", func() { testtool.TestGetPathMethod(&s1, api.ActionApply, "", "") }) }) }) }) }) golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/zones/log.go000066400000000000000000000022571437707610400214110ustar00rootroot00000000000000package zones import ( "github.com/mimuret/golang-iij-dpf/pkg/api" "github.com/mimuret/golang-iij-dpf/pkg/apis" "github.com/mimuret/golang-iij-dpf/pkg/apis/dpf/v1/core" ) var _ CountableListSpec = &LogList{} // +k8s:deepcopy-gen:interfaces=github.com/mimuret/golang-iij-dpf/pkg/api.Object type LogList struct { AttributeMeta api.Count Items []core.Log `read:"items"` } func (c *LogList) GetName() string { return "logs" } func (c *LogList) GetItems() interface{} { return &c.Items } func (c *LogList) Len() int { return len(c.Items) } func (c *LogList) Index(i int) interface{} { return c.Items[i] } func (c *LogList) GetMaxLimit() int32 { return 100 } func (c *LogList) ClearItems() { c.Items = []core.Log{} } func (c *LogList) AddItem(v interface{}) bool { if a, ok := v.(core.Log); ok { c.Items = append(c.Items, a) return true } return false } func (c *LogList) GetPathMethod(action api.Action) (string, string) { return GetPathMethodForListSpec(action, c) } func (c *LogList) Init() {} func (c *LogList) SetPathParams(args ...interface{}) error { return apis.SetPathParams(args, &c.ZoneID) } func init() { register(&LogList{}) } golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/zones/log_test.go000066400000000000000000000102311437707610400224370ustar00rootroot00000000000000package zones_test import ( "context" "net/http" "time" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/jarcoal/httpmock" core "github.com/mimuret/golang-iij-dpf/pkg/apis/dpf/v1/core" "github.com/mimuret/golang-iij-dpf/pkg/apis/dpf/v1/zones" "github.com/mimuret/golang-iij-dpf/pkg/testtool" "github.com/mimuret/golang-iij-dpf/pkg/types" ) var _ = Describe("logs", func() { var ( cl *testtool.TestClient err error reqId string s1, s2 core.Log atTime types.Time slist zones.LogList ) BeforeEach(func() { atTime, err = types.ParseTime(time.RFC3339Nano, "2021-06-20T07:55:17.753Z") Expect(err).To((Succeed())) cl = testtool.NewTestClient("", "http://localhost", nil) s1 = core.Log{ Time: atTime, LogType: "service", Operator: "user1", Operation: "add_cc_primary", Target: "1", Status: core.LogStatusStart, } s2 = core.Log{ Time: atTime, LogType: "common_config", Operator: "user2", Operation: "create_tsig", Target: "2", Status: core.LogStatusSuccess, } slist = zones.LogList{ AttributeMeta: zones.AttributeMeta{ ZoneID: "m1", }, Items: []core.Log{s1, s2}, } }) Describe("LogList", func() { var c zones.LogList Context("List", func() { BeforeEach(func() { httpmock.RegisterResponder(http.MethodGet, "http://localhost/zones/m1/logs", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "8026628BA5AD4ECA93F8506972DD50A7", "results": [ { "time": "2021-06-20T07:55:17.753Z", "log_type": "service", "operator": "user1", "operation": "add_cc_primary", "target": "1", "status": "start" }, { "time": "2021-06-20T07:55:17.753Z", "log_type": "common_config", "operator": "user2", "operation": "create_tsig", "target": "2", "status": "success" } ] }`))) httpmock.RegisterResponder(http.MethodGet, "http://localhost/zones/m1/logs/count", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "8026628BA5AD4ECA93F8506972DD50A7", "result": { "count": 2 } }`))) }) AfterEach(func() { httpmock.Reset() }) When("returns list ", func() { BeforeEach(func() { c = zones.LogList{ AttributeMeta: zones.AttributeMeta{ ZoneID: "m1", }, } reqId, err = cl.List(context.Background(), &c, nil) }) It("returns normal", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal("8026628BA5AD4ECA93F8506972DD50A7")) Expect(c).To(Equal(slist)) }) }) }) Context("SetPathParams", func() { When("no arguments, nothing to do", func() { BeforeEach(func() { err = slist.SetPathParams() }) It("returns error", func() { Expect(err).To(Succeed()) }) }) When("enough arguments", func() { BeforeEach(func() { err = slist.SetPathParams("id12") }) It("not returns error", func() { Expect(err).To(Succeed()) }) It("can set ZoneID", func() { Expect(slist.GetZoneID()).To(Equal("id12")) }) }) When("arguments has extra value", func() { BeforeEach(func() { err = slist.SetPathParams("m1", 2) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) When("arguments type missmatch (ZoneID)", func() { BeforeEach(func() { err = slist.SetPathParams(2) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) }) Context("api.Spec common test", func() { var nilSpec *zones.LogList testtool.TestDeepCopyObject(&slist, nilSpec) testtool.TestGetName(&slist, "logs") testtool.TestGetPathMethodForCountableList(&slist, "/zones/m1/logs") }) Context("api.ListSpec common test", func() { testtool.TestGetItems(&slist, &slist.Items) testtool.TestLen(&slist, 2) Context("Index", func() { When("index exist", func() { It("returns item", func() { Expect(slist.Index(0)).To(Equal(s1)) }) }) }) }) Context("api.CountableListSpec common test", func() { testtool.TestGetMaxLimit(&slist, 100) testtool.TestClearItems(&slist) testtool.TestAddItem(&slist, s1) }) }) }) golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/zones/managed_dns.go000066400000000000000000000016441437707610400230670ustar00rootroot00000000000000package zones import ( "github.com/mimuret/golang-iij-dpf/pkg/api" "github.com/mimuret/golang-iij-dpf/pkg/apis" ) var _ ListSpec = &ManagedDnsList{} // +k8s:deepcopy-gen:interfaces=github.com/mimuret/golang-iij-dpf/pkg/api.Object type ManagedDnsList struct { AttributeMeta Items []string `read:"items"` } func (c *ManagedDnsList) GetName() string { return "managed_dns_servers" } func (c *ManagedDnsList) GetItems() interface{} { return &c.Items } func (c *ManagedDnsList) Len() int { return len(c.Items) } func (c *ManagedDnsList) Index(i int) interface{} { return c.Items[i] } func (c *ManagedDnsList) GetPathMethod(action api.Action) (string, string) { return GetPathMethodForListSpec(action, c) } func (c *ManagedDnsList) Init() {} func (c *ManagedDnsList) SetPathParams(args ...interface{}) error { return apis.SetPathParams(args, &c.ZoneID) } func init() { register(&ManagedDnsList{}) } golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/zones/managed_dns_test.go000066400000000000000000000057721437707610400241340ustar00rootroot00000000000000package zones_test import ( "context" "net/http" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/jarcoal/httpmock" "github.com/mimuret/golang-iij-dpf/pkg/apis/dpf/v1/zones" "github.com/mimuret/golang-iij-dpf/pkg/testtool" ) var _ = Describe("managed_dns_servers", func() { var ( c zones.ManagedDnsList cl *testtool.TestClient err error reqId string slist zones.ManagedDnsList ) BeforeEach(func() { cl = testtool.NewTestClient("", "http://localhost", nil) slist = zones.ManagedDnsList{ AttributeMeta: zones.AttributeMeta{ ZoneID: "m1", }, Items: []string{ "ns1.example.jp.", "ns1.example.net.", "ns1.example.com.", }, } }) Describe("ManagedDnsList", func() { Context("List", func() { BeforeEach(func() { httpmock.RegisterResponder(http.MethodGet, "http://localhost/zones/m1/managed_dns_servers", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "F4F8591B01B84EFBBA0AD17029DB7DA4", "results": [ "ns1.example.jp.", "ns1.example.net.", "ns1.example.com." ] }`))) }) AfterEach(func() { httpmock.Reset() }) When("returns managed_dns servers", func() { BeforeEach(func() { c = zones.ManagedDnsList{ AttributeMeta: zones.AttributeMeta{ ZoneID: "m1", }, } reqId, err = cl.List(context.Background(), &c, nil) }) It("returns normal", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal("F4F8591B01B84EFBBA0AD17029DB7DA4")) Expect(c).To(Equal(slist)) }) }) }) Context("SetPathParams", func() { When("no arguments, nothing to do", func() { BeforeEach(func() { err = slist.SetPathParams() }) It("returns error", func() { Expect(err).To(Succeed()) }) }) When("enough arguments", func() { BeforeEach(func() { err = slist.SetPathParams("m10") }) It("not returns error", func() { Expect(err).To(Succeed()) }) It("can set ZoneID", func() { Expect(slist.GetZoneID()).To(Equal("m10")) }) }) When("arguments has extra value", func() { BeforeEach(func() { err = slist.SetPathParams("m10", 2) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) When("arguments type missmatch (ZoneID)", func() { BeforeEach(func() { err = slist.SetPathParams(2) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) }) Context("api.Spec common test", func() { var nilSpec *zones.ManagedDnsList testtool.TestDeepCopyObject(&slist, nilSpec) testtool.TestGetName(&slist, "managed_dns_servers") testtool.TestGetPathMethodForList(&slist, "/zones/m1/managed_dns_servers") }) Context("api.ListSpec common test", func() { testtool.TestGetItems(&slist, &slist.Items) testtool.TestLen(&slist, 3) Context("Index", func() { When("index exist", func() { It("returns item", func() { Expect(slist.Index(0)).To(Equal("ns1.example.jp.")) }) }) }) }) }) }) golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/zones/record.go000066400000000000000000000130601437707610400221000ustar00rootroot00000000000000package zones import ( "fmt" "strings" "github.com/miekg/dns" "github.com/mimuret/golang-iij-dpf/pkg/api" "github.com/mimuret/golang-iij-dpf/pkg/apis" "github.com/mimuret/golang-iij-dpf/pkg/types" ) type RecordState int const TypeANAMECode uint16 = 65280 const ( RecordStateApplied RecordState = 0 RecordStateToBeAdded RecordState = 1 RecordStateToBeDeleted RecordState = 2 RecordStateToBeUpdate RecordState = 3 RecordStateBeforeUpdate RecordState = 5 ) func (c RecordState) String() string { recordStateToString := map[RecordState]string{ RecordStateApplied: "Applied", RecordStateToBeAdded: "ToBeAdded", RecordStateToBeDeleted: "ToBeDeleted", RecordStateToBeUpdate: "ToBeUpdate", RecordStateBeforeUpdate: "BeforeUpdate", } return recordStateToString[c] } type Type string const ( TypeSOA Type = "SOA" TypeA Type = "A" TypeAAAA Type = "AAAA" TypeCAA Type = "CAA" TypeCNAME Type = "CNAME" TypeDS Type = "DS" TypeNS Type = "NS" TypeMX Type = "MX" TypeNAPTR Type = "NAPTR" TypeSRV Type = "SRV" TypeTXT Type = "TXT" TypeTLSA Type = "TLSA" TypePTR Type = "PTR" TypeSVCB Type = "SVCB" TypeHTTPS Type = "HTTPS" TypeANAME Type = "ANAME" ) func (c Type) String() string { return string(c) } func (c Type) Uint16() uint16 { if c == TypeANAME { return TypeANAMECode } return dns.StringToType[string(c)] } func Uint16ToType(t uint16) Type { if t == TypeANAMECode { return TypeANAME } return Type(dns.TypeToString[t]) } // +k8s:deepcopy-gen=false type KeywordsType []Type type RecordRDATA struct { Value string `read:"value" create:"value" update:"value"` } func (c *RecordRDATA) String() string { return c.Value } type RecordRDATASlice []RecordRDATA func (c RecordRDATASlice) String() string { var res []string for _, value := range c { res = append(res, value.String()) } return strings.Join(res, ",") } var _ Spec = &Record{} // +k8s:deepcopy-gen:interfaces=github.com/mimuret/golang-iij-dpf/pkg/api.Object type Record struct { AttributeMeta ID string `read:"id"` Name string `read:"name" create:"name"` TTL types.NullablePositiveInt32 `read:"ttl" create:"ttl" update:"ttl"` RRType Type `read:"rrtype" create:"rrtype"` RData RecordRDATASlice `read:"rdata" create:"rdata" update:"rdata"` State RecordState `read:"state"` Description string `read:"description" create:"description" update:"description"` Operator string `read:"operator"` } func (c *Record) GetName() string { return "records" } func (c *Record) GetPathMethod(action api.Action) (string, string) { switch action { case api.ActionCreate: return action.ToMethod(), fmt.Sprintf("/zones/%s/%s", c.GetZoneID(), c.GetName()) case api.ActionRead, api.ActionUpdate, api.ActionDelete: return action.ToMethod(), fmt.Sprintf("/zones/%s/%s/%s", c.GetZoneID(), c.GetName(), c.ID) case api.ActionCancel: return action.ToMethod(), fmt.Sprintf("/zones/%s/%s/%s/changes", c.GetZoneID(), c.GetName(), c.ID) } return "", "" } func (c *Record) SetPathParams(args ...interface{}) error { return apis.SetPathParams(args, &c.ZoneID, &c.ID) } var _ CountableListSpec = &RecordList{} // +k8s:deepcopy-gen:interfaces=github.com/mimuret/golang-iij-dpf/pkg/api.Object type RecordList struct { AttributeMeta api.Count Items []Record `read:"items"` } func (c *RecordList) GetName() string { return "records" } func (c *RecordList) GetItems() interface{} { return &c.Items } func (c *RecordList) Len() int { return len(c.Items) } func (c *RecordList) Index(i int) interface{} { return c.Items[i] } func (c *RecordList) GetMaxLimit() int32 { return 10000 } func (c *RecordList) ClearItems() { c.Items = []Record{} } func (c *RecordList) AddItem(v interface{}) bool { if a, ok := v.(Record); ok { c.Items = append(c.Items, a) return true } return false } func (c *RecordList) GetPathMethod(action api.Action) (string, string) { return GetPathMethodForListSpec(action, c) } func (c *RecordList) SetPathParams(args ...interface{}) error { return apis.SetPathParams(args, &c.ZoneID) } func (c *RecordList) Init() { for i := range c.Items { c.Items[i].AttributeMeta = c.AttributeMeta } } var _ CountableListSpec = &CurrentRecordList{} // +k8s:deepcopy-gen:interfaces=github.com/mimuret/golang-iij-dpf/pkg/api.Object type CurrentRecordList struct { AttributeMeta api.Count Items []Record `read:"items"` } func (c *CurrentRecordList) GetName() string { return "records/currents" } func (c *CurrentRecordList) Len() int { return len(c.Items) } func (c *CurrentRecordList) GetItems() interface{} { return &c.Items } func (c *CurrentRecordList) Index(i int) interface{} { return c.Items[i] } func (c *CurrentRecordList) GetMaxLimit() int32 { return 10000 } func (c *CurrentRecordList) ClearItems() { c.Items = []Record{} } func (c *CurrentRecordList) AddItem(v interface{}) bool { if a, ok := v.(Record); ok { c.Items = append(c.Items, a) return true } return false } func (c *CurrentRecordList) GetPathMethod(action api.Action) (string, string) { return GetPathMethodForListSpec(action, c) } func (c *CurrentRecordList) Init() { for i := range c.Items { c.Items[i].AttributeMeta = c.AttributeMeta } } func (c *CurrentRecordList) SetPathParams(args ...interface{}) error { return apis.SetPathParams(args, &c.ZoneID) } func init() { register(&Record{}, &RecordList{}) register(&CurrentRecordList{}) } golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/zones/record_diff.go000066400000000000000000000044071437707610400230750ustar00rootroot00000000000000package zones import ( "net/url" "github.com/google/go-querystring/query" "github.com/mimuret/golang-iij-dpf/pkg/api" "github.com/mimuret/golang-iij-dpf/pkg/apis" ) type RecordDiff struct { New *Record `read:"new"` Old *Record `read:"old"` } var _ CountableListSpec = &RecordDiffList{} // +k8s:deepcopy-gen:interfaces=github.com/mimuret/golang-iij-dpf/pkg/api.Object type RecordDiffList struct { AttributeMeta api.Count Items []RecordDiff `read:"items"` } func (c *RecordDiffList) GetName() string { return "records/diffs" } func (c *RecordDiffList) GetItems() interface{} { return &c.Items } func (c *RecordDiffList) Len() int { return len(c.Items) } func (c *RecordDiffList) Index(i int) interface{} { return c.Items[i] } func (c *RecordDiffList) GetMaxLimit() int32 { return 10000 } func (c *RecordDiffList) ClearItems() { c.Items = []RecordDiff{} } func (c *RecordDiffList) AddItem(v interface{}) bool { if a, ok := v.(RecordDiff); ok { c.Items = append(c.Items, a) return true } return false } func (c *RecordDiffList) GetPathMethod(action api.Action) (string, string) { return GetPathMethodForListSpec(action, c) } func (c *RecordDiffList) SetPathParams(args ...interface{}) error { return apis.SetPathParams(args, &c.ZoneID) } func (c *RecordDiffList) Init() { for i := range c.Items { if c.Items[i].New != nil { c.Items[i].New.AttributeMeta = c.AttributeMeta } if c.Items[i].Old != nil { c.Items[i].Old.AttributeMeta = c.AttributeMeta } } } var _ api.SearchParams = &RecordListSearchKeywords{} // +k8s:deepcopy-gen=false type RecordListSearchKeywords struct { api.CommonSearchParams FullText api.KeywordsString `url:"_keywords_full_text[],omitempty"` Name api.KeywordsString `url:"_keywords_name[],omitempty"` TTL []int32 `url:"_keywords_ttl[],omitempty"` RRType KeywordsType `url:"_keywords_rrtype[],omitempty"` RData api.KeywordsString `url:"_keywords_rdata[],omitempty"` Description api.KeywordsString `url:"_keywords_description[],omitempty"` Operator api.KeywordsString `url:"_keywords_operator[],omitempty"` } func (s *RecordListSearchKeywords) GetValues() (url.Values, error) { return query.Values(s) } func init() { register(&RecordDiffList{}) } golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/zones/record_diff_test.go000066400000000000000000000152631437707610400241360ustar00rootroot00000000000000package zones_test import ( "context" "net/http" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/jarcoal/httpmock" "github.com/mimuret/golang-iij-dpf/pkg/apis/dpf/v1/zones" "github.com/mimuret/golang-iij-dpf/pkg/testtool" ) var _ = Describe("records/diffs", func() { var ( c zones.RecordDiffList cl *testtool.TestClient err error reqId string s1, s2, s3 zones.RecordDiff slist zones.RecordDiffList ) BeforeEach(func() { cl = testtool.NewTestClient("", "http://localhost", nil) s1 = zones.RecordDiff{ New: &zones.Record{ AttributeMeta: zones.AttributeMeta{ ZoneID: "m1", }, ID: "r1", Name: "www.example.jp.", TTL: 30, RRType: zones.TypeA, RData: []zones.RecordRDATA{ {Value: "192.168.1.1"}, {Value: "192.168.1.2"}, }, State: zones.RecordStateBeforeUpdate, Description: "SERVER Site 1(IPv4)", Operator: "user1", }, } s2 = zones.RecordDiff{ Old: &zones.Record{ AttributeMeta: zones.AttributeMeta{ ZoneID: "m1", }, ID: "r1", Name: "www.example.jp.", TTL: 30, RRType: zones.TypeA, RData: []zones.RecordRDATA{ {Value: "192.168.2.1"}, {Value: "192.168.2.2"}, }, State: zones.RecordStateApplied, Description: "SERVER Site 2(IPv4)", Operator: "user1", }, } s3 = zones.RecordDiff{ New: &zones.Record{ AttributeMeta: zones.AttributeMeta{ ZoneID: "m1", }, ID: "r3", Name: "www.example.jp.", TTL: 300, RRType: zones.TypeTXT, RData: []zones.RecordRDATA{ {Value: `"new"`}, }, State: zones.RecordStateToBeAdded, Description: "SERVER(TXT)", Operator: "user1", }, Old: &zones.Record{ AttributeMeta: zones.AttributeMeta{ ZoneID: "m1", }, ID: "r3", Name: "www.example.jp.", TTL: 300, RRType: zones.TypeTXT, RData: []zones.RecordRDATA{ {Value: `"old"`}, }, State: zones.RecordStateToBeAdded, Description: "SERVER(TXT)", Operator: "user1", }, } slist = zones.RecordDiffList{ AttributeMeta: zones.AttributeMeta{ ZoneID: "m1", }, Items: []zones.RecordDiff{s1, s2, s3}, } }) Context("RecordDiffList", func() { Context("List", func() { BeforeEach(func() { httpmock.RegisterResponder(http.MethodGet, "http://localhost/zones/m1/records/diffs", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "C36898E9087C4E2F85C94D146BC6FEDD", "results": [ { "new": { "id": "r1", "name": "www.example.jp.", "ttl": 30, "rrtype": "A", "rdata": [ { "value": "192.168.1.1" }, { "value": "192.168.1.2" } ], "state": 5, "description": "SERVER Site 1(IPv4)", "operator": "user1" } }, { "old": { "id": "r1", "name": "www.example.jp.", "ttl": 30, "rrtype": "A", "rdata": [ { "value": "192.168.2.1" }, { "value": "192.168.2.2" } ], "state": 0, "description": "SERVER Site 2(IPv4)", "operator": "user1" } }, { "new": { "id": "r3", "name": "www.example.jp.", "ttl": 300, "rrtype": "TXT", "rdata": [ { "value": "\"new\"" } ], "state": 1, "description": "SERVER(TXT)", "operator": "user1" }, "old": { "id": "r3", "name": "www.example.jp.", "ttl": 300, "rrtype": "TXT", "rdata": [ { "value": "\"old\"" } ], "state": 1, "description": "SERVER(TXT)", "operator": "user1" } } ] }`))) httpmock.RegisterResponder(http.MethodGet, "http://localhost/zones/m1/records/diffs/count", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "EE547488A8B74999AD630664802B4E25", "result": { "count": 3 } }`))) }) AfterEach(func() { httpmock.Reset() }) When("returns list ", func() { BeforeEach(func() { c = zones.RecordDiffList{ AttributeMeta: zones.AttributeMeta{ ZoneID: "m1", }, } reqId, err = cl.List(context.Background(), &c, nil) }) It("returns normal", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal("C36898E9087C4E2F85C94D146BC6FEDD")) Expect(c).To(Equal(slist)) }) }) }) Context("SetPathParams", func() { When("no arguments, nothing to do", func() { BeforeEach(func() { err = slist.SetPathParams() }) It("returns error", func() { Expect(err).To(Succeed()) }) }) When("enough arguments", func() { BeforeEach(func() { err = slist.SetPathParams("m1") }) It("not returns error", func() { Expect(err).To(Succeed()) }) It("can set ZoneID", func() { Expect(slist.GetZoneID()).To(Equal("m1")) }) }) When("arguments has extra value", func() { BeforeEach(func() { err = slist.SetPathParams("m1", 2) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) When("arguments type missmatch (ZoneID)", func() { BeforeEach(func() { err = slist.SetPathParams(1) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) }) Context("api.Spec common test", func() { var nilSpec *zones.RecordDiffList testtool.TestDeepCopyObject(&slist, nilSpec) testtool.TestGetName(&slist, "records/diffs") testtool.TestGetPathMethodForCountableList(&slist, "/zones/m1/records/diffs") }) Context("api.ListSpec common test", func() { testtool.TestGetItems(&slist, &slist.Items) testtool.TestLen(&slist, 3) Context("Index", func() { When("index exist", func() { It("returns item", func() { Expect(slist.Index(0)).To(Equal(s1)) }) }) }) }) Context("api.CountableListSpec common test", func() { testtool.TestGetMaxLimit(&slist, 10000) testtool.TestClearItems(&slist) testtool.TestAddItem(&slist, s1) }) }) Describe("RecordDiff", func() { var s, copy, nilSpec *zones.RecordDiff BeforeEach(func() { s = &zones.RecordDiff{} }) Context("DeepCopy", func() { When("object is not nil", func() { BeforeEach(func() { copy = s.DeepCopy() }) It("returns copy", func() { Expect(copy).NotTo(BeNil()) Expect(copy).To(Equal(s)) }) }) When("object is not nil", func() { BeforeEach(func() { copy = nilSpec.DeepCopy() }) It("returns nil", func() { Expect(copy).To(BeNil()) }) }) }) }) }) golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/zones/record_test.go000066400000000000000000000530571437707610400231510ustar00rootroot00000000000000package zones_test import ( "context" "net/http" "net/url" "github.com/miekg/dns" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/jarcoal/httpmock" api "github.com/mimuret/golang-iij-dpf/pkg/api" "github.com/mimuret/golang-iij-dpf/pkg/apis/dpf/v1/zones" "github.com/mimuret/golang-iij-dpf/pkg/testtool" ) var _ = Describe("records", func() { var ( c zones.Record cl *testtool.TestClient err error reqId string s1, s2 zones.Record slist zones.RecordList ) BeforeEach(func() { cl = testtool.NewTestClient("", "http://localhost", nil) s1 = zones.Record{ AttributeMeta: zones.AttributeMeta{ ZoneID: "m1", }, ID: "r1", Name: "www.example.jp.", TTL: 30, RRType: zones.TypeA, RData: []zones.RecordRDATA{ {Value: "192.168.1.1"}, {Value: "192.168.1.2"}, }, State: zones.RecordStateApplied, Description: "SERVER(IPv4)", Operator: "user1", } s2 = zones.Record{ AttributeMeta: zones.AttributeMeta{ ZoneID: "m1", }, ID: "r2", Name: "www.example.jp.", TTL: 0, RRType: zones.TypeAAAA, RData: []zones.RecordRDATA{ {Value: "2001:db8::1"}, {Value: "2001:db8::2"}, }, State: zones.RecordStateToBeAdded, Description: "SERVER(IPv6)", Operator: "user1", } slist = zones.RecordList{ AttributeMeta: zones.AttributeMeta{ ZoneID: "m1", }, Items: []zones.Record{s1, s2}, } }) Describe("Record", func() { Context("Read", func() { BeforeEach(func() { httpmock.RegisterResponder(http.MethodGet, "http://localhost/zones/m1/records/r1", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "743C1E2428264E368D37233049AD49B5", "result": { "id": "r1", "name": "www.example.jp.", "ttl": 30, "rrtype": "A", "rdata": [ { "value": "192.168.1.1" }, { "value": "192.168.1.2" } ], "state": 0, "description": "SERVER(IPv4)", "operator": "user1" } }`))) httpmock.RegisterResponder(http.MethodGet, "http://localhost/zones/m1/records/r2", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "6B69B707901B479AAF83477B31340FEE", "result": { "id": "r2", "name": "www.example.jp.", "ttl": null, "rrtype": "AAAA", "rdata": [ { "value": "2001:db8::1" }, { "value": "2001:db8::2" } ], "state": 1, "description": "SERVER(IPv6)", "operator": "user1" } }`))) }) AfterEach(func() { httpmock.Reset() }) When("returns id=r1", func() { BeforeEach(func() { c = zones.Record{ AttributeMeta: zones.AttributeMeta{ ZoneID: "m1", }, ID: "r1", } reqId, err = cl.Read(context.Background(), &c) }) It("returns normal", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal("743C1E2428264E368D37233049AD49B5")) Expect(c).To(Equal(s1)) }) }) When("returns id=r2", func() { BeforeEach(func() { c = zones.Record{ AttributeMeta: zones.AttributeMeta{ ZoneID: "m1", }, ID: "r2", } reqId, err = cl.Read(context.Background(), &c) }) It("returns normal", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal("6B69B707901B479AAF83477B31340FEE")) Expect(c).To(Equal(s2)) }) }) }) Context("Create", func() { id1, bs1 := testtool.CreateAsyncResponse() BeforeEach(func() { httpmock.RegisterResponder(http.MethodPost, "http://localhost/zones/m2/records", httpmock.NewBytesResponder(202, bs1)) }) AfterEach(func() { httpmock.Reset() }) When("create MX", func() { BeforeEach(func() { s := zones.Record{ AttributeMeta: zones.AttributeMeta{ ZoneID: "m2", }, Name: "s1.example.jp.", TTL: 0, RRType: zones.TypeMX, RData: []zones.RecordRDATA{ {Value: "10 mx1.example.jp."}, {Value: "20 mx2.example.jp."}, }, Description: "MX SERVER", } reqId, err = cl.Create(context.Background(), &s, nil) }) It("returns job_id", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal(id1)) }) It("post json", func() { Expect(cl.RequestBody["/zones/m2/records"]).To(MatchJSON(`{ "name": "s1.example.jp.", "ttl": null, "rrtype": "MX", "rdata": [ {"value": "10 mx1.example.jp."}, {"value": "20 mx2.example.jp."} ], "description": "MX SERVER" }`)) }) }) }) Context("Update", func() { var ( id1, bs1 = testtool.CreateAsyncResponse() id2, bs2 = testtool.CreateAsyncResponse() ) BeforeEach(func() { httpmock.RegisterResponder(http.MethodPatch, "http://localhost/zones/m1/records/r1", httpmock.NewBytesResponder(202, bs1)) httpmock.RegisterResponder(http.MethodPatch, "http://localhost/zones/m1/records/r2", httpmock.NewBytesResponder(202, bs2)) }) AfterEach(func() { httpmock.Reset() }) When("A record", func() { BeforeEach(func() { reqId, err = cl.Update(context.Background(), &s1, nil) }) It("returns job_id", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal(id1)) }) It("post json", func() { Expect(cl.RequestBody["/zones/m1/records/r1"]).To(MatchJSON(`{ "ttl": 30, "rdata": [ { "value": "192.168.1.1" }, { "value": "192.168.1.2" } ], "description": "SERVER(IPv4)" }`)) }) }) When("AAAA record", func() { BeforeEach(func() { reqId, err = cl.Update(context.Background(), &s2, nil) }) It("returns job_id", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal(id2)) }) It("post json", func() { Expect(cl.RequestBody["/zones/m1/records/r2"]).To(MatchJSON(`{ "ttl": null, "rdata": [ { "value": "2001:db8::1" }, { "value": "2001:db8::2" } ], "description": "SERVER(IPv6)" }`)) }) }) }) Context("Delete", func() { var ( id1, bs1 = testtool.CreateAsyncResponse() id2, bs2 = testtool.CreateAsyncResponse() ) BeforeEach(func() { httpmock.RegisterResponder(http.MethodDelete, "http://localhost/zones/m1/records/r1", httpmock.NewBytesResponder(202, bs1)) httpmock.RegisterResponder(http.MethodDelete, "http://localhost/zones/m1/records/r2", httpmock.NewBytesResponder(202, bs2)) }) AfterEach(func() { httpmock.Reset() }) When("remove A", func() { BeforeEach(func() { reqId, err = cl.Delete(context.Background(), &s1) }) It("returns normal", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal(id1)) }) }) When("remove AAAA", func() { BeforeEach(func() { reqId, err = cl.Delete(context.Background(), &s2) }) It("returns normal", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal(id2)) }) }) }) Context("Cancel", func() { var ( id1, bs1 = testtool.CreateAsyncResponse() id2, bs2 = testtool.CreateAsyncResponse() ) BeforeEach(func() { httpmock.RegisterResponder(http.MethodDelete, "http://localhost/zones/m1/records/r1/changes", httpmock.NewBytesResponder(202, bs1)) httpmock.RegisterResponder(http.MethodDelete, "http://localhost/zones/m1/records/r2/changes", httpmock.NewBytesResponder(202, bs2)) }) AfterEach(func() { httpmock.Reset() }) When("cancel edit(A)", func() { BeforeEach(func() { reqId, err = cl.Cancel(context.Background(), &s1) }) It("returns normal", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal(id1)) }) }) When("cancel edit(AAAA)", func() { BeforeEach(func() { reqId, err = cl.Cancel(context.Background(), &s2) }) It("returns normal", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal(id2)) }) }) }) Context("SetPathParams", func() { When("no arguments, nothing to do", func() { BeforeEach(func() { err = s1.SetPathParams() }) It("returns error", func() { Expect(err).To(Succeed()) }) }) When("enough arguments", func() { BeforeEach(func() { err = s1.SetPathParams("m10", "r10") }) It("not returns error", func() { Expect(err).To(Succeed()) }) It("can set CommonConfigID", func() { Expect(s1.GetZoneID()).To(Equal("m10")) }) It("can set RecordId", func() { Expect(s1.ID).To(Equal("r10")) }) }) When("not enough arguments", func() { BeforeEach(func() { err = s1.SetPathParams("m10") }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) When("arguments has extra value", func() { BeforeEach(func() { err = s1.SetPathParams("m19", "r10", 2) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) When("arguments type missmatch (ZoneID)", func() { BeforeEach(func() { err = s1.SetPathParams(2, "r1") }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) When("arguments type missmatch (RecordId)", func() { BeforeEach(func() { err = s1.SetPathParams("m1", 1) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) }) Context("api.Spec common test", func() { var nilSpec *zones.Record testtool.TestDeepCopyObject(&s1, nilSpec) testtool.TestGetName(&s1, "records") Context("", func() { When("action is ActionCreate", func() { testtool.TestGetPathMethod(&s1, api.ActionCreate, http.MethodPost, "/zones/m1/records") }) When("action is ActionRead", func() { testtool.TestGetPathMethod(&s1, api.ActionRead, http.MethodGet, "/zones/m1/records/r1") }) When("action is ActionUpdate", func() { testtool.TestGetPathMethod(&s1, api.ActionUpdate, http.MethodPatch, "/zones/m1/records/r1") }) When("action is ActionDelete", func() { testtool.TestGetPathMethod(&s1, api.ActionDelete, http.MethodDelete, "/zones/m1/records/r1") }) When("action is ActionCancel", func() { testtool.TestGetPathMethod(&s1, api.ActionCancel, http.MethodDelete, "/zones/m1/records/r1/changes") }) When("action is other", func() { testtool.TestGetPathMethod(&s1, api.ActionApply, "", "") }) }) }) }) Describe("RecordList", func() { var c zones.RecordList Context("List", func() { BeforeEach(func() { httpmock.RegisterResponder(http.MethodGet, "http://localhost/zones/m1/records", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "0987808B8D38403C8A1FBE66D72D68F7", "results": [ { "id": "r1", "name": "www.example.jp.", "ttl": 30, "rrtype": "A", "rdata": [ { "value": "192.168.1.1" }, { "value": "192.168.1.2" } ], "state": 0, "description": "SERVER(IPv4)", "operator": "user1" }, { "id": "r2", "name": "www.example.jp.", "ttl": null, "rrtype": "AAAA", "rdata": [ { "value": "2001:db8::1" }, { "value": "2001:db8::2" } ], "state": 1, "description": "SERVER(IPv6)", "operator": "user1" } ] }`))) }) AfterEach(func() { httpmock.Reset() }) When("returns list ", func() { BeforeEach(func() { c = zones.RecordList{ AttributeMeta: zones.AttributeMeta{ ZoneID: "m1", }, } reqId, err = cl.List(context.Background(), &c, nil) }) It("returns normal", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal("0987808B8D38403C8A1FBE66D72D68F7")) Expect(c).To(Equal(slist)) }) }) }) Context("SetPathParams", func() { When("no arguments, nothing to do", func() { BeforeEach(func() { err = slist.SetPathParams() }) It("returns error", func() { Expect(err).To(Succeed()) }) }) When("enough arguments", func() { BeforeEach(func() { err = slist.SetPathParams("m1") }) It("not returns error", func() { Expect(err).To(Succeed()) }) It("can set ZoneID", func() { Expect(slist.GetZoneID()).To(Equal("m1")) }) }) When("arguments has extra value", func() { BeforeEach(func() { err = slist.SetPathParams("m1", 2) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) When("arguments type missmatch (ZoneID)", func() { BeforeEach(func() { err = slist.SetPathParams(1) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) }) Context("api.Spec common test", func() { var nilSpec *zones.RecordList testtool.TestDeepCopyObject(&slist, nilSpec) testtool.TestGetName(&slist, "records") testtool.TestGetPathMethodForCountableList(&slist, "/zones/m1/records") }) Context("api.ListSpec common test", func() { testtool.TestGetItems(&slist, &slist.Items) testtool.TestLen(&slist, 2) Context("Index", func() { When("index exist", func() { It("returns item", func() { Expect(slist.Index(0)).To(Equal(s1)) }) }) }) }) Context("api.CountableListSpec common test", func() { testtool.TestGetMaxLimit(&slist, 10000) testtool.TestClearItems(&slist) testtool.TestAddItem(&slist, s1) }) }) Describe("CurrentRecordList", func() { var ( c zones.CurrentRecordList slist zones.CurrentRecordList ) BeforeEach(func() { slist = zones.CurrentRecordList{ AttributeMeta: zones.AttributeMeta{ ZoneID: "m1", }, Items: []zones.Record{s1, s2}, } }) Context("List", func() { BeforeEach(func() { httpmock.RegisterResponder(http.MethodGet, "http://localhost/zones/m1/records/currents", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "0987808B8D38403C8A1FBE66D72D68F7", "results": [ { "id": "r1", "name": "www.example.jp.", "ttl": 30, "rrtype": "A", "rdata": [ { "value": "192.168.1.1" }, { "value": "192.168.1.2" } ], "state": 0, "description": "SERVER(IPv4)", "operator": "user1" }, { "id": "r2", "name": "www.example.jp.", "ttl": null, "rrtype": "AAAA", "rdata": [ { "value": "2001:db8::1" }, { "value": "2001:db8::2" } ], "state": 1, "description": "SERVER(IPv6)", "operator": "user1" } ] }`))) }) AfterEach(func() { httpmock.Reset() }) When("returns list ", func() { BeforeEach(func() { c = zones.CurrentRecordList{ AttributeMeta: zones.AttributeMeta{ ZoneID: "m1", }, } reqId, err = cl.List(context.Background(), &c, nil) }) It("returns normal", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal("0987808B8D38403C8A1FBE66D72D68F7")) Expect(c).To(Equal(slist)) }) }) }) Context("SetPathParams", func() { When("no arguments, nothing to do", func() { BeforeEach(func() { err = slist.SetPathParams() }) It("returns error", func() { Expect(err).To(Succeed()) }) }) When("enough arguments", func() { BeforeEach(func() { err = slist.SetPathParams("m1") }) It("not returns error", func() { Expect(err).To(Succeed()) }) It("can set ZoneID", func() { Expect(slist.GetZoneID()).To(Equal("m1")) }) }) When("arguments has extra value", func() { BeforeEach(func() { err = slist.SetPathParams("m1", 2) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) When("arguments type missmatch (ZoneID)", func() { BeforeEach(func() { err = slist.SetPathParams(1) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) }) Context("api.Spec common test", func() { var nilSpec *zones.CurrentRecordList testtool.TestDeepCopyObject(&slist, nilSpec) testtool.TestGetName(&slist, "records/currents") testtool.TestGetPathMethodForCountableList(&slist, "/zones/m1/records/currents") }) Context("api.ListSpec common test", func() { testtool.TestGetItems(&slist, &slist.Items) testtool.TestLen(&slist, 2) Context("Index", func() { When("index exist", func() { It("returns item", func() { Expect(slist.Index(0)).To(Equal(s1)) }) }) }) }) Context("api.CountableListSpec common test", func() { testtool.TestGetMaxLimit(&slist, 10000) testtool.TestClearItems(&slist) testtool.TestAddItem(&slist, s1) }) }) Describe("RecordListSearchKeywords", func() { Context("GetValues", func() { testcase := []struct { keyword zones.RecordListSearchKeywords values url.Values }{ { zones.RecordListSearchKeywords{ CommonSearchParams: api.CommonSearchParams{ Type: api.SearchTypeAND, Offset: int32(10), Limit: int32(100), }, }, url.Values{ "type": []string{"AND"}, "offset": []string{"10"}, "limit": []string{"100"}, }, }, { zones.RecordListSearchKeywords{ CommonSearchParams: api.CommonSearchParams{ Type: api.SearchTypeOR, Offset: int32(10), Limit: int32(100), }, FullText: api.KeywordsString{"hogehoge", "ðŸ°"}, Name: api.KeywordsString{"example.jp.", "128/0.0.168.192.in-addr.arpa."}, TTL: []int32{300, 2147483647}, RRType: zones.KeywordsType{"A", "CNAME", "HTTPS"}, RData: api.KeywordsString{"192.168.0.1", "\"hogehoge\""}, Description: api.KeywordsString{"ðŸ‡", "ðŸº"}, Operator: api.KeywordsString{"rabbit@example.jp", "SA0000000"}, }, /* _keywords_full_text[] _keywords_name[] _keywords_ttl[] _keywords_rrtype[] _keywords_rdata[] _keywords_description[] _keywords_operator[] */ url.Values{ "type": []string{"OR"}, "offset": []string{"10"}, "limit": []string{"100"}, "_keywords_full_text[]": []string{"hogehoge", "ðŸ°"}, "_keywords_name[]": []string{"example.jp.", "128/0.0.168.192.in-addr.arpa."}, "_keywords_ttl[]": []string{"300", "2147483647"}, "_keywords_rrtype[]": []string{"A", "CNAME", "HTTPS"}, "_keywords_rdata[]": []string{"192.168.0.1", "\"hogehoge\""}, "_keywords_description[]": []string{"ðŸ‡", "ðŸº"}, "_keywords_operator[]": []string{"rabbit@example.jp", "SA0000000"}, }, }, } It("can convert url.Value", func() { for _, tc := range testcase { s, err := tc.keyword.GetValues() Expect(err).To(Succeed()) Expect(s).To(Equal(tc.values)) } }) }) }) Context("Type", func() { testcase := []struct { Type zones.Type Str string Code uint16 }{ {zones.TypeSOA, "SOA", dns.TypeSOA}, {zones.TypeA, "A", dns.TypeA}, {zones.TypeAAAA, "AAAA", dns.TypeAAAA}, {zones.TypeCAA, "CAA", dns.TypeCAA}, {zones.TypeCNAME, "CNAME", dns.TypeCNAME}, {zones.TypeDS, "DS", dns.TypeDS}, {zones.TypeNS, "NS", dns.TypeNS}, {zones.TypeMX, "MX", dns.TypeMX}, {zones.TypeNAPTR, "NAPTR", dns.TypeNAPTR}, {zones.TypeSRV, "SRV", dns.TypeSRV}, {zones.TypeTXT, "TXT", dns.TypeTXT}, {zones.TypeTLSA, "TLSA", dns.TypeTLSA}, {zones.TypePTR, "PTR", dns.TypePTR}, {zones.TypeSVCB, "SVCB", dns.TypeSVCB}, {zones.TypeHTTPS, "HTTPS", dns.TypeHTTPS}, {zones.TypeANAME, "ANAME", 65280}, } Context("String", func() { It("returns string", func() { for _, tc := range testcase { Expect(tc.Type.String()).To(Equal(tc.Str)) } }) }) Context("Uint16", func() { It("returns uint16", func() { for _, tc := range testcase { Expect(tc.Type.Uint16()).To(Equal(tc.Code)) } }) }) Context("Uint16ToType", func() { It("returns Type", func() { for _, tc := range testcase { Expect(zones.Uint16ToType(tc.Code)).To(Equal(tc.Type)) } }) }) }) Context("RecordStateToString", func() { Context("String", func() { It("returns string", func() { Expect(zones.RecordStateApplied.String()).To(Equal("Applied")) }) }) }) Context("RecordRDATA", func() { var s, copy, nilSpec *zones.RecordRDATA BeforeEach(func() { s = &zones.RecordRDATA{ Value: "hoge", } }) Context("String", func() { It("returns Value", func() { Expect(s.String()).To(Equal("hoge")) }) }) Context("DeepCopy", func() { When("object is not nil", func() { BeforeEach(func() { copy = s.DeepCopy() }) It("returns copy", func() { Expect(copy).NotTo(BeNil()) Expect(copy).To(Equal(s)) }) }) When("object is not nil", func() { BeforeEach(func() { copy = nilSpec.DeepCopy() }) It("returns nil", func() { Expect(copy).To(BeNil()) }) }) }) }) Context("RecordRDATASlice", func() { var s, copy, nilSpec zones.RecordRDATASlice BeforeEach(func() { s = zones.RecordRDATASlice{ zones.RecordRDATA{ Value: "192.168.0.1", }, zones.RecordRDATA{ Value: "192.168.0.2", }, } }) Context("String", func() { It("returns comma separated string", func() { Expect(s.String()).To(Equal("192.168.0.1,192.168.0.2")) }) }) Context("DeepCopy", func() { When("object is not nil", func() { BeforeEach(func() { copy = s.DeepCopy() }) It("returns copy", func() { Expect(copy).NotTo(BeNil()) Expect(copy).To(Equal(s)) }) }) When("object is not nil", func() { BeforeEach(func() { copy = nilSpec.DeepCopy() }) It("returns nil", func() { Expect(copy).To(BeNil()) }) }) }) }) }) golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/zones/zone_apply.go000066400000000000000000000015461437707610400230100ustar00rootroot00000000000000package zones import ( "fmt" "github.com/mimuret/golang-iij-dpf/pkg/api" "github.com/mimuret/golang-iij-dpf/pkg/apis" ) var _ api.Spec = &ZoneApply{} // +k8s:deepcopy-gen:interfaces=github.com/mimuret/golang-iij-dpf/pkg/api.Object type ZoneApply struct { AttributeMeta Description string `apply:"description"` } func (c *ZoneApply) GetName() string { return "apply" } func (c *ZoneApply) GetPathMethod(action api.Action) (string, string) { switch action { case api.ActionApply: return action.ToMethod(), fmt.Sprintf("/zones/%s/changes", c.AttributeMeta.ZoneID) case api.ActionCancel: return action.ToMethod(), fmt.Sprintf("/zones/%s/changes", c.AttributeMeta.ZoneID) } return "", "" } func (c *ZoneApply) SetPathParams(args ...interface{}) error { return apis.SetPathParams(args, &c.AttributeMeta.ZoneID) } func init() { register(&ZoneApply{}) } golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/zones/zone_apply_test.go000066400000000000000000000060611437707610400240440ustar00rootroot00000000000000package zones_test import ( "context" "net/http" "github.com/jarcoal/httpmock" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/mimuret/golang-iij-dpf/pkg/api" "github.com/mimuret/golang-iij-dpf/pkg/apis/dpf/v1/zones" "github.com/mimuret/golang-iij-dpf/pkg/testtool" ) var _ = Describe("zones", func() { var ( cl *testtool.TestClient err error reqId string s zones.ZoneApply ) BeforeEach(func() { cl = testtool.NewTestClient("", "http://localhost", nil) s = zones.ZoneApply{ AttributeMeta: zones.AttributeMeta{ ZoneID: "m1", }, Description: "commit records", } }) Describe("ZoneApply", func() { Context("Apply", func() { id1, bs1 := testtool.CreateAsyncResponse() BeforeEach(func() { httpmock.RegisterResponder(http.MethodPatch, "http://localhost/zones/m1/changes", httpmock.NewBytesResponder(202, bs1)) reqId, err = cl.Apply(context.Background(), &s, nil) }) AfterEach(func() { httpmock.Reset() }) It("returns job_id", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal(id1)) }) It("post json", func() { Expect(cl.RequestBody["/zones/m1/changes"]).To(MatchJSON(`{ "description": "commit records" }`)) }) }) Context("Cancel", func() { id1, bs1 := testtool.CreateAsyncResponse() BeforeEach(func() { httpmock.RegisterResponder(http.MethodDelete, "http://localhost/zones/m1/changes", httpmock.NewBytesResponder(202, bs1)) reqId, err = cl.Cancel(context.Background(), &s) }) AfterEach(func() { httpmock.Reset() }) It("returns job_id", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal(id1)) }) It("post json", func() { Expect(cl.RequestBody["/zones/m1/changes"]).To(Equal("")) }) }) Context("SetPathParams", func() { When("no arguments, nothing to do", func() { BeforeEach(func() { err = s.SetPathParams() }) It("returns error", func() { Expect(err).To(Succeed()) }) }) When("enough arguments", func() { BeforeEach(func() { err = s.SetPathParams("m100") }) It("not returns error", func() { Expect(err).To(Succeed()) }) It("can set ZonetId", func() { Expect(s.ZoneID).To(Equal("m100")) }) }) When("arguments has extra value", func() { BeforeEach(func() { err = s.SetPathParams("m100", 2) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) When("arguments type missmatch (ZoneID)", func() { BeforeEach(func() { err = s.SetPathParams(2) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) }) Context("api.Spec common test", func() { var nilSpec *zones.ZoneApply testtool.TestDeepCopyObject(&s, nilSpec) testtool.TestGetName(&s, "apply") Context("GetPathMethod", func() { When("action is ActionApply", func() { testtool.TestGetPathMethod(&s, api.ActionApply, http.MethodPatch, "/zones/m1/changes") }) When("other", func() { testtool.TestGetPathMethod(&s, api.ActionRead, "", "") }) }) }) }) }) golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/zones/zone_proxy.go000066400000000000000000000014651437707610400230440ustar00rootroot00000000000000package zones import ( "fmt" "github.com/mimuret/golang-iij-dpf/pkg/api" "github.com/mimuret/golang-iij-dpf/pkg/apis" "github.com/mimuret/golang-iij-dpf/pkg/types" ) var _ Spec = &ZoneProxy{} // +k8s:deepcopy-gen:interfaces=github.com/mimuret/golang-iij-dpf/pkg/api.Object type ZoneProxy struct { AttributeMeta Enabled types.Boolean `read:"enabled" update:"enabled"` } func (c *ZoneProxy) GetName() string { return "zone_proxy" } func (c *ZoneProxy) GetPathMethod(action api.Action) (string, string) { switch action { case api.ActionRead, api.ActionUpdate: return action.ToMethod(), fmt.Sprintf("/zones/%s/zone_proxy", c.GetZoneID()) } return "", "" } func (c *ZoneProxy) SetPathParams(args ...interface{}) error { return apis.SetPathParams(args, &c.ZoneID) } func init() { register(&ZoneProxy{}) } golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/zones/zone_proxy_health_check.go000066400000000000000000000026631437707610400255270ustar00rootroot00000000000000package zones import ( "net" "github.com/mimuret/golang-iij-dpf/pkg/api" "github.com/mimuret/golang-iij-dpf/pkg/apis" "github.com/mimuret/golang-iij-dpf/pkg/types" ) type ZoneProxyStatus string const ( ZoneProxyStatusSuccess ZoneProxyStatus = "success" ZoneProxyStatusFail ZoneProxyStatus = "fail" ) type ZoneProxyHealthCheck struct { Address net.IP `read:"address"` Status ZoneProxyStatus `read:"status"` TsigName string `read:"tsig_name"` Enabled types.Boolean `read:"enabled"` } var _ ListSpec = &ZoneProxyHealthCheckList{} // +k8s:deepcopy-gen:interfaces=github.com/mimuret/golang-iij-dpf/pkg/api.Object type ZoneProxyHealthCheckList struct { AttributeMeta Items []ZoneProxyHealthCheck `read:"items"` } func (c *ZoneProxyHealthCheckList) GetName() string { return "zone_proxy/health_check" } func (c *ZoneProxyHealthCheckList) Len() int { return len(c.Items) } func (c *ZoneProxyHealthCheckList) GetItems() interface{} { return &c.Items } func (c *ZoneProxyHealthCheckList) Index(i int) interface{} { return c.Items[i] } func (c *ZoneProxyHealthCheckList) GetPathMethod(action api.Action) (string, string) { return GetPathMethodForListSpec(action, c) } func (c *ZoneProxyHealthCheckList) SetPathParams(args ...interface{}) error { return apis.SetPathParams(args, &c.ZoneID) } func (c *ZoneProxyHealthCheckList) Init() {} func init() { register(&ZoneProxyHealthCheckList{}) } golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/zones/zone_proxy_health_check_test.go000066400000000000000000000102511437707610400265560ustar00rootroot00000000000000package zones_test import ( "context" net "net" "net/http" "github.com/jarcoal/httpmock" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/mimuret/golang-iij-dpf/pkg/apis/dpf/v1/zones" "github.com/mimuret/golang-iij-dpf/pkg/testtool" "github.com/mimuret/golang-iij-dpf/pkg/types" ) var _ = Describe("zone_proxy", func() { var ( c zones.ZoneProxyHealthCheckList cl *testtool.TestClient err error reqId string s1, s2 zones.ZoneProxyHealthCheck slist zones.ZoneProxyHealthCheckList ) BeforeEach(func() { cl = testtool.NewTestClient("", "http://localhost", nil) s1 = zones.ZoneProxyHealthCheck{ Address: net.ParseIP("192.168.0.1"), Status: zones.ZoneProxyStatusSuccess, TsigName: "", Enabled: types.Disabled, } s2 = zones.ZoneProxyHealthCheck{ Address: net.ParseIP("2001:db8::1"), Status: zones.ZoneProxyStatusFail, TsigName: "tsig2", Enabled: types.Enabled, } slist = zones.ZoneProxyHealthCheckList{ AttributeMeta: zones.AttributeMeta{ ZoneID: "m1", }, Items: []zones.ZoneProxyHealthCheck{s1, s2}, } }) Describe("ZoneProxy", func() { Context("List", func() { BeforeEach(func() { httpmock.RegisterResponder(http.MethodGet, "http://localhost/zones/m1/zone_proxy/health_check", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "751E0AB9585E48059090FA1B46E5B7A3", "results": [ { "address": "192.168.0.1", "status": "success", "tsig_name": "", "enabled": 0 }, { "address": "2001:db8::1", "status": "fail", "tsig_name": "tsig2", "enabled": 1 } ] }`))) }) AfterEach(func() { httpmock.Reset() }) AfterEach(func() { httpmock.Reset() }) When("returns list ", func() { BeforeEach(func() { c = zones.ZoneProxyHealthCheckList{ AttributeMeta: zones.AttributeMeta{ ZoneID: "m1", }, } reqId, err = cl.List(context.Background(), &c, nil) }) It("returns normal", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal("751E0AB9585E48059090FA1B46E5B7A3")) Expect(c).To(Equal(slist)) }) }) }) Context("SetPathParams", func() { When("no arguments, nothing to do", func() { BeforeEach(func() { err = slist.SetPathParams() }) It("returns error", func() { Expect(err).To(Succeed()) }) }) When("enough arguments", func() { BeforeEach(func() { err = slist.SetPathParams("m100") }) It("not returns error", func() { Expect(err).To(Succeed()) }) It("can set ZonetId", func() { Expect(slist.ZoneID).To(Equal("m100")) }) }) When("arguments has extra value", func() { BeforeEach(func() { err = slist.SetPathParams("m100", 2) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) When("arguments type missmatch (ZoneID)", func() { BeforeEach(func() { err = slist.SetPathParams(2) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) }) Context("api.Spec common test", func() { var nilSpec *zones.ZoneProxyHealthCheckList testtool.TestDeepCopyObject(&slist, nilSpec) testtool.TestGetName(&slist, "zone_proxy/health_check") testtool.TestGetPathMethodForList(&slist, "/zones/m1/zone_proxy/health_check") }) Context("api.ListSpec common test", func() { testtool.TestGetItems(&slist, &slist.Items) testtool.TestLen(&slist, 2) Context("Index", func() { When("index exist", func() { It("returns item", func() { Expect(slist.Index(0)).To(Equal(s1)) }) }) }) }) }) Describe("ZoneProxyHealthCheck", func() { var s, copy, nilSpec *zones.ZoneProxyHealthCheck BeforeEach(func() { s = &zones.ZoneProxyHealthCheck{} }) Context("DeepCopy", func() { When("object is not nil", func() { BeforeEach(func() { copy = s.DeepCopy() }) It("returns copy", func() { Expect(copy).NotTo(BeNil()) Expect(copy).To(Equal(s)) }) }) When("object is not nil", func() { BeforeEach(func() { copy = nilSpec.DeepCopy() }) It("returns nil", func() { Expect(copy).To(BeNil()) }) }) }) }) }) golang-iij-dpf-0.9.1/pkg/apis/dpf/v1/zones/zone_proxy_test.go000066400000000000000000000115071437707610400241010ustar00rootroot00000000000000package zones_test import ( "context" "net/http" "github.com/jarcoal/httpmock" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/mimuret/golang-iij-dpf/pkg/api" "github.com/mimuret/golang-iij-dpf/pkg/apis/dpf/v1/zones" "github.com/mimuret/golang-iij-dpf/pkg/testtool" "github.com/mimuret/golang-iij-dpf/pkg/types" ) var _ = Describe("zone_proxy", func() { var ( c zones.ZoneProxy cl *testtool.TestClient err error reqId string s1, s2 zones.ZoneProxy ) BeforeEach(func() { cl = testtool.NewTestClient("", "http://localhost", nil) s1 = zones.ZoneProxy{ AttributeMeta: zones.AttributeMeta{ ZoneID: "m1", }, Enabled: types.Enabled, } s2 = zones.ZoneProxy{ AttributeMeta: zones.AttributeMeta{ ZoneID: "m2", }, Enabled: types.Disabled, } }) Describe("ZoneProxy", func() { Context("Read", func() { BeforeEach(func() { httpmock.RegisterResponder(http.MethodGet, "http://localhost/zones/m1/zone_proxy", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "0607103482984C3B9EC782480423CE63", "result": { "enabled": 1 } }`))) httpmock.RegisterResponder(http.MethodGet, "http://localhost/zones/m2/zone_proxy", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "63896F8889174DF59FF79F5C5F4B173A", "result": { "enabled": 0 } }`))) }) AfterEach(func() { httpmock.Reset() }) When("returns id=r1", func() { BeforeEach(func() { c = zones.ZoneProxy{ AttributeMeta: zones.AttributeMeta{ ZoneID: "m1", }, } reqId, err = cl.Read(context.Background(), &c) }) It("returns normal", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal("0607103482984C3B9EC782480423CE63")) Expect(c).To(Equal(s1)) }) }) When("returns id=r2", func() { BeforeEach(func() { c = zones.ZoneProxy{ AttributeMeta: zones.AttributeMeta{ ZoneID: "m2", }, } reqId, err = cl.Read(context.Background(), &c) }) It("returns normal", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal("63896F8889174DF59FF79F5C5F4B173A")) Expect(c).To(Equal(s2)) }) }) }) Context("Update", func() { var ( id1, bs1 = testtool.CreateAsyncResponse() id2, bs2 = testtool.CreateAsyncResponse() ) BeforeEach(func() { httpmock.RegisterResponder(http.MethodPatch, "http://localhost/zones/m1/zone_proxy", httpmock.NewBytesResponder(202, bs1)) httpmock.RegisterResponder(http.MethodPatch, "http://localhost/zones/m2/zone_proxy", httpmock.NewBytesResponder(202, bs2)) }) AfterEach(func() { httpmock.Reset() }) When("enable", func() { BeforeEach(func() { reqId, err = cl.Update(context.Background(), &s1, nil) }) It("returns job_id", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal(id1)) }) It("post json", func() { Expect(cl.RequestBody["/zones/m1/zone_proxy"]).To(MatchJSON(`{ "enabled": 1 }`)) }) }) When("disabled", func() { BeforeEach(func() { reqId, err = cl.Update(context.Background(), &s2, nil) }) It("returns job_id", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal(id2)) }) It("post json", func() { Expect(cl.RequestBody["/zones/m2/zone_proxy"]).To(MatchJSON(`{ "enabled": 0 }`)) }) }) }) Context("SetPathParams", func() { When("no arguments, nothing to do", func() { BeforeEach(func() { err = s1.SetPathParams() }) It("returns error", func() { Expect(err).To(Succeed()) }) }) When("enough arguments", func() { BeforeEach(func() { err = s1.SetPathParams("m100") }) It("not returns error", func() { Expect(err).To(Succeed()) }) It("can set ZonetId", func() { Expect(s1.ZoneID).To(Equal("m100")) }) }) When("arguments has extra value", func() { BeforeEach(func() { err = s1.SetPathParams("m100", 2) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) When("arguments type missmatch (ZoneID)", func() { BeforeEach(func() { err = s1.SetPathParams(2) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) }) Context("api.Spec common test", func() { var nilSpec *zones.ZoneProxy testtool.TestDeepCopyObject(&s1, nilSpec) testtool.TestGetName(&s1, "zone_proxy") Context("GetPathMethod", func() { When("action is ActionRead", func() { testtool.TestGetPathMethod(&s1, api.ActionRead, http.MethodGet, "/zones/m1/zone_proxy") }) When("action is ActionUpdate", func() { testtool.TestGetPathMethod(&s1, api.ActionUpdate, http.MethodPatch, "/zones/m1/zone_proxy") }) When("other", func() { testtool.TestGetPathMethod(&s1, api.ActionApply, "", "") }) }) }) }) }) golang-iij-dpf-0.9.1/pkg/apiutils/000077500000000000000000000000001437707610400167345ustar00rootroot00000000000000golang-iij-dpf-0.9.1/pkg/apiutils/client_test.go000066400000000000000000000225661437707610400216130ustar00rootroot00000000000000package apiutils_test import ( "context" "github.com/mimuret/golang-iij-dpf/pkg/api" "github.com/mimuret/golang-iij-dpf/pkg/apis/dpf/v1/core" "github.com/mimuret/golang-iij-dpf/pkg/apiutils" "github.com/mimuret/golang-iij-dpf/pkg/testtool" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("client.go", func() { var ( c *testtool.TestClient s *testtool.TestSpec reqId string job *core.Job err error id string ) BeforeEach(func() { c = testtool.NewTestClient("token", "http://localhost", nil) s = &testtool.TestSpec{ ID: "id1", Name: "hoge", Number: 100, } }) Context("SyncCreate", func() { When("successful creating", func() { BeforeEach(func() { id = testtool.GenReqID() c.CreateFunc = func(s api.Spec, body interface{}) (requestId string, err error) { return id, nil } c.ReadFunc = func(s api.Spec) (requestId string, err error) { job := s.(*core.Job) job.RequestID = id job.Status = core.JobStatusSuccessful return id, nil } reqId, job, err = apiutils.SyncCreate(context.Background(), c, s, nil) }) It("not returns err", func() { Expect(err).To(Succeed()) }) It("return job", func() { Expect(job).NotTo(BeNil()) Expect(job.Status).To(Equal(core.JobStatusSuccessful)) }) It("returns last request id", func() { Expect(reqId).To(Equal(id)) }) }) }) When("successful registration of creating, but create failed", func() { BeforeEach(func() { id = testtool.GenReqID() c.CreateFunc = func(s api.Spec, body interface{}) (requestId string, err error) { return id, nil } c.ReadFunc = func(s api.Spec) (requestId string, err error) { job := s.(*core.Job) job.RequestID = id job.Status = core.JobStatusFailed return id, nil } reqId, job, err = apiutils.SyncCreate(context.Background(), c, s, nil) }) It("not returns err", func() { Expect(err).To(HaveOccurred()) }) It("return job", func() { Expect(job).NotTo(BeNil()) Expect(job.Status).To(Equal(core.JobStatusFailed)) }) It("returns last request id", func() { Expect(reqId).To(Equal(id)) }) }) When("create failed", func() { BeforeEach(func() { reqId, job, err = apiutils.SyncCreate(context.Background(), c, s, nil) }) It("returns err", func() { Expect(err).To(HaveOccurred()) }) It("not return job", func() { Expect(job).To(BeNil()) }) }) Context("SyncUpdate", func() { When("successful updating", func() { BeforeEach(func() { id = testtool.GenReqID() c.UpdateFunc = func(s api.Spec, body interface{}) (requestId string, err error) { return id, nil } c.ReadFunc = func(s api.Spec) (requestId string, err error) { job := s.(*core.Job) job.RequestID = id job.Status = core.JobStatusSuccessful return id, nil } reqId, job, err = apiutils.SyncUpdate(context.Background(), c, s, nil) }) It("not returns err", func() { Expect(err).To(Succeed()) }) It("return job", func() { Expect(job).NotTo(BeNil()) Expect(job.Status).To(Equal(core.JobStatusSuccessful)) }) It("returns last request id", func() { Expect(reqId).To(Equal(id)) }) }) }) When("successful registration of updating, but update failed", func() { BeforeEach(func() { id = testtool.GenReqID() c.UpdateFunc = func(s api.Spec, body interface{}) (requestId string, err error) { return id, nil } c.ReadFunc = func(s api.Spec) (requestId string, err error) { job := s.(*core.Job) job.RequestID = id job.Status = core.JobStatusFailed return id, nil } reqId, job, err = apiutils.SyncUpdate(context.Background(), c, s, nil) }) It("not returns err", func() { Expect(err).To(HaveOccurred()) }) It("return job", func() { Expect(job).NotTo(BeNil()) Expect(job.Status).To(Equal(core.JobStatusFailed)) }) It("returns last request id", func() { Expect(reqId).To(Equal(id)) }) }) When("update failed", func() { BeforeEach(func() { reqId, job, err = apiutils.SyncUpdate(context.Background(), c, s, nil) }) It("returns err", func() { Expect(err).To(HaveOccurred()) }) It("not return job", func() { Expect(job).To(BeNil()) }) }) Context("SyncApply", func() { When("successful appling", func() { BeforeEach(func() { id = testtool.GenReqID() c.ApplyFunc = func(s api.Spec, body interface{}) (requestId string, err error) { return id, nil } c.ReadFunc = func(s api.Spec) (requestId string, err error) { job := s.(*core.Job) job.RequestID = id job.Status = core.JobStatusSuccessful return id, nil } reqId, job, err = apiutils.SyncApply(context.Background(), c, s, nil) }) It("not returns err", func() { Expect(err).To(Succeed()) }) It("return job", func() { Expect(job).NotTo(BeNil()) Expect(job.Status).To(Equal(core.JobStatusSuccessful)) }) It("returns last request id", func() { Expect(reqId).To(Equal(id)) }) }) }) When("successful registration of appling, but apply failed", func() { BeforeEach(func() { id = testtool.GenReqID() c.ApplyFunc = func(s api.Spec, body interface{}) (requestId string, err error) { return id, nil } c.ReadFunc = func(s api.Spec) (requestId string, err error) { job := s.(*core.Job) job.RequestID = id job.Status = core.JobStatusFailed return id, nil } reqId, job, err = apiutils.SyncApply(context.Background(), c, s, nil) }) It("not returns err", func() { Expect(err).To(HaveOccurred()) }) It("return job", func() { Expect(job).NotTo(BeNil()) Expect(job.Status).To(Equal(core.JobStatusFailed)) }) It("returns last request id", func() { Expect(reqId).To(Equal(id)) }) }) When("apply failed", func() { BeforeEach(func() { reqId, job, err = apiutils.SyncApply(context.Background(), c, s, nil) }) It("returns err", func() { Expect(err).To(HaveOccurred()) }) It("not return job", func() { Expect(job).To(BeNil()) }) }) Context("SyncDelete", func() { When("successful deleting", func() { BeforeEach(func() { id = testtool.GenReqID() c.DeleteFunc = func(s api.Spec) (requestId string, err error) { return id, nil } c.ReadFunc = func(s api.Spec) (requestId string, err error) { job := s.(*core.Job) job.RequestID = id job.Status = core.JobStatusSuccessful return id, nil } reqId, job, err = apiutils.SyncDelete(context.Background(), c, s) }) It("not returns err", func() { Expect(err).To(Succeed()) }) It("return job", func() { Expect(job).NotTo(BeNil()) Expect(job.Status).To(Equal(core.JobStatusSuccessful)) }) It("returns last request id", func() { Expect(reqId).To(Equal(id)) }) }) }) When("successful registration of deleteting, but delete failed", func() { BeforeEach(func() { id = testtool.GenReqID() c.DeleteFunc = func(s api.Spec) (requestId string, err error) { return id, nil } c.ReadFunc = func(s api.Spec) (requestId string, err error) { job := s.(*core.Job) job.RequestID = id job.Status = core.JobStatusFailed return id, nil } reqId, job, err = apiutils.SyncDelete(context.Background(), c, s) }) It("not returns err", func() { Expect(err).To(HaveOccurred()) }) It("return job", func() { Expect(job).NotTo(BeNil()) Expect(job.Status).To(Equal(core.JobStatusFailed)) }) It("returns last request id", func() { Expect(reqId).To(Equal(id)) }) }) When("delete failed", func() { BeforeEach(func() { reqId, job, err = apiutils.SyncDelete(context.Background(), c, s) }) It("returns err", func() { Expect(err).To(HaveOccurred()) }) It("not return job", func() { Expect(job).To(BeNil()) }) }) Context("SyncCancel", func() { When("successful canceling", func() { BeforeEach(func() { id = testtool.GenReqID() c.CancelFunc = func(s api.Spec) (requestId string, err error) { return id, nil } c.ReadFunc = func(s api.Spec) (requestId string, err error) { job := s.(*core.Job) job.RequestID = id job.Status = core.JobStatusSuccessful return id, nil } reqId, job, err = apiutils.SyncCancel(context.Background(), c, s) }) It("not returns err", func() { Expect(err).To(Succeed()) }) It("return job", func() { Expect(job).NotTo(BeNil()) Expect(job.Status).To(Equal(core.JobStatusSuccessful)) }) It("returns last request id", func() { Expect(reqId).To(Equal(id)) }) }) }) When("successful registration of canceling, but cancel failed", func() { BeforeEach(func() { id = testtool.GenReqID() c.CancelFunc = func(s api.Spec) (requestId string, err error) { return id, nil } c.ReadFunc = func(s api.Spec) (requestId string, err error) { job := s.(*core.Job) job.RequestID = id job.Status = core.JobStatusFailed return id, nil } reqId, job, err = apiutils.SyncCancel(context.Background(), c, s) }) It("not returns err", func() { Expect(err).To(HaveOccurred()) }) It("return job", func() { Expect(job).NotTo(BeNil()) Expect(job.Status).To(Equal(core.JobStatusFailed)) }) It("returns last request id", func() { Expect(reqId).To(Equal(id)) }) }) When("cancel failed", func() { BeforeEach(func() { reqId, job, err = apiutils.SyncCancel(context.Background(), c, s) }) It("returns err", func() { Expect(err).To(HaveOccurred()) }) It("not return job", func() { Expect(job).To(BeNil()) }) }) }) golang-iij-dpf-0.9.1/pkg/apiutils/cliient.go000066400000000000000000000030631437707610400207140ustar00rootroot00000000000000package apiutils import ( "context" "time" "github.com/mimuret/golang-iij-dpf/pkg/api" "github.com/mimuret/golang-iij-dpf/pkg/apis/dpf/v1/core" ) func SyncUpdate(ctx context.Context, cl api.ClientInterface, s api.Spec, body interface{}) (string, *core.Job, error) { requestID, err := cl.Update(ctx, s, body) if err != nil { return requestID, nil, err } job, err := WaitJob(ctx, cl, requestID, time.Second) return requestID, job, err } func SyncCreate(ctx context.Context, cl api.ClientInterface, s api.Spec, body interface{}) (string, *core.Job, error) { requestID, err := cl.Create(ctx, s, body) if err != nil { return requestID, nil, err } job, err := WaitJob(ctx, cl, requestID, time.Second) return requestID, job, err } func SyncApply(ctx context.Context, cl api.ClientInterface, s api.Spec, body interface{}) (string, *core.Job, error) { requestID, err := cl.Apply(ctx, s, body) if err != nil { return requestID, nil, err } job, err := WaitJob(ctx, cl, requestID, time.Second) return requestID, job, err } func SyncDelete(ctx context.Context, cl api.ClientInterface, s api.Spec) (string, *core.Job, error) { requestID, err := cl.Delete(ctx, s) if err != nil { return requestID, nil, err } job, err := WaitJob(ctx, cl, requestID, time.Second) return requestID, job, err } func SyncCancel(ctx context.Context, cl api.ClientInterface, s api.Spec) (string, *core.Job, error) { requestID, err := cl.Cancel(ctx, s) if err != nil { return requestID, nil, err } job, err := WaitJob(ctx, cl, requestID, time.Second) return requestID, job, err } golang-iij-dpf-0.9.1/pkg/apiutils/ginkgo_test.go000066400000000000000000000006261437707610400216040ustar00rootroot00000000000000package apiutils_test import ( "testing" "github.com/jarcoal/httpmock" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) func TestGinkgo(t *testing.T) { RegisterFailHandler(Fail) RunSpecs(t, "apiutils package test suite") } var _ = BeforeSuite(func() { httpmock.Activate() }) var _ = BeforeEach(func() { httpmock.Reset() }) var _ = AfterSuite(func() { httpmock.DeactivateAndReset() }) golang-iij-dpf-0.9.1/pkg/apiutils/jobs.go000066400000000000000000000026371437707610400202300ustar00rootroot00000000000000package apiutils import ( "context" "fmt" "net/url" "os" "os/signal" "path" "strconv" "time" "github.com/mimuret/golang-iij-dpf/pkg/api" "github.com/mimuret/golang-iij-dpf/pkg/apis/dpf/v1/core" ) func WaitJob(ctx context.Context, c api.ClientInterface, jobID string, interval time.Duration) (*core.Job, error) { job := &core.Job{ RequestID: jobID, } if _, err := c.Read(ctx, job); err != nil { return nil, fmt.Errorf("failed to read Job: %w", err) } ctx, stop := signal.NotifyContext(ctx, os.Interrupt) defer stop() for job.Status == core.JobStatusRunning { job.RequestID = jobID if err := c.WatchRead(ctx, interval, job); err != nil { return nil, err } } if job.Status == core.JobStatusFailed { return job, fmt.Errorf("JobID %s job failed: type: %s msg: %s", jobID, job.ErrorType, job.ErrorMessage) } return job, nil } func ParseeResourceSystemID(job *core.Job) (string, error) { u, err := url.Parse(job.ResourceUrl) if err != nil { return "", fmt.Errorf("failed to parse resource-url: %s , %w", job.ResourceUrl, err) } _, id := path.Split(u.Path) return id, nil } func ParseeResourceID(job *core.Job) (int64, error) { idStr, err := ParseeResourceSystemID(job) if err != nil { return 0, err } id, err := strconv.ParseInt(idStr, 10, 64) if err != nil { return 0, fmt.Errorf("failed to convert to int64 resource-url: %s id: %s, %w", job.ResourceUrl, idStr, err) } return id, nil } golang-iij-dpf-0.9.1/pkg/apiutils/jobs_test.go000066400000000000000000000122241437707610400212600ustar00rootroot00000000000000package apiutils_test import ( "context" "fmt" "time" "github.com/mimuret/golang-iij-dpf/pkg/api" "github.com/mimuret/golang-iij-dpf/pkg/apis/dpf/v1/core" "github.com/mimuret/golang-iij-dpf/pkg/apiutils" "github.com/mimuret/golang-iij-dpf/pkg/testtool" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("jobs", func() { var ( c *testtool.TestClient err error ) BeforeEach(func() { c = testtool.NewTestClient("token", "http://localhost", nil) }) Context("WaitJob", func() { When("failed to read first", func() { It("return err", func() { _, err := apiutils.WaitJob(context.Background(), c, "9BCFE2E9C10D4D9A8444CB0B48C72830", time.Second) Expect(err).To(HaveOccurred()) Expect(err.Error()).To(MatchRegexp("failed to read Job")) }) }) When("failed to watch read", func() { BeforeEach(func() { c.ReadFunc = func(s api.Spec) (requestId string, err error) { job := s.(*core.Job) job.RequestID = "33CF62F20EFC468E84F9779BF6FF1B4D" job.Status = core.JobStatusRunning return "ok", nil } c.WatchReadFunc = func(ctx context.Context, interval time.Duration, s api.Spec) error { return fmt.Errorf("err") } _, err = apiutils.WaitJob(context.Background(), c, "33CF62F20EFC468E84F9779BF6FF1B4D", time.Second) }) It("return err", func() { Expect(err).To(HaveOccurred()) }) }) When("job successful", func() { BeforeEach(func() { c.ReadFunc = func(s api.Spec) (requestId string, err error) { job := s.(*core.Job) job.RequestID = "33CF62F20EFC468E84F9779BF6FF1B4D" job.Status = core.JobStatusRunning return "ok", nil } c.WatchReadFunc = func(ctx context.Context, interval time.Duration, s api.Spec) error { job := s.(*core.Job) job.RequestID = "9BCFE2E9C10D4D9A8444CB0B48C72830" job.Status = core.JobStatusSuccessful return nil } }) It("returns last job", func() { eq := &core.Job{ RequestID: "9BCFE2E9C10D4D9A8444CB0B48C72830", Status: core.JobStatusSuccessful, } Eventually(func() (*core.Job, error) { return apiutils.WaitJob(context.Background(), c, "9BCFE2E9C10D4D9A8444CB0B48C72830", time.Second) }, time.Second*10).Should(Equal(eq)) }) }) When("job failed", func() { BeforeEach(func() { c.ReadFunc = func(s api.Spec) (requestId string, err error) { job := s.(*core.Job) job.RequestID = "33CF62F20EFC468E84F9779BF6FF1B4D" job.Status = core.JobStatusFailed return "ok", nil } }) It("can add first time", func() { var err error Eventually(func() error { _, err = apiutils.WaitJob(context.Background(), c, "9BCFE2E9C10D4D9A8444CB0B48C72830", time.Second) return err }, time.Second*10).Should(HaveOccurred()) Expect(err.Error()).To(MatchRegexp("JobID 9BCFE2E9C10D4D9A8444CB0B48C72830 job failed")) }) }) }) Context("ParseeResourceSystemID", func() { var ( job *core.Job id string err error ) When("normal", func() { BeforeEach(func() { job = &core.Job{ResourceUrl: "https://api.dns-platform.jp/dpf/v1/zones/a"} id, err = apiutils.ParseeResourceSystemID(job) }) It("return err", func() { Expect(err).To(Succeed()) }) It("return id", func() { Expect(id).To(Equal("a")) }) }) When("resourceUrl is invalid url", func() { BeforeEach(func() { job = &core.Job{ResourceUrl: "%1"} id, err = apiutils.ParseeResourceSystemID(job) }) It("return err", func() { Expect(err).To(HaveOccurred()) Expect(err.Error()).To(MatchRegexp("failed to parse resource-url")) }) }) When("resourceUrl is empty", func() { BeforeEach(func() { job = &core.Job{ResourceUrl: ""} id, err = apiutils.ParseeResourceSystemID(job) }) It("return empty", func() { Expect(err).To(Succeed()) Expect(id).To(Equal("")) }) }) }) Context("ParseeResourceSystemID", func() { var ( job *core.Job id int64 err error ) When("normal", func() { BeforeEach(func() { job = &core.Job{ResourceUrl: "https://api.dns-platform.jp/dpf/v1/common_configs/100"} id, err = apiutils.ParseeResourceID(job) }) It("return err", func() { Expect(err).To(Succeed()) }) It("return id", func() { Expect(id).To(Equal(int64(100))) }) }) When("resourceUrl is invalid url", func() { BeforeEach(func() { job = &core.Job{ResourceUrl: "%1"} id, err = apiutils.ParseeResourceID(job) }) It("return err", func() { Expect(err).To(HaveOccurred()) Expect(err.Error()).To(MatchRegexp("failed to parse resource-url")) }) }) When("resourceUrl is empty", func() { BeforeEach(func() { job = &core.Job{ResourceUrl: ""} id, err = apiutils.ParseeResourceID(job) }) It("return err", func() { Expect(err).To(HaveOccurred()) Expect(err.Error()).To(MatchRegexp("failed to convert to int64")) }) }) When("id is not int64", func() { BeforeEach(func() { job = &core.Job{ResourceUrl: "https://api.dns-platform.jp/dpf/v1/zones/m1"} id, err = apiutils.ParseeResourceID(job) }) It("return err", func() { Expect(err).To(HaveOccurred()) Expect(err.Error()).To(MatchRegexp("failed to convert to int64")) }) }) }) }) golang-iij-dpf-0.9.1/pkg/apiutils/zone.go000066400000000000000000000053771437707610400202520ustar00rootroot00000000000000package apiutils import ( "context" "fmt" "github.com/miekg/dns" "github.com/mimuret/golang-iij-dpf/pkg/api" "github.com/mimuret/golang-iij-dpf/pkg/apis/dpf/v1/core" "github.com/mimuret/golang-iij-dpf/pkg/apis/dpf/v1/zones" ) var ( ErrZoneNotFound = fmt.Errorf("zone not found") ErrRecordNotFound = fmt.Errorf("record not found") ) func getZoneFromSearchKeyWords(ctx context.Context, cl api.ClientInterface, keywords *core.ZoneListSearchKeywords) (*core.Zone, error) { zoneList := &core.ZoneList{} if _, err := cl.ListAll(ctx, zoneList, keywords); err != nil { return nil, fmt.Errorf("failed to search zone: %w", err) } for _, zone := range zoneList.Items { if len(keywords.Name) > 0 && keywords.Name[0] == zone.Name { return &zone, nil } if len(keywords.ServiceCode) > 0 && keywords.ServiceCode[0] == zone.ServiceCode { return &zone, nil } } return nil, ErrZoneNotFound } func GetZoneIdFromServiceCode(ctx context.Context, cl api.ClientInterface, serviceCode string) (string, error) { z, err := GetZoneFromServiceCode(ctx, cl, serviceCode) if err != nil { return "", err } return z.ID, nil } func GetZoneFromServiceCode(ctx context.Context, cl api.ClientInterface, serviceCode string) (*core.Zone, error) { return getZoneFromSearchKeyWords(ctx, cl, &core.ZoneListSearchKeywords{ ServiceCode: api.KeywordsString{serviceCode}, }) } func GetZoneIDFromZonename(ctx context.Context, cl api.ClientInterface, zonename string) (string, error) { z, err := GetZoneFromZonename(ctx, cl, zonename) if err != nil { return "", err } return z.ID, nil } func GetZoneFromZonename(ctx context.Context, cl api.ClientInterface, zonename string) (*core.Zone, error) { return getZoneFromSearchKeyWords(ctx, cl, &core.ZoneListSearchKeywords{ Name: api.KeywordsString{zonename}, }) } func GetRecordFromZoneName(ctx context.Context, cl api.ClientInterface, zonename string, recordName string, rrtype zones.Type) (*zones.Record, error) { z, err := GetZoneFromZonename(ctx, cl, zonename) if err != nil { return nil, err } return GetRecordFromZoneID(ctx, cl, z.ID, recordName, rrtype) } func GetRecordFromZoneID(ctx context.Context, cl api.ClientInterface, zoneID string, recordName string, rrtype zones.Type) (*zones.Record, error) { recordName = dns.CanonicalName(recordName) keywords := &zones.RecordListSearchKeywords{ Name: api.KeywordsString{recordName}, } currentList := &zones.CurrentRecordList{ AttributeMeta: zones.AttributeMeta{ ZoneID: zoneID, }, } if _, err := cl.ListAll(ctx, currentList, keywords); err != nil { return nil, fmt.Errorf("failed to search records: %w", err) } for _, record := range currentList.Items { if recordName == record.Name && record.RRType == rrtype { return &record, nil } } return nil, ErrRecordNotFound } golang-iij-dpf-0.9.1/pkg/apiutils/zone_test.go000066400000000000000000000253331437707610400213030ustar00rootroot00000000000000package apiutils_test import ( "context" "github.com/mimuret/golang-iij-dpf/pkg/api" "github.com/mimuret/golang-iij-dpf/pkg/apis/dpf/v1/core" "github.com/mimuret/golang-iij-dpf/pkg/apis/dpf/v1/zones" "github.com/mimuret/golang-iij-dpf/pkg/apiutils" "github.com/mimuret/golang-iij-dpf/pkg/testtool" "github.com/mimuret/golang-iij-dpf/pkg/types" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("zone", func() { var ( err error c *testtool.TestClient zoneId string z *core.Zone r *zones.Record ) BeforeEach(func() { z = &core.Zone{ ID: "m1", CommonConfigID: 1, ServiceCode: "dpm0000001", State: 1, Favorite: 1, Name: "example.jp.", Network: "", Description: "zone 1", ZoneProxyEnabled: types.Disabled, } r = &zones.Record{ AttributeMeta: zones.AttributeMeta{ ZoneID: "m1", }, ID: "r1", Name: "example.jp.", TTL: 3600, RRType: zones.TypeSOA, RData: zones.RecordRDATASlice{ zones.RecordRDATA{ Value: "ns000.d-53.net. dns-managers.iij.ad.jp. 30 3600 600 604800 900", }, }, State: zones.RecordStateApplied, } c = testtool.NewTestClient("token", "http://localhost", nil) }) Context("GetZoneIDFromServiceCode", func() { When("failed to read", func() { BeforeEach(func() { zoneId, err = apiutils.GetZoneIdFromServiceCode(context.Background(), c, "dpm0000001") }) It("return empty error", func() { Expect(err).To(HaveOccurred()) Expect(err.Error()).To(MatchRegexp("failed to search zone")) }) }) When("find", func() { BeforeEach(func() { c.ListAllFunc = func(s api.CountableListSpec, keywords api.SearchParams) (requestId string, err error) { s.AddItem(*z) s.AddItem(core.Zone{ ID: "m2", Name: "hoge.example.jp.", }) return "", nil } zoneId, err = apiutils.GetZoneIdFromServiceCode(context.Background(), c, "dpm0000001") }) It("returns zoneId", func() { Expect(err).To(Succeed()) Expect(zoneId).To(Equal("m1")) }) }) When("not find", func() { BeforeEach(func() { c.ListAllFunc = func(s api.CountableListSpec, keywords api.SearchParams) (requestId string, err error) { s.AddItem(core.Zone{ ID: "m2", Name: "hoge.example.jp.", }) return "", nil } zoneId, err = apiutils.GetZoneIdFromServiceCode(context.Background(), c, "dpm0000001") }) It("returns err", func() { Expect(err).To(HaveOccurred()) Expect(err).To(Equal(apiutils.ErrZoneNotFound)) }) }) }) Context("GetZoneIDFromZonename", func() { When("failed to read", func() { BeforeEach(func() { zoneId, err = apiutils.GetZoneIDFromZonename(context.Background(), c, "example.jp.") }) It("return empty error", func() { Expect(err).To(HaveOccurred()) Expect(err.Error()).To(MatchRegexp("failed to search zone")) }) }) When("find", func() { BeforeEach(func() { c.ListAllFunc = func(s api.CountableListSpec, keywords api.SearchParams) (requestId string, err error) { s.AddItem(*z) s.AddItem(core.Zone{ ID: "m2", Name: "hoge.example.jp.", }) return "", nil } zoneId, err = apiutils.GetZoneIDFromZonename(context.Background(), c, "example.jp.") }) It("returns zoneId", func() { Expect(err).To(Succeed()) Expect(zoneId).To(Equal("m1")) }) }) When("not find", func() { BeforeEach(func() { c.ListAllFunc = func(s api.CountableListSpec, keywords api.SearchParams) (requestId string, err error) { s.AddItem(core.Zone{ ID: "m2", Name: "hoge.example.jp.", }) return "", nil } zoneId, err = apiutils.GetZoneIDFromZonename(context.Background(), c, "example.jp.") }) It("returns err", func() { Expect(err).To(HaveOccurred()) Expect(err).To(Equal(apiutils.ErrZoneNotFound)) }) }) }) Context("GetZoneFromZonename", func() { var z1 *core.Zone When("failed to read", func() { BeforeEach(func() { z1, err = apiutils.GetZoneFromZonename(context.Background(), c, "example.jp.") }) It("return empty", func() { Expect(err).To(HaveOccurred()) Expect(err.Error()).To(MatchRegexp("failed to search zone")) Expect(z1).To(BeNil()) }) }) When("find", func() { BeforeEach(func() { c.ListAllFunc = func(s api.CountableListSpec, keywords api.SearchParams) (requestId string, err error) { s.AddItem(*z) s.AddItem(core.Zone{ ID: "m2", Name: "hoge.example.jp.", }) return "", nil } z1, err = apiutils.GetZoneFromZonename(context.Background(), c, "example.jp.") }) It("return zone", func() { Expect(err).To(Succeed()) Expect(z1).To(Equal(z)) }) }) When("not find", func() { BeforeEach(func() { c.ListAllFunc = func(s api.CountableListSpec, keywords api.SearchParams) (requestId string, err error) { s.AddItem(core.Zone{ ID: "m2", Name: "hoge.example.jp.", }) return "", nil } z1, err = apiutils.GetZoneFromZonename(context.Background(), c, "example.jp.") }) It("returns error", func() { Expect(err).To(HaveOccurred()) Expect(err).To(Equal(apiutils.ErrZoneNotFound)) }) }) }) Context("GetRecordFromZoneName", func() { var r1 *zones.Record When("failed to read", func() { BeforeEach(func() { r1, err = apiutils.GetRecordFromZoneName(context.Background(), c, "example.jp.", "example.jp.", zones.TypeSOA) }) It("returns error", func() { Expect(err).To(HaveOccurred()) Expect(err.Error()).To(MatchRegexp("failed to search zone")) }) }) When("find", func() { BeforeEach(func() { c.ListAllFunc = func(s api.CountableListSpec, keywords api.SearchParams) (requestId string, err error) { switch v := s.(type) { case *core.ZoneList: v.AddItem(core.Zone{ ID: "m1", Name: "example.jp.", }) v.AddItem(core.Zone{ ID: "m2", Name: "hoge.example.jp.", }) case *zones.CurrentRecordList: v.AddItem(*r) } return "", nil } r1, err = apiutils.GetRecordFromZoneName(context.Background(), c, "example.jp.", "example.jp.", zones.TypeSOA) }) It("returns record", func() { Expect(err).To(Succeed()) Expect(r1).To(Equal(r)) }) }) When("not find zone", func() { BeforeEach(func() { c.ListAllFunc = func(s api.CountableListSpec, keywords api.SearchParams) (requestId string, err error) { switch v := s.(type) { case *core.ZoneList: v.AddItem(core.Zone{ ID: "m2", Name: "hoge.example.jp.", }) } return "ok", nil } r1, err = apiutils.GetRecordFromZoneName(context.Background(), c, "example.jp.", "example.jp.", zones.TypeSOA) }) It("returns error", func() { Expect(err).To(HaveOccurred()) Expect(err).To(Equal(apiutils.ErrZoneNotFound)) }) }) When("not find records", func() { BeforeEach(func() { c.ListAllFunc = func(s api.CountableListSpec, keywords api.SearchParams) (requestId string, err error) { switch v := s.(type) { case *core.ZoneList: v.AddItem(core.Zone{ ID: "m1", Name: "example.jp.", }) v.AddItem(core.Zone{ ID: "m2", Name: "hoge.example.jp.", }) case *zones.CurrentRecordList: v.AddItem(zones.Record{ AttributeMeta: zones.AttributeMeta{ ZoneID: "m1", }, ID: "r2", Name: "example.jp.", TTL: 3600, RRType: zones.TypeNS, RData: zones.RecordRDATASlice{ zones.RecordRDATA{ Value: "ns1.example.jp.", }, zones.RecordRDATA{ Value: "ns2.example.jp.", }, }, State: zones.RecordStateApplied, }) } return "", nil } r1, err = apiutils.GetRecordFromZoneName(context.Background(), c, "example.jp.", "example.jp.", zones.TypeSOA) }) It("return error", func() { Expect(err).To(HaveOccurred()) Expect(err).To(Equal(apiutils.ErrRecordNotFound)) Expect(r1).To(BeNil()) }) }) }) Context("GetRecordFromZoneID", func() { var r2 *zones.Record When("failed to read", func() { BeforeEach(func() { r2, err = apiutils.GetRecordFromZoneID(context.Background(), c, "m1", "example.jp.", zones.TypeSOA) }) It("returns error", func() { Expect(err).To(HaveOccurred()) Expect(err.Error()).To(MatchRegexp("failed to search records")) }) }) When("find", func() { BeforeEach(func() { c.ListAllFunc = func(s api.CountableListSpec, keywords api.SearchParams) (requestId string, err error) { switch v := s.(type) { case *core.ZoneList: v.AddItem(core.Zone{ ID: "m1", Name: "example.jp.", }) v.AddItem(core.Zone{ ID: "m2", Name: "hoge.example.jp.", }) case *zones.CurrentRecordList: v.AddItem(*r) } return "", nil } r2, err = apiutils.GetRecordFromZoneID(context.Background(), c, "m1", "example.jp.", zones.TypeSOA) }) It("return record", func() { Expect(err).To(Succeed()) Expect(r2).To(Equal(r)) }) }) When("not find zone", func() { BeforeEach(func() { c.ListAllFunc = func(s api.CountableListSpec, keywords api.SearchParams) (requestId string, err error) { switch v := s.(type) { case *core.ZoneList: v.AddItem(core.Zone{ ID: "m2", Name: "hoge.example.jp.", }) } return "ok", nil } r2, err = apiutils.GetRecordFromZoneID(context.Background(), c, "m1", "example.jp.", zones.TypeSOA) }) It("returns error", func() { Expect(err).To(HaveOccurred()) Expect(err).To(Equal(apiutils.ErrRecordNotFound)) }) }) When("not find records", func() { BeforeEach(func() { c.ListAllFunc = func(s api.CountableListSpec, keywords api.SearchParams) (requestId string, err error) { switch v := s.(type) { case *core.ZoneList: v.AddItem(core.Zone{ ID: "m1", Name: "example.jp.", }) v.AddItem(core.Zone{ ID: "m2", Name: "hoge.example.jp.", }) case *zones.CurrentRecordList: v.AddItem(zones.Record{ AttributeMeta: zones.AttributeMeta{ ZoneID: "m1", }, ID: "r2", Name: "example.jp.", TTL: 3600, RRType: zones.TypeNS, RData: zones.RecordRDATASlice{ zones.RecordRDATA{ Value: "ns1.example.jp.", }, zones.RecordRDATA{ Value: "ns2.example.jp.", }, }, State: zones.RecordStateApplied, }) } return "", nil } r2, err = apiutils.GetRecordFromZoneID(context.Background(), c, "m1", "example.jp.", zones.TypeSOA) }) It("returns error", func() { Expect(err).To(HaveOccurred()) Expect(err).To(Equal(apiutils.ErrRecordNotFound)) }) }) }) }) golang-iij-dpf-0.9.1/pkg/meta/000077500000000000000000000000001437707610400160305ustar00rootroot00000000000000golang-iij-dpf-0.9.1/pkg/meta/meta.go000066400000000000000000000001621437707610400173040ustar00rootroot00000000000000package meta type KindVersion struct { Kind string `json:"kind"` APIVersion string `json:"apiVersion"` } golang-iij-dpf-0.9.1/pkg/schema/000077500000000000000000000000001437707610400163425ustar00rootroot00000000000000golang-iij-dpf-0.9.1/pkg/schema/ginkgo_test.go000066400000000000000000000006221437707610400212060ustar00rootroot00000000000000package schema_test import ( "testing" "github.com/jarcoal/httpmock" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) func TestGinkgo(t *testing.T) { RegisterFailHandler(Fail) RunSpecs(t, "schema package test suite") } var _ = BeforeSuite(func() { httpmock.Activate() }) var _ = BeforeEach(func() { httpmock.Reset() }) var _ = AfterSuite(func() { httpmock.DeactivateAndReset() }) golang-iij-dpf-0.9.1/pkg/schema/schema.go000066400000000000000000000040761437707610400201400ustar00rootroot00000000000000package schema import ( "encoding/json" "fmt" "reflect" "github.com/mimuret/golang-iij-dpf/pkg/api" "github.com/mimuret/golang-iij-dpf/pkg/apis" "github.com/mimuret/golang-iij-dpf/pkg/meta" ) var SchemaSet = NewSchemaSet() type Register struct { Group string } func NewRegister(groupName string) *Register { return &Register{Group: groupName} } func (r *Register) Add(items ...apis.Spec) { SchemaSet.Add(r.Group, items) } func NewSchemaSet() *schemaSet { return &schemaSet{} } type schemaSet map[string]*schema func (s schemaSet) Add(groupName string, items []apis.Spec) { if _, ok := s[groupName]; !ok { s[groupName] = &schema{group: groupName, objectMap: make(map[string]apis.Spec)} } s[groupName].Add(items) } type schema struct { group string objectMap map[string]apis.Spec } func (s *schema) Add(items []apis.Spec) { for _, item := range items { st := reflect.TypeOf(item) if st.Kind() != reflect.Ptr { name := st.Elem().Name() panic(fmt.Sprintf("schema.Add name: `%s` is not ptr %v", name, item)) } name := st.Elem().Name() if v, ok := s.objectMap[name]; ok { panic(fmt.Sprintf("schema.Add name: `%s` is duplicated, old: %v, new: %v", name, v, item)) } s.objectMap[name] = item } } func (s schemaSet) Parse(bs []byte) (apis.Spec, error) { kv := &meta.KindVersion{} if err := json.Unmarshal(bs, kv); err != nil { return nil, fmt.Errorf("failed to parse json: %w", err) } if kv.Kind == "" { return nil, fmt.Errorf("kind value is not exist") } if kv.APIVersion == "" { return nil, fmt.Errorf("apiVersion value is not exist") } gs, ok := s[kv.APIVersion] if !ok { return nil, fmt.Errorf("apiVersion `%s` is not support", kv.APIVersion) } spec, ok := gs.objectMap[kv.Kind] if !ok { return nil, fmt.Errorf("kind value `%s` is not supported", kv.Kind) } obj, ok := spec.DeepCopyObject().(apis.Spec) if !ok { return nil, fmt.Errorf("kind value `%s` DeepCopyObject is invalid", kv.Kind) } if err := api.UnMarshalInput(bs, obj); err != nil { return nil, fmt.Errorf("failed to parse resource: %w", err) } return obj, nil } golang-iij-dpf-0.9.1/pkg/schema/schema_test.go000066400000000000000000000130031437707610400211650ustar00rootroot00000000000000package schema_test import ( "fmt" "github.com/mimuret/golang-iij-dpf/pkg/api" "github.com/mimuret/golang-iij-dpf/pkg/apis" "github.com/mimuret/golang-iij-dpf/pkg/schema" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ apis.Spec = &TestSpec{} // +k8s:deepcopy-gen:interfaces=github.com/mimuret/golang-iij-dpf/pkg/api.Object type TestSpec struct { Id string `read:"id"` Name string `read:"name"` Number int64 `read:"number"` deepCopyObjectFunc func(*TestSpec) api.Object } func (t *TestSpec) GetGroup() string { return "test" } func (t *TestSpec) GetName() string { return "tests" } func (t *TestSpec) GetPathMethod(action api.Action) (string, string) { switch action { case api.ActionCreate: return action.ToMethod(), "/tests" case api.ActionRead, api.ActionUpdate, api.ActionDelete: return action.ToMethod(), fmt.Sprintf("/tests/%s", t.Id) case api.ActionCancel: return action.ToMethod(), fmt.Sprintf("/tests/%s/cancel", t.Id) case api.ActionApply: return action.ToMethod(), fmt.Sprintf("/tests/%s/apply", t.Id) } return "", "" } func (t *TestSpec) DeepCopyTestSpec() *TestSpec { res := &TestSpec{} *res = *t return res } func (t *TestSpec) DeepCopyObject() api.Object { if t.deepCopyObjectFunc != nil { return t.deepCopyObjectFunc(t) } return t.DeepCopyTestSpec() } func (t *TestSpec) SetPathParams(...interface{}) error { return nil } type ErrSpec struct { Id string } func (t ErrSpec) GetGroup() string { return "test" } func (t ErrSpec) GetName() string { return "tests" } func (t ErrSpec) GetPathMethod(action api.Action) (string, string) { switch action { case api.ActionCreate: return action.ToMethod(), "/tests" case api.ActionRead, api.ActionUpdate, api.ActionDelete: return action.ToMethod(), fmt.Sprintf("/tests/%s", t.Id) case api.ActionCancel: return action.ToMethod(), fmt.Sprintf("/tests/%s/cancel", t.Id) case api.ActionApply: return action.ToMethod(), fmt.Sprintf("/tests/%s/apply", t.Id) } return "", "" } func (t ErrSpec) SetPathParams(...interface{}) error { return nil } func (t ErrSpec) DeepCopyObject() api.Object { return nil } var _ = Describe("Register", func() { Context("Add", func() { var register *schema.Register BeforeEach(func() { schema.SchemaSet = schema.NewSchemaSet() register = schema.NewRegister("test") }) It("can add first time", func() { register.Add(&TestSpec{}) }) It("can not add not pointer", func() { Expect(func() { register.Add(ErrSpec{}) }).To(Panic()) }) It("can not add same type", func() { register.Add(&TestSpec{}) Expect(func() { register.Add(&TestSpec{}) }).To(Panic()) }) }) Context("Parse", func() { var ( register *schema.Register obj api.Object err error ) BeforeEach(func() { schema.SchemaSet = schema.NewSchemaSet() register = schema.NewRegister("test") register.Add(&TestSpec{}) err = nil obj = nil }) When("data is not json", func() { BeforeEach(func() { obj, err = schema.SchemaSet.Parse([]byte(`{`)) }) It("returns error", func() { Expect(err).To(HaveOccurred()) Expect(err.Error()).To(MatchRegexp("failed to parse json")) }) }) When("data is json, but not found kind", func() { BeforeEach(func() { obj, err = schema.SchemaSet.Parse([]byte(`{}`)) }) It("returns error", func() { Expect(err).To(HaveOccurred()) Expect(err.Error()).To(MatchRegexp("kind value is not exist")) }) }) When("data is json, but not found apiVersion", func() { BeforeEach(func() { obj, err = schema.SchemaSet.Parse([]byte(`{"kind": "TestSpec"}`)) }) It("returns error", func() { Expect(err).To(HaveOccurred()) Expect(err.Error()).To(MatchRegexp("apiVersion value is not exist")) }) }) When("apiVersion is group, if group not found", func() { BeforeEach(func() { obj, err = schema.SchemaSet.Parse([]byte(`{"kind": "TestSpec", "apiVersion": "testtest"}`)) }) It("returns error", func() { Expect(err).To(HaveOccurred()) Expect(err.Error()).To(MatchRegexp("apiVersion `testtest` is not support")) }) }) When("kind is not found", func() { BeforeEach(func() { obj, err = schema.SchemaSet.Parse([]byte(`{"apiVersion": "test", "kind": "hogehoge"}`)) }) It("returns error", func() { Expect(err).To(HaveOccurred()) Expect(err.Error()).To(MatchRegexp("kind value `hogehoge` is not support")) }) }) When("failed to parse", func() { BeforeEach(func() { obj, err = schema.SchemaSet.Parse([]byte(`{"apiVersion": "test", "kind": "TestSpec", "resource": {"Id": 0}}`)) }) It("returns error", func() { Expect(err).To(HaveOccurred()) Expect(err.Error()).To(MatchRegexp("failed to parse resource:")) }) }) When("invalid DeepCopyObject", func() { set := schema.NewSchemaSet() BeforeEach(func() { s := &TestSpec{} s.deepCopyObjectFunc = func(ts *TestSpec) api.Object { return nil } set.Add("test", []apis.Spec{s}) obj, err = set.Parse([]byte(`{"apiVersion": "test", "kind": "TestSpec", "resource": {"Id": 0}}`)) }) It("returns error", func() { Expect(err).To(HaveOccurred()) Expect(err.Error()).To(MatchRegexp("DeepCopyObject is invalid")) }) }) When("successful", func() { BeforeEach(func() { obj, err = schema.SchemaSet.Parse([]byte(`{"apiVersion": "test", "kind": "TestSpec", "resource": {"Id": "hoge"}}`)) }) It("returns error", func() { Expect(err).To(Succeed()) tc, ok := obj.(*TestSpec) Expect(ok).To(BeTrue()) Expect(tc.Id).To(Equal("hoge")) }) }) }) }) golang-iij-dpf-0.9.1/pkg/testtool/000077500000000000000000000000001437707610400167575ustar00rootroot00000000000000golang-iij-dpf-0.9.1/pkg/testtool/ginkgo_test.go000066400000000000000000000006261437707610400216270ustar00rootroot00000000000000package testtool_test import ( "testing" "github.com/jarcoal/httpmock" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) func TestGinkgo(t *testing.T) { RegisterFailHandler(Fail) RunSpecs(t, "testtool package test suite") } var _ = BeforeSuite(func() { httpmock.Activate() }) var _ = BeforeEach(func() { httpmock.Reset() }) var _ = AfterSuite(func() { httpmock.DeactivateAndReset() }) golang-iij-dpf-0.9.1/pkg/testtool/net.go000066400000000000000000000003251437707610400200740ustar00rootroot00000000000000package testtool import "github.com/mimuret/golang-iij-dpf/pkg/types" // for testing. func MustParseIPNet(str string) *types.IPNet { n, err := types.ParseIPNet(str) if err != nil { panic(err) } return n } golang-iij-dpf-0.9.1/pkg/testtool/net_test.go000066400000000000000000000012041437707610400211300ustar00rootroot00000000000000package testtool_test import ( "github.com/mimuret/golang-iij-dpf/pkg/testtool" "github.com/mimuret/golang-iij-dpf/pkg/types" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("net.go", func() { Context("MustParseIPNet", func() { var ipnet *types.IPNet When("normal", func() { BeforeEach(func() { ipnet = testtool.MustParseIPNet("192.168.0.0/16") }) It("returns *types.IPNet", func() { Expect(ipnet).NotTo(BeNil()) }) }) When("nivalid data", func() { It("raise panic", func() { Expect(func() { testtool.MustParseIPNet("192.168.a.0/16") }).To(Panic()) }) }) }) }) golang-iij-dpf-0.9.1/pkg/testtool/response.go000066400000000000000000000005461437707610400211510ustar00rootroot00000000000000package testtool import ( "strings" "github.com/google/uuid" ) func GenReqID() string { return strings.ReplaceAll(strings.ToLower(uuid.New().String()), "-", "") } func CreateAsyncResponse() (string, []byte) { id := GenReqID() bs := []byte(`{"request_id": "` + id + `","jobs_url": "https://dpi.dns-platform.jp/v1/jobs/` + id + `"}`) return id, bs } golang-iij-dpf-0.9.1/pkg/testtool/response_test.go000066400000000000000000000015021437707610400222010ustar00rootroot00000000000000package testtool_test import ( "github.com/mimuret/golang-iij-dpf/pkg/testtool" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("response.go", func() { Context("GenReqID", func() { var reqId string BeforeEach(func() { reqId = testtool.GenReqID() }) It("returns lowercase uuuid exclude hyphen", func() { Expect(reqId).To(MatchRegexp("^[a-f0-9]+$")) }) }) Context("GenReqID", func() { var ( reqId string bs []byte ) BeforeEach(func() { reqId, bs = testtool.CreateAsyncResponse() }) It("returns RequestID", func() { Expect(reqId).To(MatchRegexp("^[a-f0-9]+$")) }) It("returns AsyncResponseJson", func() { Expect(bs).To(MatchJSON(`{ "request_id": "` + reqId + `", "jobs_url": "https://dpi.dns-platform.jp/v1/jobs/` + reqId + `" }`)) }) }) }) golang-iij-dpf-0.9.1/pkg/testtool/spec.go000066400000000000000000000200751437707610400202440ustar00rootroot00000000000000package testtool import ( "fmt" "net/http" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/mimuret/golang-iij-dpf/pkg/api" "github.com/mimuret/golang-iij-dpf/pkg/schema" ) var _ api.Spec = &TestSpec{} // +k8s:deepcopy-gen:interfaces=github.com/mimuret/golang-iij-dpf/pkg/api.Object type TestSpec struct { ID string `read:"id"` Name string `read:"name" update:"name" create:"name" apply:"name"` Number int64 `read:"number" update:"number" create:"number" apply:"number"` } func (t *TestSpec) GetGroup() string { return groupName } func (t *TestSpec) GetName() string { return "tests" } func (t *TestSpec) GetPathMethod(action api.Action) (string, string) { switch action { case api.ActionCreate: return action.ToMethod(), "/tests" case api.ActionRead, api.ActionUpdate, api.ActionDelete: return action.ToMethod(), fmt.Sprintf("/tests/%s", t.ID) case api.ActionCancel: return action.ToMethod(), fmt.Sprintf("/tests/%s/cancel", t.ID) case api.ActionApply: return action.ToMethod(), fmt.Sprintf("/tests/%s/apply", t.ID) } return "", "" } func (t *TestSpec) SetPathParams(args ...interface{}) error { if len(args) == 0 { return nil } if len(args) != 1 { return fmt.Errorf("args must be string") } id, ok := args[0].(string) if !ok { return fmt.Errorf("args must be string") } t.ID = id return nil } func (t *TestSpec) DeepCopyTestSpec() *TestSpec { if t == nil { return nil } res := &TestSpec{} *res = *t return res } func (t *TestSpec) DeepCopyObject() api.Object { return t.DeepCopyTestSpec() } var _ api.ListSpec = &TestSpecList{} // +k8s:deepcopy-gen:interfaces=github.com/mimuret/golang-iij-dpf/pkg/api.Object type TestSpecList struct { Items []TestSpec `read:"items"` } func (t *TestSpecList) DeepCopyObject() api.Object { if t == nil { return nil } res := &TestSpecList{} for _, item := range t.Items { s := item.DeepCopyTestSpec() res.Items = append(res.Items, *s) } return res } func (t *TestSpecList) GetGroup() string { return groupName } func (t *TestSpecList) GetName() string { return "tests" } func (t *TestSpecList) GetItems() interface{} { return &t.Items } func (c *TestSpecList) Len() int { return len(c.Items) } func (c *TestSpecList) Index(i int) interface{} { return c.Items[i] } func (c *TestSpecList) GetMaxLimit() int32 { return 10000 } func (c *TestSpecList) ClearItems() { c.Items = []TestSpec{} } func (c *TestSpecList) AddItem(v interface{}) bool { if a, ok := v.(TestSpec); ok { c.Items = append(c.Items, a) return true } return false } func (t *TestSpecList) GetPathMethod(action api.Action) (string, string) { if action == api.ActionList { return action.ToMethod(), "/tests" } return "", "" } func (t *TestSpecList) SetPathParams(args ...interface{}) error { return nil } func (t *TestSpecList) Init() {} var _ api.CountableListSpec = &TestSpecCountableList{} type TestSpecCountableList struct { api.Count TestSpecList } func (t *TestSpecCountableList) GetPathMethod(action api.Action) (string, string) { switch action { case api.ActionList: return action.ToMethod(), "/tests" case api.ActionCount: return action.ToMethod(), "/tests/count" } return "", "" } func (t *TestSpecCountableList) DeepCopyObject() api.Object { if t == nil { return nil } res := &TestSpecCountableList{} for _, item := range t.Items { s := item.DeepCopyTestSpec() res.Items = append(res.Items, *s) } res.Count = t.Count return res } // for api.Object func TestDeepCopyObject(s api.Object, nilSpec api.Object) { Context("DeepCopyObject", func() { var o api.Object BeforeEach(func() { o = nil }) When("spec is not nil", func() { BeforeEach(func() { o = s.DeepCopyObject() }) It("returns copy object", func() { Expect(o).To(Equal(s)) }) }) When("spec is nil", func() { BeforeEach(func() { o = nilSpec.DeepCopyObject() }) It("returns nil", func() { Expect(o).To(BeNil()) }) }) }) Context("DeepCopyObject", func() { var o api.Object BeforeEach(func() { o = nil }) When("spec is not nil", func() { BeforeEach(func() { o = s.DeepCopyObject() }) It("returns copy object", func() { Expect(o).To(Equal(s)) }) }) When("spec is nil", func() { BeforeEach(func() { o = nilSpec.DeepCopyObject() }) It("returns nil", func() { Expect(o).To(BeNil()) }) }) }) } // for api.Spec func TestGetPathMethod(spec api.Spec, action api.Action, matchMethod string, matchPath string) { var method, path string When("action test", func() { BeforeEach(func() { method, path = spec.GetPathMethod(action) }) It("returns method", func() { Expect(method).To(Equal(matchMethod), "action:"+string(action)) }) It("returns path", func() { Expect(path).To(Equal(matchPath), "action:"+string(action)) }) }) } func TestGetPathMethodForSpec(spec api.Spec, createPath, getPath string) { When("action is ActionCreate", func() { TestGetPathMethod(spec, api.ActionCreate, http.MethodPost, createPath) }) When("action is ActionRead", func() { TestGetPathMethod(spec, api.ActionRead, http.MethodGet, getPath) }) When("action is ActionUpdate", func() { TestGetPathMethod(spec, api.ActionUpdate, http.MethodPatch, getPath) }) When("action is ActionDelete", func() { TestGetPathMethod(spec, api.ActionDelete, http.MethodDelete, getPath) }) When("action is other", func() { TestGetPathMethod(spec, api.ActionApply, "", "") }) } func TestGetPathMethodForList(spec api.ListSpec, listPath string) { When("action is ActionList", func() { TestGetPathMethod(spec, api.ActionList, http.MethodGet, listPath) }) When("action is other", func() { TestGetPathMethod(spec, api.ActionCount, "", "") }) } func TestGetPathMethodForCountableList(spec api.CountableListSpec, listPath string) { When("action is ActionList", func() { TestGetPathMethod(spec, api.ActionList, http.MethodGet, listPath) }) When("action is ActionCount", func() { TestGetPathMethod(spec, api.ActionCount, http.MethodGet, listPath+"/count") }) When("action is other", func() { TestGetPathMethod(spec, api.ActionApply, "", "") }) } func TestGetName(s api.Spec, name string) { Context("GetName", func() { It("returns name", func() { Expect(s.GetName()).To(Equal(name)) }) }) } func TestGetGroup(s api.Spec, name string) { Context("GetGroup", func() { It("returns group name", func() { Expect(s.GetGroup()).To(Equal(name)) }) }) } // List Spec func TestGetItems(s api.ListSpec, items interface{}) { Context("GetItems", func() { It("returns ItemSlice", func() { Expect(s.GetItems()).To(Equal(items)) }) }) } func TestLen(s api.ListSpec, num int) { Context("Len", func() { It("returns number of items", func() { Expect(s.Len()).To(Equal(num)) }) }) } // api.CountableListSpec func TestGetMaxLimit(s api.CountableListSpec, limit int32) { Context("GetMaxLimit", func() { It("returns limit", func() { Expect(s.GetMaxLimit()).To(Equal(limit)) }) }) } func TestClearItems(s api.CountableListSpec) { Context("GetMaxLimit", func() { BeforeEach(func() { Expect(s.Len()).NotTo((Equal(0))) s.ClearItems() }) It("can delete all items", func() { Expect(s.Len()).To((Equal(0))) }) }) } func TestAddItem(s api.CountableListSpec, validData interface{}) { Context("AddItem", func() { var ( copySpec api.CountableListSpec l int ok bool ) BeforeEach(func() { copySpec = api.DeepCopyCountableListSpec(s) l = copySpec.Len() }) When("add Item", func() { BeforeEach(func() { ok = copySpec.AddItem(validData) }) It("can add into list", func() { Expect(ok).To((BeTrue())) Expect(copySpec.Len()).To(Equal(l + 1)) }) }) When("add other", func() { BeforeEach(func() { ok = copySpec.AddItem(&TestSpec{}) }) It("can not add", func() { Expect(ok).To((BeFalse())) Expect(copySpec.Len()).To(Equal(l)) }) }) }) } const groupName = "test.api.dns-platform.jp/v1" func init() { schema.NewRegister(groupName).Add(&TestSpec{}) schema.NewRegister(groupName).Add(&TestSpecList{}) schema.NewRegister(groupName).Add(&TestSpecCountableList{}) } golang-iij-dpf-0.9.1/pkg/testtool/spec_test.go000066400000000000000000000332641437707610400213070ustar00rootroot00000000000000package testtool_test import ( "context" "net/http" "github.com/jarcoal/httpmock" "github.com/mimuret/golang-iij-dpf/pkg/api" "github.com/mimuret/golang-iij-dpf/pkg/testtool" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) type SpecForGetMethodPathTest struct { testtool.TestSpecCountableList Response map[api.Action]struct { Method string Path string } } func (t *SpecForGetMethodPathTest) GetPathMethod(action api.Action) (string, string) { res := t.Response[action] return res.Method, res.Path } var _ = Describe("test spec", func() { var ( c testtool.TestSpec cl *testtool.TestClient err error reqId string s1, s2 testtool.TestSpec slist testtool.TestSpecList ctx context.Context ) BeforeEach(func() { ctx = context.Background() cl = testtool.NewTestClient("", "http://localhost", nil) s1 = testtool.TestSpec{ ID: "1", Name: "name1", Number: 100, } s2 = testtool.TestSpec{ ID: "2", Name: "", Number: 0, } slist = testtool.TestSpecList{ Items: []testtool.TestSpec{s1, s2}, } }) Describe("TestSpec", func() { Context("Read", func() { BeforeEach(func() { httpmock.RegisterResponder(http.MethodGet, "http://localhost/tests/1", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "743C1E2428264E368D37233049AD49B5", "result": { "id": "1", "name": "name1", "number": 100 } }`))) httpmock.RegisterResponder(http.MethodGet, "http://localhost/tests/2", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "6B69B707901B479AAF83477B31340FEE", "result": { "id": "2", "name": "", "number": 0 } }`))) }) When("returns id=r1", func() { BeforeEach(func() { c = testtool.TestSpec{ ID: "1", } reqId, err = cl.Read(ctx, &c) }) It("returns normal", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal("743C1E2428264E368D37233049AD49B5")) Expect(c).To(Equal(s1)) }) }) When("returns id=r2", func() { BeforeEach(func() { c = testtool.TestSpec{ ID: "2", } reqId, err = cl.Read(ctx, &c) }) It("returns normal", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal("6B69B707901B479AAF83477B31340FEE")) Expect(c).To(Equal(s2)) }) }) }) Context("Create", func() { id1, bs1 := testtool.CreateAsyncResponse() BeforeEach(func() { httpmock.RegisterResponder(http.MethodPost, "http://localhost/tests", httpmock.NewBytesResponder(202, bs1)) }) When("create", func() { BeforeEach(func() { s := testtool.TestSpec{ ID: "3", Name: "name 3", Number: 3, } reqId, err = cl.Create(ctx, &s, nil) }) It("returns job_id", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal(id1)) }) It("post json", func() { Expect(cl.RequestBody["/tests"]).To(MatchJSON(`{ "name": "name 3", "number": 3 }`)) }) }) When("create empty", func() { BeforeEach(func() { s := testtool.TestSpec{ ID: "3", Name: "", Number: 0, } reqId, err = cl.Create(ctx, &s, nil) }) It("returns job_id", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal(id1)) }) It("post json", func() { Expect(cl.RequestBody["/tests"]).To(MatchJSON(`{ "name": "", "number": 0 }`)) }) }) }) Context("Update", func() { var ( id1, bs1 = testtool.CreateAsyncResponse() id2, bs2 = testtool.CreateAsyncResponse() ) BeforeEach(func() { httpmock.RegisterResponder(http.MethodPatch, "http://localhost/tests/1", httpmock.NewBytesResponder(202, bs1)) httpmock.RegisterResponder(http.MethodPatch, "http://localhost/tests/2", httpmock.NewBytesResponder(202, bs2)) }) When("test 1", func() { BeforeEach(func() { reqId, err = cl.Update(ctx, &s1, nil) }) It("returns job_id", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal(id1)) }) It("post json", func() { Expect(cl.RequestBody["/tests/1"]).To(MatchJSON(`{ "name": "name1", "number": 100 }`)) }) }) When("test 2", func() { BeforeEach(func() { reqId, err = cl.Update(ctx, &s2, nil) }) It("returns job_id", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal(id2)) }) It("post json", func() { Expect(cl.RequestBody["/tests/2"]).To(MatchJSON(`{ "name": "", "number": 0 }`)) }) }) }) Context("Delete", func() { var ( id1, bs1 = testtool.CreateAsyncResponse() id2, bs2 = testtool.CreateAsyncResponse() ) BeforeEach(func() { httpmock.RegisterResponder(http.MethodDelete, "http://localhost/tests/1", httpmock.NewBytesResponder(202, bs1)) httpmock.RegisterResponder(http.MethodDelete, "http://localhost/tests/2", httpmock.NewBytesResponder(202, bs2)) }) When("remove1", func() { BeforeEach(func() { reqId, err = cl.Delete(ctx, &s1) }) It("returns normal", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal(id1)) }) }) When("remove 2", func() { BeforeEach(func() { reqId, err = cl.Delete(ctx, &s2) }) It("returns normal", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal(id2)) }) }) }) Context("Cancel", func() { var ( id1, bs1 = testtool.CreateAsyncResponse() id2, bs2 = testtool.CreateAsyncResponse() ) BeforeEach(func() { httpmock.RegisterResponder(http.MethodDelete, "http://localhost/tests/1/cancel", httpmock.NewBytesResponder(202, bs1)) httpmock.RegisterResponder(http.MethodDelete, "http://localhost/tests/2/cancel", httpmock.NewBytesResponder(202, bs2)) }) When("cancel edit 1", func() { BeforeEach(func() { reqId, err = cl.Cancel(ctx, &s1) }) It("returns normal", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal(id1)) }) }) When("cancel edit 2", func() { BeforeEach(func() { reqId, err = cl.Cancel(ctx, &s2) }) It("returns normal", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal(id2)) }) }) }) Context("Apply", func() { var ( id1, bs1 = testtool.CreateAsyncResponse() id2, bs2 = testtool.CreateAsyncResponse() ) BeforeEach(func() { httpmock.RegisterResponder(http.MethodPatch, "http://localhost/tests/1/apply", httpmock.NewBytesResponder(202, bs1)) httpmock.RegisterResponder(http.MethodPatch, "http://localhost/tests/2/apply", httpmock.NewBytesResponder(202, bs2)) }) When("apply edit 1", func() { BeforeEach(func() { reqId, err = cl.Apply(ctx, &s1, nil) }) It("returns normal", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal(id1)) }) }) When("apply edit 2", func() { BeforeEach(func() { reqId, err = cl.Apply(ctx, &s2, nil) }) It("returns normal", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal(id2)) }) }) }) Context("SetPathParams", func() { When("no arguments, nothing to do", func() { BeforeEach(func() { err = s1.SetPathParams() }) It("returns error", func() { Expect(err).To(Succeed()) }) }) When("enough arguments", func() { BeforeEach(func() { err = s1.SetPathParams("m100") }) It("not returns error", func() { Expect(err).To(Succeed()) }) It("can set ZonetId", func() { Expect(s1.ID).To(Equal("m100")) }) }) When("arguments has extra value", func() { BeforeEach(func() { err = s1.SetPathParams("m100", 2) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) When("arguments type missmatch (Id)", func() { BeforeEach(func() { err = s1.SetPathParams(2) }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) }) }) Context("api.Spec common test", func() { var nilSpec *testtool.TestSpec testtool.TestDeepCopyObject(&s1, nilSpec) testtool.TestGetName(&s1, "tests") testtool.TestGetGroup(&s1, "test.api.dns-platform.jp/v1") Context("", func() { When("action is ActionCreate", func() { testtool.TestGetPathMethod(&s1, api.ActionCreate, http.MethodPost, "/tests") }) When("action is ActionRead", func() { testtool.TestGetPathMethod(&s1, api.ActionRead, http.MethodGet, "/tests/1") }) When("action is ActionUpdate", func() { testtool.TestGetPathMethod(&s1, api.ActionUpdate, http.MethodPatch, "/tests/1") }) When("action is ActionDelete", func() { testtool.TestGetPathMethod(&s1, api.ActionDelete, http.MethodDelete, "/tests/1") }) When("action is ActionCancel", func() { testtool.TestGetPathMethod(&s1, api.ActionCancel, http.MethodDelete, "/tests/1/cancel") }) When("action is ActionApply", func() { testtool.TestGetPathMethod(&s1, api.ActionApply, http.MethodPatch, "/tests/1/apply") }) When("action is other", func() { testtool.TestGetPathMethod(&s1, api.ActionList, "", "") }) }) }) }) Describe("TestSpecList", func() { var c testtool.TestSpecList Context("List", func() { BeforeEach(func() { httpmock.RegisterResponder(http.MethodGet, "http://localhost/tests", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "0987808B8D38403C8A1FBE66D72D68F7", "results": [ { "id": "1", "name": "name1", "number": 100 }, { "id": "2", "name": "", "number": 0 } ] }`))) }) When("returns list ", func() { BeforeEach(func() { c = testtool.TestSpecList{} reqId, err = cl.List(ctx, &c, nil) }) It("returns normal", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal("0987808B8D38403C8A1FBE66D72D68F7")) Expect(c).To(Equal(slist)) }) }) }) Context("api.Spec common test", func() { var nilSpec *testtool.TestSpecList testtool.TestDeepCopyObject(&slist, nilSpec) testtool.TestGetName(&slist, "tests") testtool.TestGetGroup(&slist, "test.api.dns-platform.jp/v1") testtool.TestGetPathMethodForList(&slist, "/tests") }) Context("api.ListSpec common test", func() { testtool.TestGetItems(&slist, &slist.Items) testtool.TestLen(&slist, 2) Context("Index", func() { When("index exist", func() { It("returns item", func() { Expect(slist.Index(0)).To(Equal(s1)) }) }) }) }) }) Describe("TestSpecCountableList", func() { var ( c testtool.TestSpecCountableList slist testtool.TestSpecCountableList ) BeforeEach(func() { slist = testtool.TestSpecCountableList{ TestSpecList: testtool.TestSpecList{ Items: []testtool.TestSpec{s1, s2}, }, } }) Context("List", func() { BeforeEach(func() { httpmock.RegisterResponder(http.MethodGet, "http://localhost/tests", httpmock.NewBytesResponder(200, []byte(`{ "request_id": "0987808B8D38403C8A1FBE66D72D68F7", "results": [ { "id": "1", "name": "name1", "number": 100 }, { "id": "2", "name": "", "number": 0 } ] }`))) }) When("returns list ", func() { BeforeEach(func() { c = testtool.TestSpecCountableList{} reqId, err = cl.List(ctx, &c, nil) }) It("returns normal", func() { Expect(err).To(Succeed()) Expect(reqId).To(Equal("0987808B8D38403C8A1FBE66D72D68F7")) Expect(c).To(Equal(slist)) }) }) }) Context("api.Spec common test", func() { var nilSpec *testtool.TestSpecCountableList testtool.TestDeepCopyObject(&slist, nilSpec) testtool.TestGetName(&slist, "tests") testtool.TestGetPathMethodForCountableList(&slist, "/tests") }) Context("api.ListSpec common test", func() { testtool.TestGetItems(&slist, &slist.Items) testtool.TestLen(&slist, 2) Context("Index", func() { When("index exist", func() { It("returns item", func() { Expect(slist.Index(0)).To(Equal(s1)) }) }) }) }) Context("api.CountableListSpec common test", func() { testtool.TestGetMaxLimit(&slist, 10000) testtool.TestClearItems(&slist) testtool.TestAddItem(&slist, s1) }) Context("SetPathParams", func() { When("nothing to do", func() { BeforeEach(func() { err = slist.SetPathParams() }) It("returns error", func() { Expect(err).To(Succeed()) }) }) }) }) Context("TestGetPathMethod", func() { s := &SpecForGetMethodPathTest{ Response: map[api.Action]struct { Method string Path string }{ api.ActionCreate: {http.MethodPost, "/tests"}, }, } testtool.TestGetPathMethod(s, api.ActionCreate, http.MethodPost, "/tests") testtool.TestGetPathMethod(s, api.ActionList, "", "") }) Context("TestGetPathMethodForSpec", func() { s := &SpecForGetMethodPathTest{ Response: map[api.Action]struct { Method string Path string }{ api.ActionCreate: {http.MethodPost, "/tests"}, api.ActionRead: {http.MethodGet, "/tests/1"}, api.ActionUpdate: {http.MethodPatch, "/tests/1"}, api.ActionDelete: {http.MethodDelete, "/tests/1"}, api.ActionCancel: {http.MethodDelete, "/tests/cancel"}, }, } testtool.TestGetPathMethodForSpec(s, "/tests", "/tests/1") }) Context("TestGetPathMethodForList", func() { s := &SpecForGetMethodPathTest{ Response: map[api.Action]struct { Method string Path string }{ api.ActionList: {http.MethodGet, "/tests"}, }, } testtool.TestGetPathMethodForList(s, "/tests") }) Context("TestGetPathMethodForCountableList", func() { s := &SpecForGetMethodPathTest{ Response: map[api.Action]struct { Method string Path string }{ api.ActionList: {http.MethodGet, "/tests"}, api.ActionCount: {http.MethodGet, "/tests/count"}, }, } testtool.TestGetPathMethodForCountableList(s, "/tests") }) }) golang-iij-dpf-0.9.1/pkg/testtool/testclient.go000066400000000000000000000122521437707610400214660ustar00rootroot00000000000000package testtool import ( "context" "io/ioutil" "net/http" "time" "github.com/jarcoal/httpmock" "github.com/mimuret/golang-iij-dpf/pkg/api" ) var _ api.ClientInterface = &TestClient{} type TestClient struct { Client api.ClientInterface Transport *httpmock.MockTransport RequestHeaders map[string]http.Header RequestBody map[string]string ReadFunc func(s api.Spec) (requestID string, err error) ListFunc func(s api.ListSpec, keywords api.SearchParams) (requestID string, err error) ListAllFunc func(s api.CountableListSpec, keywords api.SearchParams) (requestID string, err error) CountFunc func(s api.CountableListSpec, keywords api.SearchParams) (requestID string, err error) UpdateFunc func(s api.Spec, body interface{}) (requestID string, err error) CreateFunc func(s api.Spec, body interface{}) (requestID string, err error) ApplyFunc func(s api.Spec, body interface{}) (requestID string, err error) DeleteFunc func(s api.Spec) (requestID string, err error) CancelFunc func(s api.Spec) (requestID string, err error) WatchReadFunc func(ctx context.Context, interval time.Duration, s api.Spec) error WatchListFunc func(ctx context.Context, interval time.Duration, s api.ListSpec, keyword api.SearchParams) error WatchListAllFunc func(ctx context.Context, interval time.Duration, s api.CountableListSpec, keyword api.SearchParams) error } type ResponseSpec struct { Code int Spec api.Spec Err *api.BadResponse } func NewTestClient(token, endpoint string, logger api.Logger) *TestClient { cl := api.NewClient(token, endpoint, logger) nop := &TestClient{ RequestHeaders: make(map[string]http.Header), RequestBody: make(map[string]string), } cl.SetRoundTripper(nop) nop.Client = cl return nop } func (n *TestClient) SetRoundTripper(rt http.RoundTripper) { n.Client.SetRoundTripper(rt) } func (n *TestClient) RoundTrip(req *http.Request) (*http.Response, error) { if req.Body != nil { bs, err := ioutil.ReadAll(req.Body) if err != nil { return nil, err } n.RequestBody[req.URL.Path] = string(bs) n.RequestHeaders[req.URL.Path] = req.Header } return httpmock.DefaultTransport.RoundTrip(req) } func (n *TestClient) Read(ctx context.Context, s api.Spec) (string, error) { if n.ReadFunc == nil { if n.Client != nil { return n.Client.Read(ctx, s) } return "", nil } return n.ReadFunc(s) } func (n *TestClient) List(ctx context.Context, s api.ListSpec, keywords api.SearchParams) (string, error) { if n.ListFunc == nil { if n.Client != nil { return n.Client.List(ctx, s, keywords) } return "", nil } return n.ListFunc(s, keywords) } func (n *TestClient) ListAll(ctx context.Context, s api.CountableListSpec, keywords api.SearchParams) (string, error) { if n.ListAllFunc == nil { if n.Client != nil { return n.Client.ListAll(ctx, s, keywords) } return "", nil } return n.ListAllFunc(s, keywords) } func (n *TestClient) Count(ctx context.Context, s api.CountableListSpec, keywords api.SearchParams) (string, error) { if n.CountFunc == nil { if n.Client != nil { return n.Client.Count(ctx, s, keywords) } return "", nil } return n.CountFunc(s, keywords) } func (n *TestClient) Update(ctx context.Context, s api.Spec, body interface{}) (string, error) { if n.UpdateFunc == nil { if n.Client != nil { return n.Client.Update(ctx, s, body) } return "", nil } return n.UpdateFunc(s, body) } func (n *TestClient) Create(ctx context.Context, s api.Spec, body interface{}) (string, error) { if n.CreateFunc == nil { if n.Client != nil { return n.Client.Create(ctx, s, body) } return "", nil } return n.CreateFunc(s, body) } func (n *TestClient) Apply(ctx context.Context, s api.Spec, body interface{}) (string, error) { if n.ApplyFunc == nil { if n.Client != nil { return n.Client.Apply(ctx, s, body) } return "", nil } return n.ApplyFunc(s, body) } func (n *TestClient) Delete(ctx context.Context, s api.Spec) (string, error) { if n.DeleteFunc == nil { if n.Client != nil { return n.Client.Delete(ctx, s) } return "", nil } return n.DeleteFunc(s) } func (n *TestClient) Cancel(ctx context.Context, s api.Spec) (string, error) { if n.CancelFunc == nil { if n.Client != nil { return n.Client.Cancel(ctx, s) } return "", nil } return n.CancelFunc(s) } func (n *TestClient) WatchRead(ctx context.Context, interval time.Duration, s api.Spec) error { if n.WatchReadFunc == nil { if n.Client != nil { return n.Client.WatchRead(ctx, interval, s) } return nil } return n.WatchReadFunc(ctx, interval, s) } func (n *TestClient) WatchList(ctx context.Context, interval time.Duration, s api.ListSpec, keyword api.SearchParams) error { if n.WatchListFunc == nil { if n.Client != nil { return n.Client.WatchList(ctx, interval, s, keyword) } return nil } return n.WatchListFunc(ctx, interval, s, keyword) } func (n *TestClient) WatchListAll(ctx context.Context, interval time.Duration, s api.CountableListSpec, keyword api.SearchParams) error { if n.WatchListAllFunc == nil { if n.Client != nil { return n.Client.WatchListAll(ctx, interval, s, keyword) } return nil } return n.WatchListAllFunc(ctx, interval, s, keyword) } golang-iij-dpf-0.9.1/pkg/testtool/testclient_test.go000066400000000000000000000352371437707610400225350ustar00rootroot00000000000000package testtool_test import ( "context" "fmt" "io" "net/http" "regexp" "testing/iotest" "time" "github.com/jarcoal/httpmock" "github.com/mimuret/golang-iij-dpf/pkg/api" "github.com/mimuret/golang-iij-dpf/pkg/testtool" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("testclient.go", func() { Context("TestClient", func() { var ( ctx context.Context err error reqId string cl *testtool.TestClient ok bool s testtool.TestSpec slist testtool.TestSpecCountableList count int ) BeforeEach(func() { ctx = context.TODO() ok = false s = testtool.TestSpec{ ID: "1", } slist = testtool.TestSpecCountableList{} cl = testtool.NewTestClient("token", "http://localhost", nil) // for count httpmock.RegisterRegexpResponder(http.MethodGet, regexp.MustCompile(".*"), httpmock.NewErrorResponder(fmt.Errorf("error"))) httpmock.RegisterRegexpResponder(http.MethodPatch, regexp.MustCompile(".*"), httpmock.NewErrorResponder(fmt.Errorf("error"))) httpmock.RegisterRegexpResponder(http.MethodPost, regexp.MustCompile(".*"), httpmock.NewErrorResponder(fmt.Errorf("error"))) httpmock.RegisterRegexpResponder(http.MethodDelete, regexp.MustCompile(".*"), httpmock.NewErrorResponder(fmt.Errorf("error"))) }) Context("RoundTrip", func() { var req *http.Request BeforeEach(func() { req = &http.Request{} }) When("req.Body is set", func() { When("failed to read req.Body", func() { BeforeEach(func() { req.Body = io.NopCloser(iotest.ErrReader(fmt.Errorf("error"))) _, err = cl.RoundTrip(req) }) It("return error", func() { Expect(err).To(HaveOccurred()) }) }) }) }) Context("Read", func() { When("exist ReadFunc", func() { BeforeEach(func() { cl.ReadFunc = func(s api.Spec) (requestId string, err error) { ok = true v := s.(*testtool.TestSpec) v.Name = "changed" return "", nil } _, err = cl.Read(ctx, &s) }) It("no error", func() { Expect(err).To(Succeed()) }) It("run ReadFunc", func() { Expect(ok).To(BeTrue()) }) It("can change value", func() { Expect(s.Name).To(Equal("changed")) }) }) When("not exist ReadFunc", func() { BeforeEach(func() { _, err = cl.Read(ctx, &s) count = httpmock.GetTotalCallCount() }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) It("run TestClient.Client.Read", func() { Expect(ok).To(BeFalse()) Expect(count).To(Equal(1)) }) }) When("not exist ReadFunc or Client", func() { BeforeEach(func() { cl.Client = nil reqId, err = cl.Read(ctx, &s) }) It("returns empty request id", func() { Expect(reqId).To(BeEmpty()) }) It("not returns error", func() { Expect(err).To(Succeed()) }) }) }) Context("List", func() { When("exist ListFunc", func() { BeforeEach(func() { cl.ListFunc = func(list api.ListSpec, keywords api.SearchParams) (requestId string, err error) { ok = true v := list.(*testtool.TestSpecCountableList) v.AddItem(s) return "", nil } _, err = cl.List(ctx, &slist, nil) }) It("not returns error", func() { Expect(err).To(Succeed()) }) It("run ListFunc", func() { Expect(ok).To(BeTrue()) }) It("can edit", func() { Expect(slist.Len()).To(Equal(1)) Expect(slist.Index(0)).To(Equal(s)) }) }) When("not exist ListFunc", func() { BeforeEach(func() { _, err = cl.List(ctx, &slist, nil) count = httpmock.GetTotalCallCount() }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) It("run TestClient.Client.List", func() { Expect(ok).To(BeFalse()) Expect(count).To(Equal(1)) }) }) When("not exist ListFunc or Client", func() { BeforeEach(func() { cl.Client = nil reqId, err = cl.List(ctx, &slist, nil) }) It("returns empty request id", func() { Expect(reqId).To(BeEmpty()) }) It("not returns error", func() { Expect(err).To(Succeed()) }) }) }) Context("ListAll", func() { When("exist ListAllFunc", func() { BeforeEach(func() { cl.ListAllFunc = func(list api.CountableListSpec, keywords api.SearchParams) (requestId string, err error) { ok = true v := list.(*testtool.TestSpecCountableList) v.AddItem(s) return "", nil } _, err = cl.ListAll(ctx, &slist, nil) }) It("not returns error", func() { Expect(err).To(Succeed()) }) It("run ListAllFunc", func() { Expect(ok).To(BeTrue()) }) It("can edit", func() { Expect(slist.Len()).To(Equal(1)) Expect(slist.Index(0)).To(Equal(s)) }) }) When("not exist ListAllFunc", func() { BeforeEach(func() { _, err = cl.ListAll(ctx, &slist, nil) count = httpmock.GetTotalCallCount() }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) It("run TestClient.Client.ListAll", func() { Expect(ok).To(BeFalse()) Expect(count).To(Equal(1)) }) }) When("not exist ListAllFunc or Client", func() { BeforeEach(func() { cl.Client = nil reqId, err = cl.ListAll(ctx, &slist, nil) }) It("returns empty request id", func() { Expect(reqId).To(BeEmpty()) }) It("not returns error", func() { Expect(err).To(Succeed()) }) }) }) Context("Count", func() { When("exist CountFunc", func() { BeforeEach(func() { cl.CountFunc = func(list api.CountableListSpec, keywords api.SearchParams) (requestId string, err error) { ok = true v := list.(*testtool.TestSpecCountableList) v.SetCount(100) return "", nil } _, err = cl.Count(ctx, &slist, nil) }) It("not returns error", func() { Expect(err).To(Succeed()) }) It("run CountFunc", func() { Expect(ok).To(BeTrue()) }) It("can edit", func() { Expect(slist.GetCount()).To(Equal(int32(100))) }) }) When("not exist CountFunc", func() { BeforeEach(func() { _, err = cl.Count(ctx, &slist, nil) count = httpmock.GetTotalCallCount() }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) It("run TestClient.Client.Count", func() { Expect(ok).To(BeFalse()) Expect(count).To(Equal(1)) }) }) When("not exist CountFunc or Client", func() { BeforeEach(func() { cl.Client = nil reqId, err = cl.Count(ctx, &slist, nil) }) It("returns empty request id", func() { Expect(reqId).To(BeEmpty()) }) It("not returns error", func() { Expect(err).To(Succeed()) }) }) }) Context("Update", func() { When("exist UpdateFunc", func() { BeforeEach(func() { cl.UpdateFunc = func(s api.Spec, body interface{}) (requestId string, err error) { ok = true return "", nil } _, err = cl.Update(ctx, &s, nil) }) It("not returns error", func() { Expect(err).To(Succeed()) }) It("run UpdateFunc", func() { Expect(ok).To(BeTrue()) }) }) When("not exist UpdateFunc", func() { BeforeEach(func() { _, err = cl.Update(ctx, &s, nil) count = httpmock.GetTotalCallCount() }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) It("run TestClient.Client.Update", func() { Expect(ok).To(BeFalse()) Expect(count).To(Equal(1)) }) }) When("not exist UpdateFunc or Client", func() { BeforeEach(func() { cl.Client = nil reqId, err = cl.Update(ctx, &s, nil) }) It("returns empty request id", func() { Expect(reqId).To(BeEmpty()) }) It("not returns error", func() { Expect(err).To(Succeed()) }) }) }) Context("Create", func() { When("exist CreateFunc", func() { BeforeEach(func() { cl.CreateFunc = func(s api.Spec, body interface{}) (requestId string, err error) { ok = true return "", nil } _, err = cl.Create(ctx, &s, nil) }) It("not returns error", func() { Expect(err).To(Succeed()) }) It("run CreateFunc", func() { Expect(ok).To(BeTrue()) }) }) When("not exist CreateFunc", func() { BeforeEach(func() { _, err = cl.Create(ctx, &s, nil) count = httpmock.GetTotalCallCount() }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) It("run TestClient.Client.Create", func() { Expect(ok).To(BeFalse()) Expect(count).To(Equal(1)) }) }) When("not exist CreateFunc or Client", func() { BeforeEach(func() { cl.Client = nil reqId, err = cl.Create(ctx, &s, nil) }) It("returns empty request id", func() { Expect(reqId).To(BeEmpty()) }) It("not returns error", func() { Expect(err).To(Succeed()) }) }) }) Context("Apply", func() { When("exist CreateFunc", func() { BeforeEach(func() { cl.ApplyFunc = func(s api.Spec, body interface{}) (requestId string, err error) { ok = true return "", nil } _, err = cl.Apply(ctx, &s, nil) }) It("not returns error", func() { Expect(err).To(Succeed()) }) It("run ApplyFunc", func() { Expect(ok).To(BeTrue()) }) }) When("not exist ApplyFunc", func() { BeforeEach(func() { _, err = cl.Apply(ctx, &s, nil) count = httpmock.GetTotalCallCount() }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) It("run TestClient.Client.Apply", func() { Expect(ok).To(BeFalse()) Expect(count).To(Equal(1)) }) }) When("not exist ApplyFunc or Client", func() { BeforeEach(func() { cl.Client = nil reqId, err = cl.Apply(ctx, &s, nil) }) It("returns empty request id", func() { Expect(reqId).To(BeEmpty()) }) It("not returns error", func() { Expect(err).To(Succeed()) }) }) }) Context("Delete", func() { When("exist DeleteFunc", func() { BeforeEach(func() { cl.DeleteFunc = func(s api.Spec) (requestId string, err error) { ok = true return "", nil } _, err = cl.Delete(ctx, &s) }) It("not returns error", func() { Expect(err).To(Succeed()) }) It("run DeleteFunc", func() { Expect(ok).To(BeTrue()) }) }) When("not exist DeleteFunc", func() { BeforeEach(func() { _, err = cl.Delete(ctx, &s) count = httpmock.GetTotalCallCount() }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) It("run TestClient.Client.Delete", func() { Expect(ok).To(BeFalse()) Expect(count).To(Equal(1)) }) }) When("not exist DeleteFunc or Client", func() { BeforeEach(func() { cl.Client = nil reqId, err = cl.Delete(ctx, &s) }) It("returns empty request id", func() { Expect(reqId).To(BeEmpty()) }) It("not returns error", func() { Expect(err).To(Succeed()) }) }) }) Context("Cancel", func() { When("exist CancelFunc", func() { BeforeEach(func() { cl.CancelFunc = func(s api.Spec) (requestId string, err error) { ok = true return "", nil } _, err = cl.Cancel(ctx, &s) }) It("not returns error", func() { Expect(err).To(Succeed()) }) It("run CancelFunc", func() { Expect(ok).To(BeTrue()) }) }) When("not exist CancelFunc", func() { BeforeEach(func() { _, err = cl.Cancel(ctx, &s) count = httpmock.GetTotalCallCount() }) It("returns error", func() { Expect(err).To(HaveOccurred()) }) It("run TestClient.Client.Cancel", func() { Expect(ok).To(BeFalse()) Expect(count).To(Equal(1)) }) }) When("not exist CancelFunc or Client", func() { BeforeEach(func() { cl.Client = nil reqId, err = cl.Cancel(ctx, &s) }) It("returns empty request id", func() { Expect(reqId).To(BeEmpty()) }) It("not returns error", func() { Expect(err).To(Succeed()) }) }) }) Context("WatchRead", func() { When("exist WatchReadFunc", func() { BeforeEach(func() { cl.WatchReadFunc = func(ctx context.Context, interval time.Duration, s api.Spec) error { ok = true return nil } _ = cl.WatchRead(context.TODO(), time.Second, &s) }) It("run WatchReadFunc", func() { Expect(ok).To(BeTrue()) }) }) When("not exist WatchReadFunc", func() { BeforeEach(func() { _ = cl.WatchRead(context.TODO(), time.Second, &s) count = httpmock.GetTotalCallCount() }) It("run TestClient.Client.WatchRead", func() { Expect(ok).To(BeFalse()) Expect(count).To(Equal(1)) }) }) When("not exist WatchReadFunc or Client", func() { BeforeEach(func() { cl.Client = nil err = cl.WatchRead(context.TODO(), time.Second, &s) }) It("not returns error", func() { Expect(err).To(Succeed()) }) }) }) Context("WatchList", func() { When("exist WatchListFunc", func() { BeforeEach(func() { cl.WatchListFunc = func(ctx context.Context, interval time.Duration, s api.ListSpec, keyword api.SearchParams) error { ok = true return nil } _ = cl.WatchList(context.TODO(), time.Second, &slist, nil) }) It("run WatchListFunc", func() { Expect(ok).To(BeTrue()) }) }) When("not exist WatchListFunc", func() { BeforeEach(func() { _ = cl.WatchList(context.TODO(), time.Second, &slist, nil) count = httpmock.GetTotalCallCount() }) It("run TestClient.Client.WatchList", func() { Expect(ok).To(BeFalse()) Expect(count).To(Equal(1)) }) }) When("not exist WatchListFunc or Client", func() { BeforeEach(func() { cl.Client = nil err = cl.WatchList(context.TODO(), time.Second, &slist, nil) }) It("not returns error", func() { Expect(err).To(Succeed()) }) }) }) Context("WatchListAll", func() { When("exist WatchListFunc", func() { BeforeEach(func() { cl.WatchListAllFunc = func(ctx context.Context, interval time.Duration, s api.CountableListSpec, keyword api.SearchParams) error { ok = true return nil } _ = cl.WatchListAll(context.TODO(), time.Second, &slist, nil) }) It("run WatchListFunc", func() { Expect(ok).To(BeTrue()) }) }) When("not exist WatchListAllFunc", func() { BeforeEach(func() { _ = cl.WatchListAll(context.TODO(), time.Second, &slist, nil) count = httpmock.GetTotalCallCount() }) It("run TestClient.Client.WatchListAll", func() { Expect(ok).To(BeFalse()) Expect(count).To(Equal(1)) }) }) When("not exist WatchListAllFunc or Client", func() { BeforeEach(func() { cl.Client = nil err = cl.WatchListAll(context.TODO(), time.Second, &slist, nil) }) It("not returns error", func() { Expect(err).To(Succeed()) }) }) }) }) }) golang-iij-dpf-0.9.1/pkg/types/000077500000000000000000000000001437707610400162465ustar00rootroot00000000000000golang-iij-dpf-0.9.1/pkg/types/ZZ_deepcopy_generated.go000066400000000000000000000031101437707610400230410ustar00rootroot00000000000000//go:build !ignore_autogenerated // +build !ignore_autogenerated /* MIT License Copyright (c) 2021 Manabu Sonoda 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. */ // Code generated by deepcopy-gen. DO NOT EDIT. package types // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Count) DeepCopyInto(out *Count) { *out = *in return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Count. func (in *Count) DeepCopy() *Count { if in == nil { return nil } out := new(Count) in.DeepCopyInto(out) return out } golang-iij-dpf-0.9.1/pkg/types/count.go000066400000000000000000000002511437707610400177230ustar00rootroot00000000000000package types type Count struct { Count int32 `read:"count"` } func (c *Count) SetCount(v int32) { c.Count = v } func (c *Count) GetCount() int32 { return c.Count } golang-iij-dpf-0.9.1/pkg/types/count_test.go000066400000000000000000000020101437707610400207550ustar00rootroot00000000000000package types_test import ( "github.com/mimuret/golang-iij-dpf/pkg/types" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("types.count", func() { Context("Count", func() { var count types.Count BeforeEach(func() { count.Count = 100 }) Context("GetCount", func() { It("returns count value", func() { Expect(count.GetCount()).To(Equal(int32(100))) }) }) Context("SetCount", func() { It("returns count value", func() { count.SetCount(50) Expect(count.GetCount()).To(Equal(int32(50))) }) }) Context("DeepCopy", func() { var ( copy *types.Count nilMeta *types.Count ) When("AttributeMeta is not nil", func() { BeforeEach(func() { copy = count.DeepCopy() }) It("returns copy ", func() { Expect(copy).To(Equal(&count)) }) }) When("AttributeMeta is nil", func() { BeforeEach(func() { copy = nilMeta.DeepCopy() }) It("returns copy ", func() { Expect(copy).To(BeNil()) }) }) }) }) }) golang-iij-dpf-0.9.1/pkg/types/doc.go000066400000000000000000000000541437707610400173410ustar00rootroot00000000000000package types // +k8s:deepcopy-gen=package golang-iij-dpf-0.9.1/pkg/types/ginkgo_test.go000066400000000000000000000006201437707610400211100ustar00rootroot00000000000000package types_test import ( "testing" "github.com/jarcoal/httpmock" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) func TestGinkgo(t *testing.T) { RegisterFailHandler(Fail) RunSpecs(t, "types package test suite") } var _ = BeforeSuite(func() { httpmock.Activate() }) var _ = BeforeEach(func() { httpmock.Reset() }) var _ = AfterSuite(func() { httpmock.DeactivateAndReset() }) golang-iij-dpf-0.9.1/pkg/types/int.go000066400000000000000000000017021437707610400173670ustar00rootroot00000000000000package types import ( "bytes" "encoding/json" jsoniter "github.com/json-iterator/go" ) // 0 is null type NullablePositiveInt32 int32 func (t *NullablePositiveInt32) UnmarshalJSON(bs []byte) error { if bytes.Equal(bs, []byte("null")) { return nil } var i32 int32 if err := json.Unmarshal(bs, &i32); err != nil { return err } *t = NullablePositiveInt32(i32) return nil } func (t NullablePositiveInt32) MarshalJSON() ([]byte, error) { if t == 0 { return []byte("null"), nil } return jsoniter.Marshal(int32(t)) } type NullablePositiveInt64 int64 func (t *NullablePositiveInt64) UnmarshalJSON(bs []byte) error { if bytes.Equal(bs, []byte("null")) { return nil } var i64 int64 if err := json.Unmarshal(bs, &i64); err != nil { return err } *t = NullablePositiveInt64(i64) return nil } func (t NullablePositiveInt64) MarshalJSON() ([]byte, error) { if t == 0 { return []byte("null"), nil } return jsoniter.Marshal(int64(t)) } golang-iij-dpf-0.9.1/pkg/types/int_test.go000066400000000000000000000054721437707610400204360ustar00rootroot00000000000000package types_test import ( "github.com/mimuret/golang-iij-dpf/pkg/types" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("types.NullablePositiveInt32", func() { Context("UnmarshalJSON", func() { var ( err error p32 types.NullablePositiveInt32 ) When("failed to parse int32", func() { BeforeEach(func() { err = p32.UnmarshalJSON([]byte("/")) }) It("returns err", func() { Expect(err).To(HaveOccurred()) }) }) When("args is null", func() { BeforeEach(func() { err = p32.UnmarshalJSON([]byte("null")) }) It("returns 0 value", func() { Expect(err).To(Succeed()) Expect(p32).To(Equal(types.NullablePositiveInt32(0))) }) }) When("parse successfull", func() { BeforeEach(func() { err = p32.UnmarshalJSON([]byte("1")) }) It("returns value", func() { Expect(err).To(Succeed()) Expect(p32).To(Equal(types.NullablePositiveInt32(1))) }) }) }) Context("MarshalJSON", func() { var ( err error bs []byte ) When("value is zero", func() { BeforeEach(func() { bs, err = types.NullablePositiveInt32(0).MarshalJSON() }) It("returns err", func() { Expect(err).To(Succeed()) Expect(bs).To(Equal([]byte("null"))) }) }) When("value is not null", func() { BeforeEach(func() { bs, err = types.NullablePositiveInt32(1).MarshalJSON() }) It("returns 0 value", func() { Expect(err).To(Succeed()) Expect(bs).To(Equal([]byte("1"))) }) }) }) }) var _ = Describe("types.NullablePositiveInt64", func() { Context("UnmarshalJSON", func() { var ( err error p64 types.NullablePositiveInt64 ) When("failed to parse int64", func() { BeforeEach(func() { err = p64.UnmarshalJSON([]byte("/")) }) It("returns err", func() { Expect(err).To(HaveOccurred()) }) }) When("args is null", func() { BeforeEach(func() { err = p64.UnmarshalJSON([]byte("null")) }) It("returns 0 value", func() { Expect(err).To(Succeed()) Expect(p64).To(Equal(types.NullablePositiveInt64(0))) }) }) When("parse successfull", func() { BeforeEach(func() { err = p64.UnmarshalJSON([]byte("1")) }) It("returns value", func() { Expect(err).To(Succeed()) Expect(p64).To(Equal(types.NullablePositiveInt64(1))) }) }) }) Context("MarshalJSON", func() { var ( err error bs []byte ) When("value is zero", func() { BeforeEach(func() { bs, err = types.NullablePositiveInt64(0).MarshalJSON() }) It("returns err", func() { Expect(err).To(Succeed()) Expect(bs).To(Equal([]byte("null"))) }) }) When("value is not null", func() { BeforeEach(func() { bs, err = types.NullablePositiveInt64(1).MarshalJSON() }) It("returns 0 value", func() { Expect(err).To(Succeed()) Expect(bs).To(Equal([]byte("1"))) }) }) }) }) golang-iij-dpf-0.9.1/pkg/types/net.go000066400000000000000000000016421437707610400173660ustar00rootroot00000000000000package types import ( "encoding/json" "net" ) func ParseIPNet(str string) (*IPNet, error) { _, ipnet, err := net.ParseCIDR(str) if err != nil { return nil, err } return &IPNet{*ipnet}, nil } // +k8s:deepcopy-gen=false type IPNet struct { net.IPNet } func (i IPNet) MarshalJSON() ([]byte, error) { return json.Marshal(i.String()) } func (i *IPNet) UnmarshalJSON(b []byte) error { var s string if err := json.Unmarshal(b, &s); err != nil { return err } if s == "" { i.IPNet = net.IPNet{} return nil } _, ipnet, err := net.ParseCIDR(s) if err != nil { return err } i.IPNet = *ipnet return nil } func (i *IPNet) DeepCopyInto(in *IPNet) { i.IPNet.IP = make(net.IP, len(in.IPNet.IP)) i.IPNet.Mask = make(net.IPMask, len(in.IPNet.Mask)) copy(i.IPNet.IP, in.IPNet.IP) copy(i.IPNet.Mask, in.IPNet.Mask) } func (i *IPNet) DeepCopy() *IPNet { res := &IPNet{} res.DeepCopyInto(i) return res } golang-iij-dpf-0.9.1/pkg/types/net_test.go000066400000000000000000000060441437707610400204260ustar00rootroot00000000000000package types_test import ( "encoding/json" "net" "github.com/mimuret/golang-iij-dpf/pkg/types" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("types.net", func() { Context("ParseIPNet", func() { var ( err error ipnet *types.IPNet ) When("failed to parse net.IPNet", func() { BeforeEach(func() { _, err = types.ParseIPNet("//") }) It("returns err", func() { Expect(err).To(HaveOccurred()) }) }) When("parse successfull", func() { BeforeEach(func() { ipnet, err = types.ParseIPNet("192.168.0.0/24") }) It("returns count value", func() { Expect(err).To(Succeed()) Expect(ipnet).To(Equal(&types.IPNet{ net.IPNet{ IP: net.ParseIP("192.168.0.0").To4(), Mask: net.IPv4Mask(255, 255, 255, 0), }, })) }) }) }) Context("IPNet", func() { var ( err error bs []byte ipnet *types.IPNet ) BeforeEach(func() { ipnet = &types.IPNet{} }) Context("MarshalJSON", func() { When("valid value", func() { BeforeEach(func() { ipnet, err = types.ParseIPNet("192.168.0.0/24") Expect(err).To(Succeed()) bs, err = json.Marshal(ipnet) Expect(err).To(Succeed()) }) It("returns count value", func() { Expect(string(bs)).To(Equal(`"192.168.0.0/24"`)) }) }) When("valid empty", func() { BeforeEach(func() { bs, err = json.Marshal(ipnet) Expect(err).To(Succeed()) }) It("returns count value", func() { Expect(string(bs)).To(Equal(`"\u003cnil\u003e"`)) }) }) }) Context("UnmarshalJSON", func() { When("valid format", func() { BeforeEach(func() { err = json.Unmarshal([]byte(`"192.168.0.0/24"`), ipnet) Expect(err).To(Succeed()) }) It("returns count value", func() { Expect(ipnet).To(Equal(&types.IPNet{ net.IPNet{ IP: net.ParseIP("192.168.0.0").To4(), Mask: net.IPv4Mask(255, 255, 255, 0), }, })) }) }) When("input value is struct", func() { BeforeEach(func() { err = json.Unmarshal([]byte(`{"name": "hoge"}`), ipnet) }) It("returns err", func() { Expect(err).To(HaveOccurred()) }) }) When("invalid format", func() { BeforeEach(func() { err = json.Unmarshal([]byte(`"192.168.0.0/24/24"`), ipnet) }) It("returns err", func() { Expect(err).To(HaveOccurred()) }) }) When("\u003cnil\u003e", func() { BeforeEach(func() { err = json.Unmarshal([]byte(`"\u003cnil\u003e"`), ipnet) }) It("returns err", func() { Expect(err).To(Succeed()) Expect(*ipnet).To(Equal(types.IPNet{})) }) }) }) Context("DeepCopy", func() { BeforeEach(func() { ipnet, err = types.ParseIPNet("2001:db8::1/64") Expect(err).To(Succeed()) }) It("returns copy object", func() { copy := ipnet.DeepCopy() Expect(copy).To(Equal(ipnet)) Expect(copy).ShouldNot(BeIdenticalTo(ipnet)) Expect(copy.IPNet.IP).ShouldNot(BeIdenticalTo(ipnet.IPNet.IP)) Expect(copy.IPNet.Mask).ShouldNot(BeIdenticalTo(ipnet.IPNet.Mask)) }) }) }) }) golang-iij-dpf-0.9.1/pkg/types/time.go000066400000000000000000000011571437707610400175370ustar00rootroot00000000000000package types import ( "encoding/json" "time" ) func ParseTime(layout, value string) (Time, error) { var err error res := Time{} res.Time, err = time.Parse(layout, value) if err != nil { return res, err } return res, nil } // +k8s:deepcopy-gen=false type Time struct { time.Time } func (i Time) MarshalJSON() ([]byte, error) { return json.Marshal(i.Time) } func (i *Time) UnmarshalJSON(data []byte) error { if string(data) == `""` { return nil } var err error i.Time, err = time.Parse(`"`+time.RFC3339Nano+`"`, string(data)) return err } func (i *Time) DeepCopyInto(in *Time) { i.Time = in.Time } golang-iij-dpf-0.9.1/pkg/types/time_test.go000066400000000000000000000047731437707610400206050ustar00rootroot00000000000000package types_test import ( "encoding/json" "time" "github.com/mimuret/golang-iij-dpf/pkg/types" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("types.time", func() { Context("ParseTime", func() { var ( err error t types.Time ) When("failed to parse time.Parse", func() { BeforeEach(func() { _, err = types.ParseTime(" ", "//") }) It("returns err", func() { Expect(err).To(HaveOccurred()) }) }) When("parse successfull", func() { BeforeEach(func() { t, err = types.ParseTime(time.RFC3339Nano, "2021-07-17T17:27:05.999999999+09:00") Expect(err).To(Succeed()) }) It("returns count value", func() { Expect(t.Year()).To(Equal(2021)) Expect(t.Month()).To(Equal(time.July)) Expect(t.Day()).To(Equal(17)) Expect(t.Hour()).To(Equal(17)) Expect(t.Minute()).To(Equal(27)) }) }) }) Context("Time", func() { var ( bs []byte err error t types.Time ) Context("MarshalJSON", func() { When("valid value", func() { BeforeEach(func() { t, err = types.ParseTime(time.RFC3339Nano, "2021-07-17T17:27:05.01+09:00") Expect(err).To(Succeed()) bs, err = json.Marshal(t) Expect(err).To(Succeed()) }) It("return string", func() { Expect(string(bs)).To(Equal(`"2021-07-17T17:27:05.01+09:00"`)) }) }) }) Context("UnmarshalJSON", func() { When("invalid format", func() { BeforeEach(func() { err = json.Unmarshal([]byte(`"p[rke[prkew[rkwe[rkw["`), &t) }) It("returns count value", func() { Expect(err).To(HaveOccurred()) }) }) When("empty value", func() { BeforeEach(func() { err = json.Unmarshal([]byte(`""`), &t) }) It("returns count value", func() { Expect(err).To(Succeed()) Expect(t).To(Equal(types.Time{})) }) }) When("valid format", func() { BeforeEach(func() { err = json.Unmarshal([]byte(`"2021-07-17T17:27:05.0+09:00"`), &t) Expect(err).To(Succeed()) }) It("returns count value", func() { te, err := types.ParseTime(time.RFC3339Nano, "2021-07-17T17:27:05.0+09:00") Expect(err).To(Succeed()) Expect(t).To(Equal(te)) }) }) }) Context("DeepCopyInto", func() { BeforeEach(func() { err = json.Unmarshal([]byte(`"2021-07-17T17:27:05.0+09:00"`), &t) Expect(err).To(Succeed()) }) It("returns copy object", func() { copy := types.Time{} copy.DeepCopyInto(&t) Expect(copy).To(Equal(t)) Expect(©).ShouldNot(BeIdenticalTo(&t)) }) }) }) }) golang-iij-dpf-0.9.1/pkg/types/types.go000066400000000000000000000013771437707610400177510ustar00rootroot00000000000000package types type Boolean int const ( Enabled Boolean = 1 Disabled Boolean = 0 ) func (c Boolean) String() string { booleanToString := map[Boolean]string{ Enabled: "Enabled", Disabled: "Disabled", } return booleanToString[c] } type State int const ( StateBeforeStart State = 1 StateRunning State = 2 ) func (c State) String() string { stateToString := map[State]string{ StateBeforeStart: "BeforeStart", StateRunning: "Started", } return stateToString[c] } type Favorite int const ( FavoriteHighPriority Favorite = 1 FavoriteLowPriority Favorite = 2 ) func (c Favorite) String() string { favoriteToString := map[Favorite]string{ FavoriteHighPriority: "High", FavoriteLowPriority: "Low", } return favoriteToString[c] } golang-iij-dpf-0.9.1/pkg/types/types_test.go000066400000000000000000000023361437707610400210040ustar00rootroot00000000000000package types_test import ( "github.com/mimuret/golang-iij-dpf/pkg/types" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("types", func() { Context("Boolean", func() { Context("String", func() { When("Enabled", func() { It("return Enabled", func() { Expect(types.Enabled.String()).To(Equal("Enabled")) }) }) When("Disabled", func() { It("return Disabled", func() { Expect(types.Disabled.String()).To(Equal("Disabled")) }) }) }) }) Context("State", func() { Context("String", func() { When("Enabled", func() { It("return StateBeforeStart", func() { Expect(types.StateBeforeStart.String()).To(Equal("BeforeStart")) }) }) When("Disabled", func() { It("return StateRunning", func() { Expect(types.StateRunning.String()).To(Equal("Started")) }) }) }) }) Context("Favorite", func() { Context("String", func() { When("Enabled", func() { It("return FavoriteHighPriority", func() { Expect(types.FavoriteHighPriority.String()).To(Equal("High")) }) }) When("Disabled", func() { It("return FavoriteLowPriority", func() { Expect(types.FavoriteLowPriority.String()).To(Equal("Low")) }) }) }) }) }) golang-iij-dpf-0.9.1/pkg/utils/000077500000000000000000000000001437707610400162425ustar00rootroot00000000000000golang-iij-dpf-0.9.1/pkg/utils/convert.go000066400000000000000000000010401437707610400202440ustar00rootroot00000000000000package utils import ( "fmt" ) func ToInt64(val interface{}) (int64, error) { var res int64 switch v := val.(type) { case int: res = int64(v) case int8: res = int64(v) case int16: res = int64(v) case int32: res = int64(v) case int64: res = v default: return 0, fmt.Errorf("failed to convert int64") } return res, nil } func ToString(val interface{}) (string, error) { var res string switch v := val.(type) { case string: res = v default: return "", fmt.Errorf("failed to convert int64") } return res, nil } golang-iij-dpf-0.9.1/pkg/utils/convert_test.go000066400000000000000000000030601437707610400213070ustar00rootroot00000000000000package utils_test import ( "testing" "github.com/mimuret/golang-iij-dpf/pkg/utils" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) func TestUtils(t *testing.T) { RegisterFailHandler(Fail) RunSpecs(t, "utils Suite") } var _ = Describe("utils", func() { Context("ToInt64", func() { When("convertable types", func() { When("int", func() { It("return int64", func() { Expect(utils.ToInt64(int(10))).To(Equal(int64(10))) }) }) When("int8", func() { It("return int64", func() { Expect(utils.ToInt64(int8(10))).To(Equal(int64(10))) }) }) When("int16", func() { It("return int64", func() { Expect(utils.ToInt64(int16(10))).To(Equal(int64(10))) }) }) When("int32", func() { It("return int64", func() { Expect(utils.ToInt64(int32(10))).To(Equal(int64(10))) }) }) When("int64", func() { It("return int64", func() { Expect(utils.ToInt64(int64(10))).To(Equal(int64(10))) }) }) }) When("not convertable types", func() { When("uint", func() { It("return err", func() { _, err := utils.ToInt64(uint(10)) Expect(err).To(HaveOccurred()) }) }) }) }) Context("ToString", func() { When("convertable types", func() { When("string", func() { It("return string", func() { Expect(utils.ToString("hogehoge")).To(Equal("hogehoge")) }) }) }) When("not convertable types", func() { When("int", func() { It("return error", func() { _, err := utils.ToString(uint(10)) Expect(err).To(HaveOccurred()) }) }) }) }) })