From b3cc42fecdb0237a622f0b865193746d2f5a8cdd Mon Sep 17 00:00:00 2001 From: Matt Primrose Date: Mon, 13 May 2024 11:14:36 -0700 Subject: [PATCH] refactor: adds linting rules --- .github/.golangci.yml | 107 +++++----- .github/workflows/ci.yml | 103 ++++++++++ .github/workflows/codeql-analysis.yml | 10 +- .github/workflows/go.yml | 66 ------- .github/workflows/scorecard.yml | 2 +- .golangci.yml | 107 +++++----- README.md | 3 +- internal/message/base.go | 22 ++- internal/message/base_test.go | 102 +++++----- internal/message/types.go | 4 +- internal/message/wsman.go | 50 +++-- internal/message/wsman_test.go | 43 ++-- pkg/apf/processor.go | 107 ++++++++-- pkg/apf/processor_test.go | 95 ++++++++- pkg/apf/types.go | 186 ++++++++++-------- pkg/common/decoder.go | 19 +- pkg/wsman/amt/alarmclock/decoder.go | 10 +- pkg/wsman/amt/alarmclock/decoder_test.go | 1 + pkg/wsman/amt/alarmclock/marshal.go | 6 +- pkg/wsman/amt/alarmclock/service.go | 38 ++-- pkg/wsman/amt/alarmclock/service_test.go | 134 +++++++------ pkg/wsman/amt/alarmclock/types.go | 8 +- pkg/wsman/amt/auditlog/decoder.go | 76 +++---- pkg/wsman/amt/auditlog/marshal.go | 6 +- pkg/wsman/amt/auditlog/message.go | 23 ++- pkg/wsman/amt/auditlog/message_test.go | 90 +++++---- pkg/wsman/amt/auditlog/types.go | 6 +- pkg/wsman/amt/authorization/decoder.go | 49 ++--- pkg/wsman/amt/authorization/marshal.go | 6 +- pkg/wsman/amt/authorization/service.go | 115 +++++++---- pkg/wsman/amt/authorization/service_test.go | 84 ++++---- pkg/wsman/amt/authorization/types.go | 10 +- pkg/wsman/amt/boot/capabilities.go | 11 +- pkg/wsman/amt/boot/capabilities_test.go | 73 +++---- pkg/wsman/amt/boot/decoder.go | 19 +- pkg/wsman/amt/boot/marshal.go | 6 +- pkg/wsman/amt/boot/settingdata.go | 24 ++- pkg/wsman/amt/boot/settingdata_test.go | 82 ++++---- pkg/wsman/amt/boot/types.go | 8 +- pkg/wsman/amt/environmentdetection/decoder.go | 8 +- pkg/wsman/amt/environmentdetection/marshal.go | 6 +- .../amt/environmentdetection/settingdata.go | 16 +- .../environmentdetection/settingdata_test.go | 104 +++++----- pkg/wsman/amt/environmentdetection/types.go | 6 +- pkg/wsman/amt/ethernetport/decoder.go | 45 ++--- pkg/wsman/amt/ethernetport/marshal.go | 6 +- pkg/wsman/amt/ethernetport/settings.go | 20 +- pkg/wsman/amt/ethernetport/settings_test.go | 96 +++++---- pkg/wsman/amt/ethernetport/types.go | 22 +-- pkg/wsman/amt/general/decoder.go | 39 ++-- pkg/wsman/amt/general/marshal.go | 6 +- pkg/wsman/amt/general/settings.go | 36 ++-- pkg/wsman/amt/general/settings_test.go | 89 +++++---- pkg/wsman/amt/general/types.go | 13 +- pkg/wsman/amt/ieee8021x/credentialcontext.go | 6 +- .../amt/ieee8021x/credentialcontext_test.go | 59 +++--- pkg/wsman/amt/ieee8021x/decoder.go | 17 +- pkg/wsman/amt/ieee8021x/marshal.go | 6 +- pkg/wsman/amt/ieee8021x/profile.go | 16 +- pkg/wsman/amt/ieee8021x/profile_test.go | 96 ++++----- pkg/wsman/amt/ieee8021x/types.go | 6 +- pkg/wsman/amt/kerberos/decoder.go | 27 +-- pkg/wsman/amt/kerberos/marshal.go | 6 +- pkg/wsman/amt/kerberos/settingdata.go | 29 +-- pkg/wsman/amt/kerberos/settingdata_test.go | 108 +++++----- pkg/wsman/amt/kerberos/types.go | 14 +- pkg/wsman/amt/managementpresence/decoder.go | 5 +- pkg/wsman/amt/managementpresence/marshal.go | 6 +- pkg/wsman/amt/managementpresence/remotesap.go | 14 +- .../amt/managementpresence/remotesap_test.go | 95 +++++---- pkg/wsman/amt/managementpresence/types.go | 2 +- pkg/wsman/amt/messagelog/decoder.go | 87 ++++---- pkg/wsman/amt/messagelog/log.go | 37 ++-- pkg/wsman/amt/messagelog/log_test.go | 90 +++++---- pkg/wsman/amt/messagelog/marshal.go | 6 +- pkg/wsman/amt/messagelog/types.go | 6 +- pkg/wsman/amt/messages.go | 11 +- pkg/wsman/amt/messages_test.go | 32 ++- pkg/wsman/amt/methods/methods.go | 8 +- pkg/wsman/amt/methods/methods_test.go | 13 +- pkg/wsman/amt/mps/constants.go | 2 +- pkg/wsman/amt/mps/marshal.go | 6 +- pkg/wsman/amt/mps/types.go | 4 +- pkg/wsman/amt/mps/usernamepassword.go | 16 +- pkg/wsman/amt/mps/usernamepassword_test.go | 92 +++++---- pkg/wsman/amt/publickey/certificate.go | 23 ++- pkg/wsman/amt/publickey/certificate_test.go | 163 ++++++++------- pkg/wsman/amt/publickey/decoder.go | 45 ++--- pkg/wsman/amt/publickey/managementservice.go | 134 ++++++++----- .../amt/publickey/managementservice_test.go | 167 +++++++++------- pkg/wsman/amt/publickey/marshal.go | 6 +- pkg/wsman/amt/publickey/types.go | 8 +- pkg/wsman/amt/publicprivate/constants.go | 2 +- pkg/wsman/amt/publicprivate/keypair.go | 16 +- pkg/wsman/amt/publicprivate/keypair_test.go | 122 ++++++------ pkg/wsman/amt/publicprivate/marshal.go | 6 +- pkg/wsman/amt/publicprivate/types.go | 2 +- pkg/wsman/amt/redirection/decoder.go | 15 +- pkg/wsman/amt/redirection/marshal.go | 6 +- pkg/wsman/amt/redirection/service.go | 19 +- pkg/wsman/amt/redirection/service_test.go | 154 ++++++++------- pkg/wsman/amt/redirection/types.go | 8 +- pkg/wsman/amt/remoteaccess/decoder.go | 32 +-- pkg/wsman/amt/remoteaccess/marshal.go | 6 +- .../amt/remoteaccess/policyappliestomps.go | 13 +- .../remoteaccess/policyappliestomps_test.go | 109 +++++----- pkg/wsman/amt/remoteaccess/policyrule.go | 17 +- pkg/wsman/amt/remoteaccess/policyrule_test.go | 102 +++++----- pkg/wsman/amt/remoteaccess/service.go | 46 +++-- pkg/wsman/amt/remoteaccess/service_test.go | 129 ++++++------ pkg/wsman/amt/remoteaccess/types.go | 15 +- .../amt/setupandconfiguration/decoder.go | 51 ++--- .../amt/setupandconfiguration/marshal.go | 6 +- .../amt/setupandconfiguration/service.go | 147 ++++++++------ .../amt/setupandconfiguration/service_test.go | 147 ++++++++------ pkg/wsman/amt/setupandconfiguration/types.go | 16 +- pkg/wsman/amt/timesynchronization/decoder.go | 37 ++-- pkg/wsman/amt/timesynchronization/marshal.go | 6 +- pkg/wsman/amt/timesynchronization/service.go | 23 ++- .../amt/timesynchronization/service_test.go | 110 ++++++----- pkg/wsman/amt/timesynchronization/types.go | 8 +- pkg/wsman/amt/tls/constants.go | 6 +- pkg/wsman/amt/tls/credentialcontext.go | 20 +- pkg/wsman/amt/tls/credentialcontext_test.go | 37 ++-- pkg/wsman/amt/tls/marshal.go | 6 +- .../amt/tls/protocolendpointcollection.go | 11 +- .../tls/protocolendpointcollection_test.go | 86 ++++---- pkg/wsman/amt/tls/settingdata.go | 14 +- pkg/wsman/amt/tls/settingdata_test.go | 109 +++++----- pkg/wsman/amt/tls/types.go | 6 +- .../amt/userinitiatedconnection/decoder.go | 17 +- .../amt/userinitiatedconnection/marshal.go | 6 +- .../amt/userinitiatedconnection/service.go | 15 +- .../userinitiatedconnection/service_test.go | 120 +++++------ .../amt/userinitiatedconnection/types.go | 4 +- .../amt/wifiportconfiguration/decoder.go | 46 +++-- .../amt/wifiportconfiguration/marshal.go | 6 +- .../amt/wifiportconfiguration/service.go | 82 +++++--- .../amt/wifiportconfiguration/service_test.go | 57 +++--- pkg/wsman/amt/wifiportconfiguration/types.go | 30 +-- pkg/wsman/cim/bios/decoder.go | 24 ++- pkg/wsman/cim/bios/element.go | 13 +- pkg/wsman/cim/bios/element_test.go | 85 ++++---- pkg/wsman/cim/bios/marshal.go | 6 +- pkg/wsman/cim/bios/types.go | 2 +- pkg/wsman/cim/boot/configsetting.go | 18 +- pkg/wsman/cim/boot/configsetting_test.go | 105 +++++----- pkg/wsman/cim/boot/decoder.go | 69 +++---- pkg/wsman/cim/boot/marshal.go | 6 +- pkg/wsman/cim/boot/service.go | 42 ++-- pkg/wsman/cim/boot/service_test.go | 95 ++++----- pkg/wsman/cim/boot/sourcesetting.go | 12 +- pkg/wsman/cim/boot/sourcesetting_test.go | 93 ++++----- pkg/wsman/cim/boot/types.go | 11 +- pkg/wsman/cim/card/card.go | 14 +- pkg/wsman/cim/card/card_test.go | 74 +++---- pkg/wsman/cim/card/decoder.go | 19 +- pkg/wsman/cim/card/marshal.go | 6 +- pkg/wsman/cim/card/types.go | 9 +- pkg/wsman/cim/chassis/chassis.go | 14 +- pkg/wsman/cim/chassis/chassis_test.go | 93 +++++---- pkg/wsman/cim/chassis/decoder.go | 24 ++- pkg/wsman/cim/chassis/marshal.go | 6 +- pkg/wsman/cim/chassis/types.go | 3 +- pkg/wsman/cim/chip/chip.go | 14 +- pkg/wsman/cim/chip/chip_test.go | 78 ++++---- pkg/wsman/cim/chip/decoder.go | 7 +- pkg/wsman/cim/chip/marshal.go | 6 +- pkg/wsman/cim/chip/types.go | 5 +- pkg/wsman/cim/computer/constants.go | 2 +- pkg/wsman/cim/computer/marshal.go | 6 +- pkg/wsman/cim/computer/systempackage.go | 14 +- pkg/wsman/cim/computer/systempackage_test.go | 77 ++++---- pkg/wsman/cim/computer/types.go | 5 +- pkg/wsman/cim/concrete/constants.go | 2 +- pkg/wsman/cim/concrete/dependency.go | 12 +- pkg/wsman/cim/concrete/dependency_test.go | 62 +++--- pkg/wsman/cim/concrete/marshal.go | 6 +- pkg/wsman/cim/concrete/types.go | 5 +- pkg/wsman/cim/credential/constants.go | 2 +- pkg/wsman/cim/credential/context.go | 12 +- pkg/wsman/cim/credential/context_test.go | 56 +++--- pkg/wsman/cim/credential/marshal.go | 6 +- pkg/wsman/cim/credential/types.go | 5 +- pkg/wsman/cim/ieee8021x/constants.go | 2 +- pkg/wsman/cim/ieee8021x/marshal.go | 6 +- pkg/wsman/cim/ieee8021x/settings.go | 10 +- pkg/wsman/cim/ieee8021x/settings_test.go | 59 +++--- pkg/wsman/cim/ieee8021x/types.go | 5 +- pkg/wsman/cim/kvm/decoder.go | 45 +++-- pkg/wsman/cim/kvm/marshal.go | 6 +- pkg/wsman/cim/kvm/redirectionsap.go | 17 +- pkg/wsman/cim/kvm/redirectionsap_test.go | 87 ++++---- pkg/wsman/cim/kvm/types.go | 7 +- pkg/wsman/cim/mediaaccess/decoder.go | 47 +++-- pkg/wsman/cim/mediaaccess/device.go | 10 +- pkg/wsman/cim/mediaaccess/device_test.go | 67 ++++--- pkg/wsman/cim/mediaaccess/marshal.go | 6 +- pkg/wsman/cim/mediaaccess/types.go | 5 +- pkg/wsman/cim/messages.go | 8 +- pkg/wsman/cim/messages_test.go | 23 +++ pkg/wsman/cim/methods/methods.go | 2 +- pkg/wsman/cim/methods/methods_test.go | 13 +- pkg/wsman/cim/models/constants.go | 84 +++++--- pkg/wsman/cim/models/methods.go | 8 +- pkg/wsman/cim/models/types.go | 96 ++++----- pkg/wsman/cim/physical/decoder.go | 27 +-- pkg/wsman/cim/physical/decoder_test.go | 4 +- pkg/wsman/cim/physical/marshal.go | 6 +- pkg/wsman/cim/physical/memory.go | 10 +- pkg/wsman/cim/physical/memory_test.go | 58 +++--- pkg/wsman/cim/physical/package.go | 10 +- pkg/wsman/cim/physical/package_test.go | 60 +++--- pkg/wsman/cim/physical/types.go | 8 +- pkg/wsman/cim/power/decoder.go | 58 +++--- pkg/wsman/cim/power/managementservice.go | 16 +- pkg/wsman/cim/power/managementservice_test.go | 86 ++++---- pkg/wsman/cim/power/marshal.go | 6 +- pkg/wsman/cim/power/types.go | 5 +- pkg/wsman/cim/processor/decoder.go | 47 +++-- pkg/wsman/cim/processor/marshal.go | 6 +- pkg/wsman/cim/processor/processor.go | 14 +- pkg/wsman/cim/processor/processor_test.go | 90 +++++---- pkg/wsman/cim/processor/types.go | 3 +- pkg/wsman/cim/service/availabletoelement.go | 10 +- .../cim/service/availabletoelement_test.go | 31 +-- pkg/wsman/cim/service/decoder.go | 19 +- pkg/wsman/cim/service/marshal.go | 6 +- pkg/wsman/cim/service/types.go | 5 +- pkg/wsman/cim/software/constants.go | 2 +- pkg/wsman/cim/software/identity.go | 30 +-- pkg/wsman/cim/software/identity_test.go | 78 ++++---- pkg/wsman/cim/software/marshal.go | 6 +- pkg/wsman/cim/software/types.go | 5 +- pkg/wsman/cim/system/constants.go | 2 +- pkg/wsman/cim/system/marshal.go | 6 +- pkg/wsman/cim/system/packaging.go | 19 +- pkg/wsman/cim/system/packaging_test.go | 60 +++--- pkg/wsman/cim/system/types.go | 2 +- pkg/wsman/cim/wifi/decoder.go | 82 ++++---- pkg/wsman/cim/wifi/decoder_test.go | 6 +- pkg/wsman/cim/wifi/endpointsettings.go | 12 +- pkg/wsman/cim/wifi/endpointsettings_test.go | 88 +++++---- pkg/wsman/cim/wifi/marshal.go | 6 +- pkg/wsman/cim/wifi/port.go | 38 ++-- pkg/wsman/cim/wifi/port_test.go | 90 +++++---- pkg/wsman/cim/wifi/types.go | 7 +- pkg/wsman/client/hash.go | 44 ++++- pkg/wsman/client/hash_test.go | 12 +- pkg/wsman/client/relay.go | 118 +++++++---- pkg/wsman/client/relay_test.go | 121 ++++++++---- pkg/wsman/client/types.go | 2 +- pkg/wsman/client/wsman.go | 109 ++++++---- pkg/wsman/client/wsman_tcp.go | 32 ++- pkg/wsman/client/wsman_test.go | 91 ++++++--- pkg/wsman/common/constants.go | 50 +++-- pkg/wsman/ips/alarmclock/constants.go | 2 +- pkg/wsman/ips/alarmclock/marshal.go | 6 +- pkg/wsman/ips/alarmclock/occurrence.go | 21 +- pkg/wsman/ips/alarmclock/occurrence_test.go | 84 ++++---- pkg/wsman/ips/alarmclock/types.go | 2 +- pkg/wsman/ips/hostbasedsetup/decoder.go | 67 ++++--- pkg/wsman/ips/hostbasedsetup/decoder_test.go | 2 + pkg/wsman/ips/hostbasedsetup/marshal.go | 6 +- pkg/wsman/ips/hostbasedsetup/service.go | 123 ++++++++---- pkg/wsman/ips/hostbasedsetup/service_test.go | 150 +++++++------- pkg/wsman/ips/hostbasedsetup/types.go | 28 +-- pkg/wsman/ips/ieee8021x/credentialcontext.go | 33 ++-- .../ips/ieee8021x/credentialcontext_test.go | 28 +-- pkg/wsman/ips/ieee8021x/decoder.go | 21 +- pkg/wsman/ips/ieee8021x/marshal.go | 6 +- pkg/wsman/ips/ieee8021x/settings.go | 51 +++-- pkg/wsman/ips/ieee8021x/settings_test.go | 86 ++++---- pkg/wsman/ips/ieee8021x/types.go | 6 +- pkg/wsman/ips/messages.go | 8 +- pkg/wsman/ips/messages_test.go | 5 + pkg/wsman/ips/methods/methods.go | 2 +- pkg/wsman/ips/methods/methods_test.go | 13 +- pkg/wsman/ips/optin/decoder.go | 33 ++-- pkg/wsman/ips/optin/marshal.go | 6 +- pkg/wsman/ips/optin/service.go | 83 +++++--- pkg/wsman/ips/optin/service_test.go | 143 ++++++++------ pkg/wsman/ips/optin/types.go | 26 +-- pkg/wsman/messages.go | 6 +- pkg/wsman/messages_test.go | 5 + pkg/wsman/types.go | 2 +- pkg/wsman/wsmantesting/clientMock.go | 13 +- pkg/wsman/wsmantesting/constants.go | 47 +++-- 288 files changed, 6132 insertions(+), 4462 deletions(-) create mode 100644 .github/workflows/ci.yml delete mode 100644 .github/workflows/go.yml diff --git a/.github/.golangci.yml b/.github/.golangci.yml index ada44107..d61dc529 100644 --- a/.github/.golangci.yml +++ b/.github/.golangci.yml @@ -1,19 +1,17 @@ linters-settings: gci: - local-prefixes: github.com/open-amt-cloud-toolkit/console - dupl: - threshold: 300 + local-prefixes: github.com/open-amt-cloud-toolkit/go-wsman-messages errorlint: errorf: true errcheck: check-type-assertions: true - check-blank: true + check-blank: false exhaustive: check-generated: false default-signifies-exhaustive: false funlen: - lines: 65 - statements: 40 + lines: 100 + statements: 45 gocognit: min-complexity: 15 gocyclo: @@ -35,14 +33,12 @@ linters-settings: gofumpt: extra-rules: true gomnd: - settings: - mnd: - checks: - - argument - - case - - condition - - operation - - return + checks: + - argument + - case + - condition + - operation + - return govet: check-shadowing: true misspell: @@ -56,69 +52,64 @@ linters-settings: linters: disable-all: true enable: - # - errcheck - - gosimple - # - govet - - ineffassign - - unused - # - asciicheck + - asciicheck # - bodyclose # - cyclop # - deadcode - # # - depguard - # - dogsled + # - depguard + - dogsled # - dupl - # - durationcheck - # - errcheck - # - errorlint - # - exhaustive - # - exportloopref - # - forbidigo + - durationcheck + - errcheck + - errorlint + - exhaustive + - exportloopref + - forbidigo # - funlen - # - gci - # # - gochecknoglobals - # - gochecknoinits + - gci + # - gochecknoglobals + - gochecknoinits # - gocognit - # - goconst + - goconst # - gocritic # - gocyclo - # - godot + - godot # - godox # - goerr113 - # - gofmt - # - gofumpt - # - goimports + - gofmt + - gofumpt + - goimports # - gomnd - # - gomodguard - # - goprintffuncname + - gomodguard + - goprintffuncname # - gosec - # - gosimple + - gosimple # - govet - # - ineffassign - # - makezero + - ineffassign + - makezero # - misspell - # - nakedret + - nakedret # - nestif - # - nlreturn + - nlreturn # - noctx - # - nolintlint + - nolintlint # - paralleltest - # - predeclared + - predeclared # - revive - # - rowserrcheck - # - sqlclosecheck - # - staticcheck + - rowserrcheck + - sqlclosecheck + - staticcheck # - structcheck # - stylecheck - # - tparallel - # - thelper - # - typecheck - # - unconvert + - tparallel + - thelper + - typecheck + - unconvert # - unparam - # - unused + - unused # - varcheck - # - wsl - # - whitespace + - wsl + - whitespace # disable: # - exhaustivestruct @@ -141,7 +132,5 @@ issues: linters: - funlen - goerr113 - -run: - skip-dirs: - - docs + exclude-dirs: + - docs \ No newline at end of file diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 00000000..26096059 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,103 @@ +name: CI +on: + push: + branches: [ main ] + pull_request: +permissions: + contents: read # for actions/checkout to fetch code + +jobs: + formatting: + name: runner / formatting + runs-on: ubuntu-latest + steps: + - name: Check out code into the Go module directory + uses: actions/checkout@44c2b7a8a4ea60a981eaca3cf939b5f4305c123b + - name: Format + run: if [ "$(gofmt -s -l . | wc -l)" -gt 0 ]; then exit 1; fi + - name: Run go vet + run: go vet ./... + + golangci-lint: + name: runner / golangci-lint + runs-on: ubuntu-latest + steps: + - name: Check out code into the Go module directory + uses: actions/checkout@44c2b7a8a4ea60a981eaca3cf939b5f4305c123b + - name: golangci-lint + uses: reviewdog/action-golangci-lint@v2 + with: + fail_on_error: true + golangci_lint_flags: "--config=.github/.golangci.yml ./..." + + yamllint: + name: runner / yamllint + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@44c2b7a8a4ea60a981eaca3cf939b5f4305c123b + - uses: reviewdog/action-yamllint@v1 + with: + fail_on_error: true + reporter: github-pr-review + yamllint_flags: '-d "{extends: default, rules: {truthy: disable}}" .' + + dotenv-linter: + name: runner / dotenv-linter + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@44c2b7a8a4ea60a981eaca3cf939b5f4305c123b + - uses: dotenv-linter/action-dotenv-linter@v2 + with: + reporter: github-pr-review + + check-dependencies: + name: runner / check-dependencies + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@44c2b7a8a4ea60a981eaca3cf939b5f4305c123b + - uses: actions/setup-go@cdcb36043654635271a94b9a6d1392de5bb323a7 + - name: WriteGoList + run: go list -json -m all > go.list + - name: Nancy + uses: sonatype-nexus-community/nancy-github-action@main + continue-on-error: true + - name: "Dependency Review" + uses: actions/dependency-review-action@0c155c5e8556a497adf53f2c18edabf945ed8e70 # v4.3.2 + + tests: + name: runner / build and tests + runs-on: ubuntu-latest + strategy: + matrix: + go-version: [1.20.x, 1.21.x, 1.22.x] + os: [windows-2019, windows-2022, ubuntu-22.04, ubuntu-20.04] + steps: + - uses: actions/checkout@44c2b7a8a4ea60a981eaca3cf939b5f4305c123b + - uses: actions/setup-go@cdcb36043654635271a94b9a6d1392de5bb323a7 + with: + go-version: ${{ matrix.go-version }} + - name: Checkout code + uses: actions/checkout@44c2b7a8a4ea60a981eaca3cf939b5f4305c123b # v4.1.5 + - name: Install Test Converter and run tests + run: | + export GOPATH="$HOME/go/" + export PATH=$PATH:$GOPATH/bin + go install github.com/jstemmer/go-junit-report/v2@latest + go test -covermode=atomic -coverprofile=coverage.out -race -v ./... > test_output.txt 2>&1 || true + cat test_output.txt + cat test_output.txt | go-junit-report -set-exit-code > junit-${{matrix.os}}-${{matrix.go-version}}-${{github.run_attempt}}.xml + if grep -q "FAIL" test_output.txt; then exit 1; fi + - name: Upload Coverage Results + uses: codecov/codecov-action@5ecb98a3c6b747ed38dc09f787459979aebb39be # v4.3.1 + with: + token: ${{ secrets.CODECOV_TOKEN }} + - name: GitHub Upload Release Artifacts + uses: actions/upload-artifact@65462800fd760344b1a7b4382951275a0abb4808 # v4.3.3 + with: + name: JUnit Results ${{matrix.os}}-${{matrix.go-version}}-${{github.run_attempt}} + path: junit-${{matrix.os}}-${{matrix.go-version}}-${{github.run_attempt}}.xml + # - name: Integration tests + # run: "docker-compose up \ + # --build \ + # --abort-on-container-exit \ + # --exit-code-from integration" \ No newline at end of file diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml index 56602691..8754c35f 100644 --- a/.github/workflows/codeql-analysis.yml +++ b/.github/workflows/codeql-analysis.yml @@ -17,10 +17,10 @@ on: types: - created push: - branches: [ main, v2.0 ] + branches: [ main ] pull_request: # The branches below must be a subset of the branches above - branches: [ main, v2.0 ] + branches: [ main ] schedule: - cron: '26 23 * * 0' @@ -55,7 +55,7 @@ jobs: # Initializes the CodeQL tools for scanning. - name: Initialize CodeQL - uses: github/codeql-action/init@d39d31e687223d841ef683f52467bd88e9b21c14 # v3.25.3 + uses: github/codeql-action/init@ccf74c947955fd1cf117aef6a0e4e66191ef6f61 # v3.25.4 with: languages: ${{ matrix.language }} # If you wish to specify custom queries, you can do so here or in a config file. @@ -66,7 +66,7 @@ jobs: # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). # If this step fails, then you should remove it and run the build manually (see below) - name: Autobuild - uses: github/codeql-action/autobuild@d39d31e687223d841ef683f52467bd88e9b21c14 # v3.25.3 + uses: github/codeql-action/autobuild@ccf74c947955fd1cf117aef6a0e4e66191ef6f61 # v3.25.4 # ℹ️ Command-line programs to run using the OS shell. # 📚 https://git.io/JvXDl @@ -80,7 +80,7 @@ jobs: # make release - name: Perform CodeQL Analysis - uses: github/codeql-action/analyze@d39d31e687223d841ef683f52467bd88e9b21c14 # v3.25.3 + uses: github/codeql-action/analyze@ccf74c947955fd1cf117aef6a0e4e66191ef6f61 # v3.25.4 - name: Generate Security Report uses: rsdmike/github-security-report-action@a149b24539044c92786ec39af8ba38c93496495d # v3.0.4 continue-on-error: true diff --git a/.github/workflows/go.yml b/.github/workflows/go.yml deleted file mode 100644 index c63b2533..00000000 --- a/.github/workflows/go.yml +++ /dev/null @@ -1,66 +0,0 @@ -#********************************************************************* -# Copyright (c) Intel Corporation 2020 -# SPDX-License-Identifier: Apache-2.0 -#*********************************************************************/ - -# This workflow will do a clean install of go dependencies, build the source code and run tests across different versions of go - -name: Go CI - -on: - push: - branches: [ main, v2.0] - pull_request: - branches: [ main, v2.0] - workflow_dispatch: -permissions: - contents: read - -jobs: - build: - permissions: - contents: read # for actions/checkout to fetch code - pull-requests: read # for golangci/golangci-lint-action to fetch pull requests - runs-on: ubuntu-latest - - strategy: - matrix: - go-version: [1.20.x, 1.21.x, 1.22.x] - - steps: - - name: Harden Runner - uses: step-security/harden-runner@a4aa98b93cab29d9b1101a6143fb8bce00e2eac4 # v2.7.1 - with: - egress-policy: audit - - - name: Install Go - uses: actions/setup-go@cdcb36043654635271a94b9a6d1392de5bb323a7 # v5.0.1 - with: - go-version: ${{ matrix.go-version }} - - name: Checkout code - uses: actions/checkout@44c2b7a8a4ea60a981eaca3cf939b5f4305c123b # v4.1.5 - - name: Install Test Converter and run tests - run: | - export GOPATH="$HOME/go/" - export PATH=$PATH:$GOPATH/bin - go install github.com/jstemmer/go-junit-report/v2@latest - go test -covermode=atomic -coverprofile=coverage.out -race -v ./... > test_output.txt 2>&1 || true - cat test_output.txt - cat test_output.txt | go-junit-report -set-exit-code > junit.xml - if grep -q "FAIL" test_output.txt; then exit 1; fi - - name: Format - run: if [ "$(gofmt -s -l . | wc -l)" -gt 0 ]; then exit 1; fi - - name: Run go vet - run: go vet ./... - - name: golangci-lint - uses: reviewdog/action-golangci-lint@v2 - with: - fail_on_error: true - golangci_lint_flags: "--config=.github/.golangci.yml ./..." - - uses: codecov/codecov-action@5ecb98a3c6b747ed38dc09f787459979aebb39be # v4.3.1 - name: Upload Coverage Results - - name: GitHub Upload Release Artifacts - uses: actions/upload-artifact@65462800fd760344b1a7b4382951275a0abb4808 # v4.3.3 - with: - name: go-wsman-unit - path: go-wsman.xml \ No newline at end of file diff --git a/.github/workflows/scorecard.yml b/.github/workflows/scorecard.yml index a61ce406..98103119 100644 --- a/.github/workflows/scorecard.yml +++ b/.github/workflows/scorecard.yml @@ -72,6 +72,6 @@ jobs: # Upload the results to GitHub's code scanning dashboard. - name: "Upload to code-scanning" - uses: github/codeql-action/upload-sarif@d39d31e687223d841ef683f52467bd88e9b21c14 # v3.25.3 + uses: github/codeql-action/upload-sarif@ccf74c947955fd1cf117aef6a0e4e66191ef6f61 # v3.25.4 with: sarif_file: results.sarif diff --git a/.golangci.yml b/.golangci.yml index ada44107..d61dc529 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -1,19 +1,17 @@ linters-settings: gci: - local-prefixes: github.com/open-amt-cloud-toolkit/console - dupl: - threshold: 300 + local-prefixes: github.com/open-amt-cloud-toolkit/go-wsman-messages errorlint: errorf: true errcheck: check-type-assertions: true - check-blank: true + check-blank: false exhaustive: check-generated: false default-signifies-exhaustive: false funlen: - lines: 65 - statements: 40 + lines: 100 + statements: 45 gocognit: min-complexity: 15 gocyclo: @@ -35,14 +33,12 @@ linters-settings: gofumpt: extra-rules: true gomnd: - settings: - mnd: - checks: - - argument - - case - - condition - - operation - - return + checks: + - argument + - case + - condition + - operation + - return govet: check-shadowing: true misspell: @@ -56,69 +52,64 @@ linters-settings: linters: disable-all: true enable: - # - errcheck - - gosimple - # - govet - - ineffassign - - unused - # - asciicheck + - asciicheck # - bodyclose # - cyclop # - deadcode - # # - depguard - # - dogsled + # - depguard + - dogsled # - dupl - # - durationcheck - # - errcheck - # - errorlint - # - exhaustive - # - exportloopref - # - forbidigo + - durationcheck + - errcheck + - errorlint + - exhaustive + - exportloopref + - forbidigo # - funlen - # - gci - # # - gochecknoglobals - # - gochecknoinits + - gci + # - gochecknoglobals + - gochecknoinits # - gocognit - # - goconst + - goconst # - gocritic # - gocyclo - # - godot + - godot # - godox # - goerr113 - # - gofmt - # - gofumpt - # - goimports + - gofmt + - gofumpt + - goimports # - gomnd - # - gomodguard - # - goprintffuncname + - gomodguard + - goprintffuncname # - gosec - # - gosimple + - gosimple # - govet - # - ineffassign - # - makezero + - ineffassign + - makezero # - misspell - # - nakedret + - nakedret # - nestif - # - nlreturn + - nlreturn # - noctx - # - nolintlint + - nolintlint # - paralleltest - # - predeclared + - predeclared # - revive - # - rowserrcheck - # - sqlclosecheck - # - staticcheck + - rowserrcheck + - sqlclosecheck + - staticcheck # - structcheck # - stylecheck - # - tparallel - # - thelper - # - typecheck - # - unconvert + - tparallel + - thelper + - typecheck + - unconvert # - unparam - # - unused + - unused # - varcheck - # - wsl - # - whitespace + - wsl + - whitespace # disable: # - exhaustivestruct @@ -141,7 +132,5 @@ issues: linters: - funlen - goerr113 - -run: - skip-dirs: - - docs + exclude-dirs: + - docs \ No newline at end of file diff --git a/README.md b/README.md index 7617b210..049ebd24 100644 --- a/README.md +++ b/README.md @@ -47,4 +47,5 @@ if err != nil { - Ensure code is formatted correctly with `gofmt -s -w ./` - Ensure all unit tests pass with `go test ./...` -- Ensure code has been linted with `docker run --rm -v ${pwd}:/app -w /app golangci/golangci-lint:v1.52.2 golangci-lint run -v` \ No newline at end of file +- Ensure code has been gci'd with `gci.exe write --skip-generated -s standard -s default .` +- Ensure code has been linted with `docker run --rm -v ${pwd}:/app -w /app golangci/golangci-lint:latest golangci-lint run -v` \ No newline at end of file diff --git a/internal/message/base.go b/internal/message/base.go index 46421ab0..db4e8454 100644 --- a/internal/message/base.go +++ b/internal/message/base.go @@ -26,16 +26,17 @@ func NewBaseWithClient(wsmanMessageCreator *WSManMessageCreator, className strin } } -// Enumerate returns an enumeration context which is used in a subsequent Pull call +// Enumerate returns an enumeration context which is used in a subsequent Pull call. func (b *Base) Enumerate() string { header := b.WSManMessageCreator.CreateHeader(BaseActionsEnumerate, b.className, nil, "", "") return b.WSManMessageCreator.CreateXML(header, EnumerateBody) } -// Get retrieves the representation of the instance +// Get retrieves the representation of the instance. func (b *Base) Get(selector *Selector) string { header := b.WSManMessageCreator.CreateHeader(BaseActionsGet, b.className, selector, "", "") + return b.WSManMessageCreator.CreateXML(header, GetBody) } @@ -43,42 +44,49 @@ func (b *Base) Get(selector *Selector) string { func (b *Base) Pull(enumerationContext string) string { header := b.WSManMessageCreator.CreateHeader(BaseActionsPull, b.className, nil, "", "") body := createCommonBodyPull(enumerationContext, 0, 0) + return b.WSManMessageCreator.CreateXML(header, body) } -// Delete removes a the specified instance +// Delete removes a the specified instance. func (b *Base) Delete(selector Selector) string { header := b.WSManMessageCreator.CreateHeader(BaseActionsDelete, b.className, &selector, "", "") + return b.WSManMessageCreator.CreateXML(header, DeleteBody) } -// Put will change properties of the selected instance +// Put will change properties of the selected instance. func (b *Base) Put(data interface{}, useHeaderSelector bool, customSelector *Selector) string { if customSelector == nil { customSelector = &Selector{Name: "InstanceID", Value: fmt.Sprintf("%v", data)} } + var header string + if useHeaderSelector { header = b.WSManMessageCreator.CreateHeader(BaseActionsPut, b.className, customSelector, "", "") } else { header = b.WSManMessageCreator.CreateHeader(BaseActionsPut, b.className, nil, "", "") } + body := b.WSManMessageCreator.createCommonBodyCreateOrPut(b.className, data) + return b.WSManMessageCreator.CreateXML(header, body) } -// Creates a new instance of this class +// Creates a new instance of this class. func (b *Base) Create(data interface{}, selector *Selector) string { header := b.WSManMessageCreator.CreateHeader(BaseActionsCreate, b.className, selector, "", "") body := b.WSManMessageCreator.createCommonBodyCreateOrPut(b.className, data) + return b.WSManMessageCreator.CreateXML(header, body) } // RequestStateChange requests that the state of the element be changed to the value specified in the RequestedState parameter . . . func (b *Base) RequestStateChange(actionName string, requestedState int) string { - header := b.WSManMessageCreator.CreateHeader(actionName, b.className, nil, "", "") body := createCommonBodyRequestStateChange(fmt.Sprintf("%s%s", b.WSManMessageCreator.ResourceURIBase, b.className), requestedState) + return b.WSManMessageCreator.CreateXML(header, body) } @@ -86,10 +94,12 @@ func (b *Base) Execute(message *client.Message) error { if b.client != nil { xmlResponse, err := b.client.Post(message.XMLInput) message.XMLOutput = string(xmlResponse) + if err != nil { return err } } + // potentially could return an error that says that client doesn't exist return nil } diff --git a/internal/message/base_test.go b/internal/message/base_test.go index 27564ba9..cf3b3822 100644 --- a/internal/message/base_test.go +++ b/internal/message/base_test.go @@ -18,8 +18,15 @@ type MockClient struct { Err error } +const ( + TestData = "test-data" + TestAction = "test-action" + TestContext = "test-context" +) + func (c *MockClient) Post(msg string) ([]byte, error) { - var response []byte = nil + var response []byte + return response, c.Err } func (c *MockClient) Send(data []byte) error { return nil } @@ -30,8 +37,9 @@ func (c *MockClient) Connect() error { return nil } func TestBaseWithClient(t *testing.T) { mockWsmanMessageCreator := NewWSManMessageCreator("test-uri") mockClient := MockClient{} - MessageId := 0 + MessageID := 0 base := NewBaseWithClient(mockWsmanMessageCreator, "TestClass", &mockClient) + t.Run("Execute with no error", func(t *testing.T) { mockClient.Err = nil message := client.Message{ @@ -49,68 +57,68 @@ func TestBaseWithClient(t *testing.T) { assert.Error(t, err) }) t.Run("Enumerate", func(t *testing.T) { - expected := fmt.Sprintf("
http://schemas.xmlsoap.org/ws/2004/09/enumeration/Enumerate/wsmantest-uriTestClass%dhttp://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymousPT60S
", MessageId) - MessageId++ + expected := fmt.Sprintf("
http://schemas.xmlsoap.org/ws/2004/09/enumeration/Enumerate/wsmantest-uriTestClass%dhttp://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymousPT60S
", MessageID) + MessageID++ actual := base.Enumerate() assert.Equal(t, expected, actual) }) t.Run("Get", func(t *testing.T) { selector := &Selector{Name: "Key", Value: "Value"} - expected := fmt.Sprintf("
http://schemas.xmlsoap.org/ws/2004/09/transfer/Get/wsmantest-uriTestClass%dhttp://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymousPT60SValue
", MessageId) - MessageId++ + expected := fmt.Sprintf("
http://schemas.xmlsoap.org/ws/2004/09/transfer/Get/wsmantest-uriTestClass%dhttp://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymousPT60SValue
", MessageID) + MessageID++ actual := base.Get(selector) assert.Equal(t, expected, actual) }) t.Run("Pull", func(t *testing.T) { - enumerationContext := "test-context" - expected := fmt.Sprintf("
http://schemas.xmlsoap.org/ws/2004/09/enumeration/Pull/wsmantest-uriTestClass%dhttp://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymousPT60S
test-context99999999
", MessageId) - MessageId++ + enumerationContext := TestContext + expected := fmt.Sprintf("
http://schemas.xmlsoap.org/ws/2004/09/enumeration/Pull/wsmantest-uriTestClass%dhttp://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymousPT60S
test-context99999999
", MessageID) + MessageID++ actual := base.Pull(enumerationContext) assert.Equal(t, expected, actual) }) t.Run("Delete", func(t *testing.T) { - expected := fmt.Sprintf("
http://schemas.xmlsoap.org/ws/2004/09/transfer/Delete/wsmantest-uriTestClass%dhttp://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymousPT60SValue
", MessageId) - MessageId++ + expected := fmt.Sprintf("
http://schemas.xmlsoap.org/ws/2004/09/transfer/Delete/wsmantest-uriTestClass%dhttp://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymousPT60SValue
", MessageID) + MessageID++ actual := base.Delete(Selector{Name: "Name", Value: "Value"}) assert.Equal(t, expected, actual) }) t.Run("Put", func(t *testing.T) { - data := "test-data" + data := TestData customSelector := &Selector{Name: "Key", Value: "Value"} - expected := fmt.Sprintf("
http://schemas.xmlsoap.org/ws/2004/09/transfer/Put/wsmantest-uriTestClass%dhttp://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymousPT60SValue
test-data
", MessageId) - MessageId++ + expected := fmt.Sprintf("
http://schemas.xmlsoap.org/ws/2004/09/transfer/Put/wsmantest-uriTestClass%dhttp://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymousPT60SValue
test-data
", MessageID) + MessageID++ actual := base.Put(data, true, customSelector) assert.Equal(t, expected, actual) - expectedDefaultSelector := fmt.Sprintf("
http://schemas.xmlsoap.org/ws/2004/09/transfer/Put/wsmantest-uriTestClass%dhttp://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymousPT60Stest-data
test-data
", MessageId) - MessageId++ + expectedDefaultSelector := fmt.Sprintf("
http://schemas.xmlsoap.org/ws/2004/09/transfer/Put/wsmantest-uriTestClass%dhttp://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymousPT60Stest-data
test-data
", MessageID) + MessageID++ actualDefaultSelector := base.Put(data, true, nil) assert.Equal(t, expectedDefaultSelector, actualDefaultSelector) - expectedNoSelector := fmt.Sprintf("
http://schemas.xmlsoap.org/ws/2004/09/transfer/Put/wsmantest-uriTestClass%dhttp://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymousPT60S
test-data
", MessageId) - MessageId++ + expectedNoSelector := fmt.Sprintf("
http://schemas.xmlsoap.org/ws/2004/09/transfer/Put/wsmantest-uriTestClass%dhttp://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymousPT60S
test-data
", MessageID) + MessageID++ actualNoSelector := base.Put(data, false, customSelector) assert.Equal(t, expectedNoSelector, actualNoSelector) }) t.Run("Create", func(t *testing.T) { - data := "test-data" + data := TestData selector := &Selector{Name: "Key", Value: "Value"} - expected := fmt.Sprintf("
http://schemas.xmlsoap.org/ws/2004/09/transfer/Create/wsmantest-uriTestClass%dhttp://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymousPT60SValue
test-data
", MessageId) - MessageId++ + expected := fmt.Sprintf("
http://schemas.xmlsoap.org/ws/2004/09/transfer/Create/wsmantest-uriTestClass%dhttp://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymousPT60SValue
test-data
", MessageID) + MessageID++ actual := base.Create(data, selector) assert.Equal(t, expected, actual) }) t.Run("RequestStateChange", func(t *testing.T) { - actionName := "test-action" + actionName := TestAction requestedState := 2 - expected := fmt.Sprintf("
test-action/wsmantest-uriTestClass%dhttp://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymousPT60S
2
", MessageId) - MessageId++ + expected := fmt.Sprintf("
test-action/wsmantest-uriTestClass%dhttp://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymousPT60S
2
", MessageID) + MessageID++ actual := base.RequestStateChange(actionName, requestedState) assert.Equal(t, expected, actual) }) @@ -119,71 +127,71 @@ func TestBaseWithClient(t *testing.T) { func TestBase(t *testing.T) { mockWsmanMessageCreator := NewWSManMessageCreator("test-uri") base := NewBase(mockWsmanMessageCreator, "TestClass") - MessageId := 0 + MessageID := 0 t.Run("Enumerate", func(t *testing.T) { - expected := fmt.Sprintf("
http://schemas.xmlsoap.org/ws/2004/09/enumeration/Enumerate/wsmantest-uriTestClass%dhttp://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymousPT60S
", MessageId) - MessageId++ + expected := fmt.Sprintf("
http://schemas.xmlsoap.org/ws/2004/09/enumeration/Enumerate/wsmantest-uriTestClass%dhttp://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymousPT60S
", MessageID) + MessageID++ actual := base.Enumerate() assert.Equal(t, expected, actual) }) t.Run("Get", func(t *testing.T) { selector := &Selector{Name: "Key", Value: "Value"} - expected := fmt.Sprintf("
http://schemas.xmlsoap.org/ws/2004/09/transfer/Get/wsmantest-uriTestClass%dhttp://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymousPT60SValue
", MessageId) - MessageId++ + expected := fmt.Sprintf("
http://schemas.xmlsoap.org/ws/2004/09/transfer/Get/wsmantest-uriTestClass%dhttp://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymousPT60SValue
", MessageID) + MessageID++ actual := base.Get(selector) assert.Equal(t, expected, actual) }) t.Run("Pull", func(t *testing.T) { - enumerationContext := "test-context" - expected := fmt.Sprintf("
http://schemas.xmlsoap.org/ws/2004/09/enumeration/Pull/wsmantest-uriTestClass%dhttp://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymousPT60S
test-context99999999
", MessageId) - MessageId++ + enumerationContext := TestContext + expected := fmt.Sprintf("
http://schemas.xmlsoap.org/ws/2004/09/enumeration/Pull/wsmantest-uriTestClass%dhttp://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymousPT60S
test-context99999999
", MessageID) + MessageID++ actual := base.Pull(enumerationContext) assert.Equal(t, expected, actual) }) t.Run("Delete", func(t *testing.T) { - expected := fmt.Sprintf("
http://schemas.xmlsoap.org/ws/2004/09/transfer/Delete/wsmantest-uriTestClass%dhttp://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymousPT60SValue
", MessageId) - MessageId++ + expected := fmt.Sprintf("
http://schemas.xmlsoap.org/ws/2004/09/transfer/Delete/wsmantest-uriTestClass%dhttp://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymousPT60SValue
", MessageID) + MessageID++ actual := base.Delete(Selector{Name: "Name", Value: "Value"}) assert.Equal(t, expected, actual) }) t.Run("Put", func(t *testing.T) { - data := "test-data" + data := TestData customSelector := &Selector{Name: "Key", Value: "Value"} - expected := fmt.Sprintf("
http://schemas.xmlsoap.org/ws/2004/09/transfer/Put/wsmantest-uriTestClass%dhttp://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymousPT60SValue
test-data
", MessageId) - MessageId++ + expected := fmt.Sprintf("
http://schemas.xmlsoap.org/ws/2004/09/transfer/Put/wsmantest-uriTestClass%dhttp://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymousPT60SValue
test-data
", MessageID) + MessageID++ actual := base.Put(data, true, customSelector) assert.Equal(t, expected, actual) - expectedDefaultSelector := fmt.Sprintf("
http://schemas.xmlsoap.org/ws/2004/09/transfer/Put/wsmantest-uriTestClass%dhttp://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymousPT60Stest-data
test-data
", MessageId) - MessageId++ + expectedDefaultSelector := fmt.Sprintf("
http://schemas.xmlsoap.org/ws/2004/09/transfer/Put/wsmantest-uriTestClass%dhttp://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymousPT60Stest-data
test-data
", MessageID) + MessageID++ actualDefaultSelector := base.Put(data, true, nil) assert.Equal(t, expectedDefaultSelector, actualDefaultSelector) - expectedNoSelector := fmt.Sprintf("
http://schemas.xmlsoap.org/ws/2004/09/transfer/Put/wsmantest-uriTestClass%dhttp://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymousPT60S
test-data
", MessageId) - MessageId++ + expectedNoSelector := fmt.Sprintf("
http://schemas.xmlsoap.org/ws/2004/09/transfer/Put/wsmantest-uriTestClass%dhttp://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymousPT60S
test-data
", MessageID) + MessageID++ actualNoSelector := base.Put(data, false, customSelector) assert.Equal(t, expectedNoSelector, actualNoSelector) }) t.Run("Create", func(t *testing.T) { - data := "test-data" + data := TestData selector := &Selector{Name: "Key", Value: "Value"} - expected := fmt.Sprintf("
http://schemas.xmlsoap.org/ws/2004/09/transfer/Create/wsmantest-uriTestClass%dhttp://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymousPT60SValue
test-data
", MessageId) - MessageId++ + expected := fmt.Sprintf("
http://schemas.xmlsoap.org/ws/2004/09/transfer/Create/wsmantest-uriTestClass%dhttp://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymousPT60SValue
test-data
", MessageID) + MessageID++ actual := base.Create(data, selector) assert.Equal(t, expected, actual) }) t.Run("RequestStateChange", func(t *testing.T) { - actionName := "test-action" + actionName := TestAction requestedState := 2 - expected := fmt.Sprintf("
test-action/wsmantest-uriTestClass%dhttp://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymousPT60S
2
", MessageId) - MessageId++ + expected := fmt.Sprintf("
test-action/wsmantest-uriTestClass%dhttp://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymousPT60S
2
", MessageID) + MessageID++ actual := base.RequestStateChange(actionName, requestedState) assert.Equal(t, expected, actual) }) diff --git a/internal/message/types.go b/internal/message/types.go index 734acc98..a4f83b88 100644 --- a/internal/message/types.go +++ b/internal/message/types.go @@ -54,8 +54,8 @@ type ReturnValue struct { } type WSManMessageCreator struct { MessageID int - XmlCommonPrefix string - XmlCommonEnd string + XMLCommonPrefix string + XMLCommonEnd string AnonymousAddress string DefaultTimeout string ResourceURIBase string diff --git a/internal/message/wsman.go b/internal/message/wsman.go index 437dfcd9..c2416c1f 100644 --- a/internal/message/wsman.go +++ b/internal/message/wsman.go @@ -11,47 +11,58 @@ import ( "log" "reflect" "strings" + + "github.com/sirupsen/logrus" ) -func NewWSManMessageCreator(resourceUriBase string) *WSManMessageCreator { +func NewWSManMessageCreator(resourceURIBase string) *WSManMessageCreator { return &WSManMessageCreator{ MessageID: 0, - XmlCommonPrefix: ``, - XmlCommonEnd: ``, + XMLCommonPrefix: ``, + XMLCommonEnd: ``, AnonymousAddress: "http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous", DefaultTimeout: "PT60S", - ResourceURIBase: resourceUriBase, + ResourceURIBase: resourceURIBase, } } + func (w WSManMessageCreator) CreateXML(header, body string) string { - return w.XmlCommonPrefix + header + body + w.XmlCommonEnd + return w.XMLCommonPrefix + header + body + w.XMLCommonEnd } -func (w *WSManMessageCreator) CreateHeader(action string, wsmanClass string, selector *Selector, address string, timeout string) string { +func (w *WSManMessageCreator) CreateHeader(action, wsmanClass string, selector *Selector, address, timeout string) string { header := "
" header += fmt.Sprintf(`%s/wsman%s%s%d`, action, w.ResourceURIBase, wsmanClass, w.MessageID) + w.MessageID++ + if address != "" { header += fmt.Sprintf(`%s`, address) } else { header += fmt.Sprintf(`%s`, w.AnonymousAddress) } + header += "" + if timeout != "" { header += fmt.Sprintf(`%s`, timeout) } else { header += fmt.Sprintf(`%s`, w.DefaultTimeout) } + if selector != nil { header += w.createSelector(*selector) } + header += "
" + return header } func IsSlice(v interface{}) bool { return reflect.TypeOf(v).Kind() == reflect.Slice } + func (w WSManMessageCreator) namespaceMe(subj interface{}, wsmanClass string) { ifaceValue := reflect.ValueOf(subj) // Check if the interface value is a pointer @@ -60,28 +71,38 @@ func (w WSManMessageCreator) namespaceMe(subj interface{}, wsmanClass string) { stype := ifaceValue.Elem() if stype.Kind() == reflect.Struct { field := stype.FieldByName("H") - if field.IsValid() && field.CanAddr() { - fieldPtr := field.Addr().Interface().(*string) - *fieldPtr = fmt.Sprintf("%s%s", w.ResourceURIBase, wsmanClass) + + fieldPtr, ok := field.Addr().Interface().(*string) + if !ok { + logrus.Error("Failed to convert H to string") } + + *fieldPtr = fmt.Sprintf("%s%s", w.ResourceURIBase, wsmanClass) } } } -func (w WSManMessageCreator) CreateBody(method string, wsmanClass string, data interface{}) string { + +func (w WSManMessageCreator) CreateBody(method, wsmanClass string, data interface{}) string { var str strings.Builder + str.WriteString("") + if data != nil { w.namespaceMe(data, wsmanClass) + xmlString, err := xml.Marshal(data) if err != nil { log.Println(err) } + str.WriteString(string(xmlString)) } else { str.WriteString(fmt.Sprintf(``, method, w.ResourceURIBase, wsmanClass)) str.WriteString(fmt.Sprintf(``, method)) } + str.WriteString("") + return str.String() } @@ -89,10 +110,10 @@ func (w WSManMessageCreator) CreateBody(method string, wsmanClass string, data i // It can be used in the header or body. // selectorSet is the selector data being passed in. It could take many forms depending on the WSMAN call. func (w *WSManMessageCreator) createSelector(selectorSet Selector) string { - if selectorSet.Name != "" { - return fmt.Sprintf(`%s`, selectorSet.Name, selectorSet.Value) + return fmt.Sprintf(`%s`, selectorSet.Name, selectorSet.Value) } + return "" } @@ -108,6 +129,7 @@ func (w *WSManMessageCreator) CreateSelectorObjectForBody(selector Selector) map }, }, } + return obj } @@ -115,9 +137,11 @@ func createCommonBodyPull(enumerationContext string, maxElements, maxCharacters if maxElements == 0 { maxElements = 999 } + if maxCharacters == 0 { maxCharacters = 99999 } + return fmt.Sprintf(`%s%d%d`, enumerationContext, maxElements, maxCharacters) } @@ -126,5 +150,5 @@ func (w WSManMessageCreator) createCommonBodyCreateOrPut(wsmanClass string, data } func createCommonBodyRequestStateChange(input string, requestedState int) string { - return fmt.Sprintf(`%d`, input, requestedState) + return fmt.Sprintf(`%d`, input, requestedState) } diff --git a/internal/message/wsman_test.go b/internal/message/wsman_test.go index 476abdd0..65b0bd41 100644 --- a/internal/message/wsman_test.go +++ b/internal/message/wsman_test.go @@ -14,58 +14,64 @@ import ( ) func TestCreateXML(t *testing.T) { - messageId := 0 + messageID := 0 enumerationContext := "A4070000-0000-0000-0000-000000000000" wsmanMessageCreator := NewWSManMessageCreator("http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/") t.Run("creates an enumerate wsman string when provided a header and body to CreateXML", func(t *testing.T) { header := wsmanMessageCreator.CreateHeader(BaseActionsEnumerate, "CIM_ServiceAvailableToElement", nil, "", "") response := wsmanMessageCreator.CreateXML(header, EnumerateBody) - correctResponse := fmt.Sprintf(`
http://schemas.xmlsoap.org/ws/2004/09/enumeration/Enumerate/wsmanhttp://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ServiceAvailableToElement%dhttp://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymousPT60S
`, messageId) - messageId++ + correctResponse := fmt.Sprintf(`
http://schemas.xmlsoap.org/ws/2004/09/enumeration/Enumerate/wsmanhttp://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ServiceAvailableToElement%dhttp://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymousPT60S
`, messageID) + messageID++ + assert.Equal(t, correctResponse, response) }) t.Run("creates a pull wsman string when provided a header and body to createXML", func(t *testing.T) { header := wsmanMessageCreator.CreateHeader(BaseActionsPull, "CIM_ServiceAvailableToElement", nil, "", "") - var PULL_BODY = fmt.Sprintf(`%s99999999`, enumerationContext) - response := wsmanMessageCreator.CreateXML(header, PULL_BODY) - correctResponse := fmt.Sprintf(`
http://schemas.xmlsoap.org/ws/2004/09/enumeration/Pull/wsmanhttp://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ServiceAvailableToElement%dhttp://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymousPT60S
%s99999999
`, messageId, enumerationContext) - messageId++ + PullBody := fmt.Sprintf(`%s99999999`, enumerationContext) + response := wsmanMessageCreator.CreateXML(header, PullBody) + correctResponse := fmt.Sprintf(`
http://schemas.xmlsoap.org/ws/2004/09/enumeration/Pull/wsmanhttp://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ServiceAvailableToElement%dhttp://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymousPT60S
%s99999999
`, messageID, enumerationContext) + messageID++ + assert.Equal(t, correctResponse, response) }) } func TestCreateHeader(t *testing.T) { - messageId := 0 + messageID := 0 selector := Selector{Name: "InstanceID", Value: "Intel(r) AMT Device 0"} wsmanMessageCreator := NewWSManMessageCreator("http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/") t.Run("creates a correct header with action, resourceUri, and messageId provided for createHeader", func(t *testing.T) { - correctHeader := fmt.Sprintf(`
http://schemas.xmlsoap.org/ws/2004/09/enumeration/Enumerate/wsmanhttp://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ServiceAvailableToElement%dhttp://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymousPT60S
`, messageId) + correctHeader := fmt.Sprintf(`
http://schemas.xmlsoap.org/ws/2004/09/enumeration/Enumerate/wsmanhttp://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ServiceAvailableToElement%dhttp://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymousPT60S
`, messageID) header := wsmanMessageCreator.CreateHeader(BaseActionsEnumerate, "CIM_ServiceAvailableToElement", nil, "", "") - messageId++ + messageID++ + assert.Equal(t, correctHeader, header) }) t.Run("applies custom address correctly in createHeader", func(t *testing.T) { - correctHeader := fmt.Sprintf(`
http://schemas.xmlsoap.org/ws/2004/09/enumeration/Enumerate/wsmanhttp://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ServiceAvailableToElement%dcustomAddressPT60S
`, messageId) + correctHeader := fmt.Sprintf(`
http://schemas.xmlsoap.org/ws/2004/09/enumeration/Enumerate/wsmanhttp://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ServiceAvailableToElement%dcustomAddressPT60S
`, messageID) header := wsmanMessageCreator.CreateHeader(BaseActionsEnumerate, "CIM_ServiceAvailableToElement", nil, "customAddress", "") - messageId++ + messageID++ + assert.Equal(t, correctHeader, header) }) t.Run("applies custom timeout correctly in createHeader", func(t *testing.T) { - correctHeader := fmt.Sprintf(`
http://schemas.xmlsoap.org/ws/2004/09/enumeration/Enumerate/wsmanhttp://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ServiceAvailableToElement%dhttp://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymousPT30S
`, messageId) + correctHeader := fmt.Sprintf(`
http://schemas.xmlsoap.org/ws/2004/09/enumeration/Enumerate/wsmanhttp://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ServiceAvailableToElement%dhttp://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymousPT30S
`, messageID) header := wsmanMessageCreator.CreateHeader(BaseActionsEnumerate, "CIM_ServiceAvailableToElement", nil, "", "PT30S") - messageId++ + messageID++ + assert.Equal(t, correctHeader, header) }) t.Run("applies custom selector correctly in createHeader", func(t *testing.T) { - correctHeader := fmt.Sprintf(`
http://schemas.xmlsoap.org/ws/2004/09/enumeration/Enumerate/wsmanhttp://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ServiceAvailableToElement%dhttp://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymousPT30SIntel(r) AMT Device 0
`, messageId) + correctHeader := fmt.Sprintf(`
http://schemas.xmlsoap.org/ws/2004/09/enumeration/Enumerate/wsmanhttp://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ServiceAvailableToElement%dhttp://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymousPT30SIntel(r) AMT Device 0
`, messageID) header := wsmanMessageCreator.CreateHeader(BaseActionsEnumerate, "CIM_ServiceAvailableToElement", &selector, "", "PT30S") - messageId++ + messageID++ + assert.Equal(t, correctHeader, header) }) } @@ -87,6 +93,7 @@ func TestCreateBody(t *testing.T) { expectedResult := `test` assert.Equal(t, expectedResult, result) }) + t.Run("should create body without data", func(t *testing.T) { result := wsmanMessageCreator.CreateBody("testMethod", "testUri", nil) expectedResult := "" @@ -96,13 +103,14 @@ func TestCreateBody(t *testing.T) { func TestCreateSelectorObjectForBody(t *testing.T) { wsmanMessageCreator := NewWSManMessageCreator("http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/") + t.Run("should return map string interface", func(t *testing.T) { selector := Selector{ Name: "InstanceID", Value: "Value", } result := wsmanMessageCreator.CreateSelectorObjectForBody(selector) - expectedResult := map[string]interface{}(map[string]interface{}{"Selector": []map[string]interface{}{{"$": map[string]string{"Name": "InstanceID"}, "_": "Value"}}}) + expectedResult := map[string]interface{}{"Selector": []map[string]interface{}{{"$": map[string]string{"Name": "InstanceID"}, "_": "Value"}}} assert.Equal(t, expectedResult, result) }) } @@ -113,6 +121,7 @@ func TestIsSlice(t *testing.T) { result := IsSlice(slice) assert.True(t, result) }) + t.Run("should return false if input is not slice", func(t *testing.T) { notSlice := 0 result := IsSlice(notSlice) diff --git a/pkg/apf/processor.go b/pkg/apf/processor.go index 9c9d9d67..2badebd7 100644 --- a/pkg/apf/processor.go +++ b/pkg/apf/processor.go @@ -16,10 +16,13 @@ import ( func Process(data []byte, session *Session) bytes.Buffer { var bin_buf bytes.Buffer + var dataToSend interface{} + switch data[0] { case APF_GLOBAL_REQUEST: // 80 log.Debug("received APF_GLOBAL_REQUEST") + dataToSend = ProcessGlobalRequest(data) case APF_CHANNEL_OPEN: // (90) Sent by Intel AMT when a channel needs to be open from Intel AMT. This is not common, but WSMAN events are a good example of channel coming from AMT. log.Debug("received APF_CHANNEL_OPEN") @@ -27,56 +30,71 @@ func Process(data []byte, session *Session) bytes.Buffer { log.Debug("received APF_DISCONNECT") case APF_SERVICE_REQUEST: // (5) log.Debug("received APF_SERVICE_REQUEST") + dataToSend = ProcessServiceRequest(data) case APF_CHANNEL_OPEN_CONFIRMATION: // (91) Intel AMT confirmation to an APF_CHANNEL_OPEN request. log.Debug("received APF_CHANNEL_OPEN_CONFIRMATION") + ProcessChannelOpenConfirmation(data, session) case APF_CHANNEL_OPEN_FAILURE: // (92) Intel AMT rejected our connection attempt. log.Debug("received APF_CHANNEL_OPEN_FAILURE") + ProcessChannelOpenFailure(data, session) case APF_CHANNEL_CLOSE: // (97) Intel AMT is closing this channel, we need to disconnect the LMS TCP connection log.Debug("received APF_CHANNEL_CLOSE") + ProcessChannelClose(data, session) case APF_CHANNEL_DATA: // (94) Intel AMT is sending data that we must relay into an LMS TCP connection. ProcessChannelData(data, session) case APF_CHANNEL_WINDOW_ADJUST: // 93 log.Debug("received APF_CHANNEL_WINDOW_ADJUST") + ProcessChannelWindowAdjust(data, session) case APF_PROTOCOLVERSION: // 192 log.Debug("received APF PROTOCOL VERSION") + dataToSend = ProcessProtocolVersion(data) case APF_USERAUTH_REQUEST: // 50 default: } + if dataToSend != nil { err := binary.Write(&bin_buf, binary.BigEndian, dataToSend) if err != nil { log.Error(err) } } + return bin_buf } func ProcessChannelWindowAdjust(data []byte, session *Session) { adjustMessage := APF_CHANNEL_WINDOW_ADJUST_MESSAGE{} dataBuffer := bytes.NewBuffer(data) + err := binary.Read(dataBuffer, binary.BigEndian, &adjustMessage) if err != nil { log.Error(err) } + session.TXWindow += adjustMessage.BytesToAdd log.Tracef("%+v", adjustMessage) } + func ProcessChannelClose(data []byte, session *Session) APF_CHANNEL_CLOSE_MESSAGE { closeMessage := APF_CHANNEL_CLOSE_MESSAGE{} dataBuffer := bytes.NewBuffer(data) + err := binary.Read(dataBuffer, binary.BigEndian, &closeMessage) if err != nil { log.Error(err) } + log.Tracef("%+v", closeMessage) + return ChannelClose(closeMessage.RecipientChannel) } + func ProcessGlobalRequest(data []byte) interface{} { genericHeader := APF_GENERIC_HEADER{} dataBuffer := bytes.NewBuffer(data) @@ -85,12 +103,14 @@ func ProcessGlobalRequest(data []byte) interface{} { if err != nil { log.Error(err) } + err = binary.Read(dataBuffer, binary.BigEndian, &genericHeader.StringLength) if err != nil { log.Error(err) } var reply interface{} + if int(genericHeader.StringLength) > 0 { stringBuffer := make([]byte, genericHeader.StringLength) tcpForwardRequest := APF_TCP_FORWARD_REQUEST{} @@ -99,27 +119,35 @@ func ProcessGlobalRequest(data []byte) interface{} { if err != nil { log.Error(err) } + genericHeader.String = string(stringBuffer[:int(genericHeader.StringLength)]) + err = binary.Read(dataBuffer, binary.BigEndian, &tcpForwardRequest.WantReply) if err != nil { log.Error(err) } + err = binary.Read(dataBuffer, binary.BigEndian, &tcpForwardRequest.AddressLength) if err != nil { log.Error(err) } + if int(tcpForwardRequest.AddressLength) > 0 { addressBuffer := make([]byte, tcpForwardRequest.AddressLength) + err = binary.Read(dataBuffer, binary.BigEndian, &addressBuffer) if err != nil { log.Error(err) } + tcpForwardRequest.Address = string(addressBuffer[:int(tcpForwardRequest.AddressLength)]) } + err = binary.Read(dataBuffer, binary.BigEndian, &tcpForwardRequest.Port) if err != nil { log.Error(err) } + log.Tracef("%+v", genericHeader) log.Tracef("%+v", tcpForwardRequest) @@ -133,8 +161,10 @@ func ProcessGlobalRequest(data []byte) interface{} { reply = APF_REQUEST_SUCCESS } } + return reply } + func ProcessChannelData(data []byte, session *Session) { channelData := APF_CHANNEL_DATA_MESSAGE{} buf2 := bytes.NewBuffer(data) @@ -143,22 +173,27 @@ func ProcessChannelData(data []byte, session *Session) { if err != nil { log.Error(err) } + err = binary.Read(buf2, binary.BigEndian, &channelData.RecipientChannel) if err != nil { log.Error(err) } + err = binary.Read(buf2, binary.BigEndian, &channelData.DataLength) if err != nil { log.Error(err) } + session.RXWindow = channelData.DataLength dataBuffer := make([]byte, channelData.DataLength) + err = binary.Read(buf2, binary.BigEndian, &dataBuffer) if err != nil { log.Error(err) } - //log.Debug("received APF_CHANNEL_DATA - " + fmt.Sprint(channelData.DataLength)) - //log.Tracef("%+v", channelData) + + // log.Debug("received APF_CHANNEL_DATA - " + fmt.Sprint(channelData.DataLength)) + // log.Tracef("%+v", channelData) session.Tempdata = append(session.Tempdata, dataBuffer[:channelData.DataLength]...) // var windowAdjust APF_CHANNEL_WINDOW_ADJUST_MESSAGE @@ -166,7 +201,7 @@ func ProcessChannelData(data []byte, session *Session) { // windowAdjust = ChannelWindowAdjust(channelData.RecipientChannel, session.RXWindow) // session.RXWindow = 0 // } - session.Timer.Reset(3 * time.Second) + // var windowAdjust APF_CHANNEL_WINDOW_ADJUST_MESSAGE // if session.RXWindow > 1024 { // TODO: Check this // windowAdjust = ChannelWindowAdjust(channelData.RecipientChannel, session.RXWindow) @@ -174,16 +209,20 @@ func ProcessChannelData(data []byte, session *Session) { // } // // log.Tracef("%+v", session) // return windowAdjust - //return windowAdjust + // return windowAdjust + session.Timer.Reset(3 * time.Second) } + func ProcessServiceRequest(data []byte) APF_SERVICE_ACCEPT_MESSAGE { service := 0 message := APF_SERVICE_REQUEST_MESSAGE{} dataBuffer := bytes.NewBuffer(data) + err := binary.Read(dataBuffer, binary.BigEndian, &message.MessageType) if err != nil { log.Error(err) } + err = binary.Read(dataBuffer, binary.BigEndian, &message.ServiceNameLength) if err != nil { log.Error(err) @@ -191,12 +230,15 @@ func ProcessServiceRequest(data []byte) APF_SERVICE_ACCEPT_MESSAGE { if int(message.ServiceNameLength) > 0 { serviceNameBuffer := make([]byte, message.ServiceNameLength) + err = binary.Read(dataBuffer, binary.BigEndian, &serviceNameBuffer) if err != nil { log.Error(err) } + message.ServiceName = string(serviceNameBuffer[:int(message.ServiceNameLength)]) } + log.Tracef("%+v", message) if message.ServiceNameLength == 18 { @@ -206,19 +248,25 @@ func ProcessServiceRequest(data []byte) APF_SERVICE_ACCEPT_MESSAGE { service = 2 } } + var serviceAccept APF_SERVICE_ACCEPT_MESSAGE + if service > 0 { serviceAccept = ServiceAccept(message.ServiceName) } + return serviceAccept } + func ProcessChannelOpenConfirmation(data []byte, session *Session) { confirmationMessage := APF_CHANNEL_OPEN_CONFIRMATION_MESSAGE{} dataBuffer := bytes.NewBuffer(data) + err := binary.Read(dataBuffer, binary.BigEndian, &confirmationMessage) if err != nil { log.Error(err) } + log.Tracef("%+v", confirmationMessage) // replySuccess := ChannelOpenReplySuccess(confirmationMessage.RecipientChannel, confirmationMessage.SenderChannel) @@ -229,77 +277,100 @@ func ProcessChannelOpenConfirmation(data []byte, session *Session) { session.TXWindow = confirmationMessage.InitialWindowSize session.Status <- true } + func ProcessChannelOpenFailure(data []byte, session *Session) { channelOpenFailure := APF_CHANNEL_OPEN_FAILURE_MESSAGE{} dataBuffer := bytes.NewBuffer(data) + err := binary.Read(dataBuffer, binary.BigEndian, &channelOpenFailure) if err != nil { log.Error(err) } + log.Tracef("%+v", channelOpenFailure) session.Status <- false session.ErrorBuffer <- errors.New("error opening APF channel, reason code: " + fmt.Sprint(channelOpenFailure.ReasonCode)) } + func ProcessProtocolVersion(data []byte) APF_PROTOCOL_VERSION_MESSAGE { message := APF_PROTOCOL_VERSION_MESSAGE{} dataBuffer := bytes.NewBuffer(data) + err := binary.Read(dataBuffer, binary.BigEndian, &message) if err != nil { log.Error(err) } + log.Tracef("%+v", message) version := ProtocolVersion(message.MajorVersion, message.MinorVersion, message.TriggerReason) + return version } -// Send the AFP service accept message to the MEI +// Send the AFP service accept message to the MEI. func ServiceAccept(serviceName string) APF_SERVICE_ACCEPT_MESSAGE { log.Debug("sending APF_SERVICE_ACCEPT_MESSAGE") + if len(serviceName) != 18 { serviceName = fmt.Sprintf("'%-18s'", serviceName) } + var test [18]byte + copy(test[:], []byte(serviceName)[:18]) + serviceAcceptMessage := APF_SERVICE_ACCEPT_MESSAGE{ MessageType: APF_SERVICE_ACCEPT, ServiceNameLength: 18, ServiceName: test, } + log.Tracef("%+v", serviceAcceptMessage) + return serviceAcceptMessage } -func ProtocolVersion(majorversion uint32, minorversion uint32, triggerreason uint32) APF_PROTOCOL_VERSION_MESSAGE { +func ProtocolVersion(majorversion, minorversion, triggerreason uint32) APF_PROTOCOL_VERSION_MESSAGE { log.Debug("sending APF_PROTOCOL_VERSION_MESSAGE") + protVersion := APF_PROTOCOL_VERSION_MESSAGE{} protVersion.MessageType = APF_PROTOCOLVERSION protVersion.MajorVersion = majorversion protVersion.MinorVersion = minorversion protVersion.TriggerReason = triggerreason + log.Tracef("%+v", protVersion) + return protVersion } func TcpForwardReplySuccess(port uint32) APF_TCP_FORWARD_REPLY_MESSAGE { log.Debug("sending APF_TCP_FORWARD_REPLY_MESSAGE") + message := APF_TCP_FORWARD_REPLY_MESSAGE{ MessageType: APF_REQUEST_SUCCESS, PortBound: port, } + log.Tracef("%+v", message) + return message } func ChannelOpen(senderChannel int) bytes.Buffer { var channelType [15]byte + copy(channelType[:], []byte(APF_OPEN_CHANNEL_REQUEST_FORWARDED)[:15]) + var address [3]byte + copy(address[:], []byte("::1")[:3]) + openMessage := APF_CHANNEL_OPEN_MESSAGE{ MessageType: APF_CHANNEL_OPEN, ChannelTypeLength: 15, ChannelType: channelType, - SenderChannel: uint32(senderChannel), //hmm + SenderChannel: uint32(senderChannel), // hmm Reserved: 0xFFFFFFFF, InitialWindowSize: LME_RX_WINDOW_SIZE, ConnectedAddressLength: 3, @@ -309,28 +380,35 @@ func ChannelOpen(senderChannel int) bytes.Buffer { OriginatorIPAddress: address, OriginatorPort: 123, } + log.Tracef("%+v", openMessage) + var bin_buf bytes.Buffer + err := binary.Write(&bin_buf, binary.BigEndian, openMessage) if err != nil { log.Error(err) } + return bin_buf } -func ChannelOpenReplySuccess(recipientChannel uint32, senderChannel uint32) APF_CHANNEL_OPEN_CONFIRMATION_MESSAGE { +func ChannelOpenReplySuccess(recipientChannel, senderChannel uint32) APF_CHANNEL_OPEN_CONFIRMATION_MESSAGE { log.Debug("sending APF_CHANNEL_OPEN_CONFIRMATION") + message := APF_CHANNEL_OPEN_CONFIRMATION_MESSAGE{} message.MessageType = APF_CHANNEL_OPEN_CONFIRMATION message.RecipientChannel = recipientChannel message.SenderChannel = senderChannel message.InitialWindowSize = LME_RX_WINDOW_SIZE message.Reserved = 0xFFFFFFFF + log.Tracef("%+v", message) + return message } -func ChannelOpenReplyFailure(recipientChannel uint32, reason uint32) APF_CHANNEL_OPEN_FAILURE_MESSAGE { +func ChannelOpenReplyFailure(recipientChannel, reason uint32) APF_CHANNEL_OPEN_FAILURE_MESSAGE { log.Debug("sending APF_CHANNEL_OPEN_FAILURE") message := APF_CHANNEL_OPEN_FAILURE_MESSAGE{} @@ -339,32 +417,39 @@ func ChannelOpenReplyFailure(recipientChannel uint32, reason uint32) APF_CHANNEL message.ReasonCode = reason message.Reserved = 0x00000000 message.Reserved2 = 0x00000000 + return message } func ChannelClose(recipientChannel uint32) APF_CHANNEL_CLOSE_MESSAGE { log.Debug("sending APF_CHANNEL_CLOSE_MESSAGE") + message := APF_CHANNEL_CLOSE_MESSAGE{} message.MessageType = APF_CHANNEL_CLOSE message.RecipientChannel = recipientChannel + return message } func ChannelData(recipientChannel uint32, buffer []byte) APF_CHANNEL_DATA_MESSAGE { log.Debug("sending APF_CHANNEL_DATA_MESSAGE") + message := APF_CHANNEL_DATA_MESSAGE{} message.MessageType = APF_CHANNEL_DATA message.RecipientChannel = recipientChannel message.DataLength = uint32(len(buffer)) message.Data = buffer + return message } -func ChannelWindowAdjust(recipientChannel uint32, len uint32) APF_CHANNEL_WINDOW_ADJUST_MESSAGE { +func ChannelWindowAdjust(recipientChannel, l uint32) APF_CHANNEL_WINDOW_ADJUST_MESSAGE { log.Debug("sending APF_CHANNEL_WINDOW_ADJUST_MESSAGE") + message := APF_CHANNEL_WINDOW_ADJUST_MESSAGE{} message.MessageType = APF_CHANNEL_WINDOW_ADJUST message.RecipientChannel = recipientChannel - message.BytesToAdd = len + message.BytesToAdd = l + return message } diff --git a/pkg/apf/processor_test.go b/pkg/apf/processor_test.go index d8aa29c8..daafe1cb 100644 --- a/pkg/apf/processor_test.go +++ b/pkg/apf/processor_test.go @@ -8,18 +8,25 @@ import ( "testing" "time" + "github.com/sirupsen/logrus" "github.com/stretchr/testify/assert" ) func TestProcess(t *testing.T) { + t.Parallel() + data := []byte{0x01} session := &Session{} result := Process(data, session) + assert.NotNil(t, result) } + func TestProcessChannelOpenFailure(t *testing.T) { + t.Parallel() + data := []byte{0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00} errorChannel := make(chan error) statusChannel := make(chan bool) @@ -29,57 +36,81 @@ func TestProcessChannelOpenFailure(t *testing.T) { Status: statusChannel, } defer close(errorChannel) + go func() { status := <-statusChannel err := <-errorChannel assert.Error(t, err) assert.False(t, status) }() + ProcessChannelOpenFailure(data, session) } + func TestProcessChannelWindowAdjust(t *testing.T) { + t.Parallel() + data := []byte{0x01} session := &Session{} + ProcessChannelWindowAdjust(data, session) } + func TestProcessChannelClose(t *testing.T) { + t.Parallel() + data := []byte{0x01} session := &Session{} result := ProcessChannelClose(data, session) + assert.NotNil(t, result) } + func TestProcessGlobalRequest(t *testing.T) { - data := []byte{0x01, + t.Parallel() + + data := []byte{ + 0x01, 0x00, 0x00, 0x00, 0x0D, 0x74, 0x63, 0x70, 0x69, 0x70, 0x2d, 0x66, 0x6f, 0x72, 0x77, 0x61, 0x72, 0x64, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x42, 0x60} + 0x00, 0x00, 0x42, 0x60, + } result := ProcessGlobalRequest(data) assert.NotNil(t, result) } + func TestProcessChannelData(t *testing.T) { - data := []byte{0x01, + t.Parallel() + + data := []byte{ + 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, } - timer := time.NewTimer(time.Duration(2 * time.Second)) + timer := time.NewTimer(2 * time.Second) session := &Session{ Timer: timer, } + go func() { <-timer.C }() ProcessChannelData(data, session) - } + func TestProcessServiceRequestWhenAUTH(t *testing.T) { + t.Parallel() + data := []byte{0x01, 0x00, 0x00, 0x00, 0x12, 0x61, 0x75, 0x74, 0x68, 0x40, 0x61, 0x6d, 0x74, 0x2e, 0x69, 0x6e, 0x74, 0x65, 0x6c, 0x2e, 0x63, 0x6f, 0x6d} hi := int(0x12) - println(hi) + logrus.Print(hi) + result := ProcessServiceRequest(data) + assert.NotNil(t, result) assert.Equal(t, uint8(0x6), result.MessageType) // APF_SERVICE_ACCEPT assert.Equal(t, uint32(0x12), result.ServiceNameLength) @@ -87,83 +118,131 @@ func TestProcessServiceRequestWhenAUTH(t *testing.T) { } func TestProcessServiceRequestWhenPWFD(t *testing.T) { + t.Parallel() + data := []byte{0x01, 0x00, 0x00, 0x00, 0x12, 0x70, 0x66, 0x77, 0x64, 0x40, 0x61, 0x6d, 0x74, 0x2e, 0x69, 0x6e, 0x74, 0x65, 0x6c, 0x2e, 0x63, 0x6f, 0x6d} hi := int(0x12) - println(hi) + logrus.Print(hi) + result := ProcessServiceRequest(data) + assert.NotNil(t, result) assert.Equal(t, uint8(0x6), result.MessageType) // APF_SERVICE_ACCEPT assert.Equal(t, uint32(0x12), result.ServiceNameLength) assert.Equal(t, [18]uint8{0x70, 0x66, 0x77, 0x64, 0x40, 0x61, 0x6d, 0x74, 0x2e, 0x69, 0x6e, 0x74, 0x65, 0x6c, 0x2e, 0x63, 0x6f, 0x6d}, result.ServiceName) } + func TestProcessChannelOpenConfirmation(t *testing.T) { + t.Parallel() + data := []byte{0x01} statusChannel := make(chan bool) session := &Session{ Status: statusChannel, } + defer close(statusChannel) + go func() { <-statusChannel - println("Hello, status is done") + logrus.Print("Hello, status is done") }() ProcessChannelOpenConfirmation(data, session) } + func TestProcessProtocolVersion(t *testing.T) { + t.Parallel() + data := []byte{0x01} result := ProcessProtocolVersion(data) assert.NotNil(t, result) } + func TestServiceAcceptLessThan18Characters(t *testing.T) { + t.Parallel() + serviceName := "test" result := ServiceAccept(serviceName) assert.NotNil(t, result) } + func TestServiceAcceptEmptyString(t *testing.T) { + t.Parallel() + serviceName := "" result := ServiceAccept(serviceName) assert.NotNil(t, result) } + func TestServiceAccept18Characters(t *testing.T) { + t.Parallel() + serviceName := " " result := ServiceAccept(serviceName) assert.NotNil(t, result) } + func TestServiceAcceptMoreThan18Characters(t *testing.T) { + t.Parallel() + serviceName := " " result := ServiceAccept(serviceName) assert.NotNil(t, result) } + func TestProtocolVersion(t *testing.T) { + t.Parallel() + result := ProtocolVersion(1, 0, 9) assert.NotNil(t, result) } + func TestTcpForwardReplySuccess(t *testing.T) { + t.Parallel() + result := TcpForwardReplySuccess(16992) assert.NotNil(t, result) } + func TestChannelOpen(t *testing.T) { + t.Parallel() + result := ChannelOpen(1) assert.NotNil(t, result) } + func TestChannelOpenReplySuccess(t *testing.T) { + t.Parallel() + result := ChannelOpenReplySuccess(0, 1) assert.NotNil(t, result) } + func TestChannelOpenReplyFailure(t *testing.T) { + t.Parallel() + result := ChannelOpenReplyFailure(0, 1) assert.NotNil(t, result) } + func TestChannelClose(t *testing.T) { + t.Parallel() + result := ChannelClose(0) assert.NotNil(t, result) } + func TestChannelData(t *testing.T) { + t.Parallel() + data := []byte{0x01} result := ChannelData(0, data) assert.NotNil(t, result) } + func TestChannelWindowAdjust(t *testing.T) { + t.Parallel() + result := ChannelWindowAdjust(0, 32) assert.NotNil(t, result) } diff --git a/pkg/apf/types.go b/pkg/apf/types.go index 8f18a852..916860a6 100644 --- a/pkg/apf/types.go +++ b/pkg/apf/types.go @@ -6,69 +6,85 @@ package apf import "time" -const LMS_PROTOCOL_VERSION = 4 -const LME_RX_WINDOW_SIZE = 4096 - -// message op codes -const APF_DISCONNECT = 1 -const APF_SERVICE_REQUEST = 5 -const APF_SERVICE_ACCEPT = 6 -const APF_USERAUTH_REQUEST = 50 -const APF_USERAUTH_FAILURE = 51 -const APF_USERAUTH_SUCCESS = 52 -const APF_GLOBAL_REQUEST = 80 -const APF_REQUEST_SUCCESS = 81 -const APF_REQUEST_FAILURE = 82 -const APF_CHANNEL_OPEN = 90 -const APF_CHANNEL_OPEN_CONFIRMATION = 91 -const APF_CHANNEL_OPEN_FAILURE = 92 -const APF_CHANNEL_WINDOW_ADJUST = 93 -const APF_CHANNEL_DATA = 94 -const APF_CHANNEL_CLOSE = 97 -const APF_PROTOCOLVERSION = 192 - -// disconnect reason codes -const APF_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT = 1 -const APF_DISCONNECT_PROTOCOL_ERROR = 2 -const APF_DISCONNECT_KEY_EXCHANGE_FAILED = 3 -const APF_DISCONNECT_RESERVED = 4 -const APF_DISCONNECT_MAC_ERROR = 5 -const APF_DISCONNECT_COMPRESSION_ERROR = 6 -const APF_DISCONNECT_SERVICE_NOT_AVAILABLE = 7 -const APF_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED = 8 -const APF_DISCONNECT_HOST_KEY_NOT_VERIFIABLE = 9 -const APF_DISCONNECT_CONNECTION_LOST = 10 -const APF_DISCONNECT_BY_APPLICATION = 11 -const APF_DISCONNECT_TOO_MANY_CONNECTIONS = 12 -const APF_DISCONNECT_AUTH_CANCELLED_BY_USER = 13 -const APF_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE = 14 -const APF_DISCONNECT_ILLEGAL_USER_NAME = 15 - -// strings used in global messages -const APF_GLOBAL_REQUEST_STR_TCP_FORWARD_REQUEST = "tcpip-forward" -const APF_GLOBAL_REQUEST_STR_TCP_FORWARD_CANCEL_REQUEST = "cancel-tcpip-forward" -const APF_GLOBAL_REQUEST_STR_UDP_SEND_TO = "udp-send-to@amt.intel.com" -const APF_OPEN_CHANNEL_REQUEST_FORWARDED = "forwarded-tcpip" -const APF_OPEN_CHANNEL_REQUEST_DIRECT = "direct-tcpip" - -// APF service names -const APF_SERVICE_PFWD = "pfwd@amt.intel.com" -const APF_SERVICE_AUTH = "auth@amt.intel.com" - -// APF Authentication method -const APF_AUTH_NONE = "none" -const APF_AUTH_PASSWORD = "password" - -const APF_TRIGGER_REASON_USER_INITIATED_REQUEST = 1 -const APF_TRIGGER_REASON_ALERT_REQUEST = 2 -const APF_TRIGGER_REASON_HIT_PROVISIONING_REQUEST = 3 -const APF_TRIGGER_REASON_PERIODIC_REQUEST = 4 -const APF_TRIGGER_REASON_LME_REQUEST = 254 - -const OPEN_FAILURE_REASON_ADMINISTRATIVELY_PROHIBITED = 1 -const OPEN_FAILURE_REASON_CONNECT_FAILED = 2 -const OPEN_FAILURE_REASON_UNKNOWN_CHANNEL_TYPE = 3 -const OPEN_FAILURE_REASON_RESOURCE_SHORTAGE = 4 +const ( + LMS_PROTOCOL_VERSION = 4 + LME_RX_WINDOW_SIZE = 4096 +) + +// message op codes. +const ( + APF_DISCONNECT = 1 + APF_SERVICE_REQUEST = 5 + APF_SERVICE_ACCEPT = 6 + APF_USERAUTH_REQUEST = 50 + APF_USERAUTH_FAILURE = 51 + APF_USERAUTH_SUCCESS = 52 + APF_GLOBAL_REQUEST = 80 + APF_REQUEST_SUCCESS = 81 + APF_REQUEST_FAILURE = 82 + APF_CHANNEL_OPEN = 90 + APF_CHANNEL_OPEN_CONFIRMATION = 91 + APF_CHANNEL_OPEN_FAILURE = 92 + APF_CHANNEL_WINDOW_ADJUST = 93 + APF_CHANNEL_DATA = 94 + APF_CHANNEL_CLOSE = 97 + APF_PROTOCOLVERSION = 192 +) + +// disconnect reason codes. +const ( + APF_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT = 1 + APF_DISCONNECT_PROTOCOL_ERROR = 2 + APF_DISCONNECT_KEY_EXCHANGE_FAILED = 3 + APF_DISCONNECT_RESERVED = 4 + APF_DISCONNECT_MAC_ERROR = 5 + APF_DISCONNECT_COMPRESSION_ERROR = 6 + APF_DISCONNECT_SERVICE_NOT_AVAILABLE = 7 + APF_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED = 8 + APF_DISCONNECT_HOST_KEY_NOT_VERIFIABLE = 9 + APF_DISCONNECT_CONNECTION_LOST = 10 + APF_DISCONNECT_BY_APPLICATION = 11 + APF_DISCONNECT_TOO_MANY_CONNECTIONS = 12 + APF_DISCONNECT_AUTH_CANCELLED_BY_USER = 13 + APF_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE = 14 + APF_DISCONNECT_ILLEGAL_USER_NAME = 15 +) + +// strings used in global messages. +const ( + APF_GLOBAL_REQUEST_STR_TCP_FORWARD_REQUEST = "tcpip-forward" + APF_GLOBAL_REQUEST_STR_TCP_FORWARD_CANCEL_REQUEST = "cancel-tcpip-forward" + APF_GLOBAL_REQUEST_STR_UDP_SEND_TO = "udp-send-to@amt.intel.com" + APF_OPEN_CHANNEL_REQUEST_FORWARDED = "forwarded-tcpip" + APF_OPEN_CHANNEL_REQUEST_DIRECT = "direct-tcpip" +) + +// APF service names. +const ( + APF_SERVICE_PFWD = "pfwd@amt.intel.com" + APF_SERVICE_AUTH = "auth@amt.intel.com" +) + +// APF Authentication method. +const ( + APF_AUTH_NONE = "none" + APF_AUTH_PASSWORD = "password" +) + +const ( + APF_TRIGGER_REASON_USER_INITIATED_REQUEST = 1 + APF_TRIGGER_REASON_ALERT_REQUEST = 2 + APF_TRIGGER_REASON_HIT_PROVISIONING_REQUEST = 3 + APF_TRIGGER_REASON_PERIODIC_REQUEST = 4 + APF_TRIGGER_REASON_LME_REQUEST = 254 +) + +const ( + OPEN_FAILURE_REASON_ADMINISTRATIVELY_PROHIBITED = 1 + OPEN_FAILURE_REASON_CONNECT_FAILED = 2 + OPEN_FAILURE_REASON_UNKNOWN_CHANNEL_TYPE = 3 + OPEN_FAILURE_REASON_RESOURCE_SHORTAGE = 4 +) type APF_MESSAGE_HEADER struct { MessageType byte @@ -79,8 +95,8 @@ type APF_MESSAGE_HEADER struct { * * @MessageType: * @RequestStringLength: length of the string identifies the request - * @RequestString: the string that identifies the request - **/ + * @RequestString: the string that identifies the request. + *.*/ type APF_GENERIC_HEADER struct { MessageType byte @@ -97,8 +113,8 @@ type APF_TCP_FORWARD_REQUEST struct { /** * TCP forward reply message * @MessageType - Protocol's Major version - * @PortBound - the TCP port was bound on the server - **/ + * @PortBound - the TCP port was bound on the server. + *.*/ type APF_TCP_FORWARD_REPLY_MESSAGE struct { MessageType byte PortBound uint32 @@ -110,8 +126,8 @@ type APF_TCP_FORWARD_REPLY_MESSAGE struct { * @RecipientChannel - channel number given in the open request * @SenderChannel - channel number assigned by the sender * @InitialWindowSize - Number of bytes in the window - * @Reserved - Reserved - **/ + * @Reserved - Reserved. + *.*/ type APF_CHANNEL_OPEN_CONFIRMATION_MESSAGE struct { MessageType byte RecipientChannel uint32 @@ -125,8 +141,8 @@ type APF_CHANNEL_OPEN_CONFIRMATION_MESSAGE struct { * @MessageType - APF_CHANNEL_OPEN_FAILURE * @RecipientChannel - channel number given in the open request * @ReasonCode - code for the reason channel could not be open - * @Reserved - Reserved - **/ + * @Reserved - Reserved. + *.*/ type APF_CHANNEL_OPEN_FAILURE_MESSAGE struct { MessageType byte RecipientChannel uint32 @@ -138,8 +154,8 @@ type APF_CHANNEL_OPEN_FAILURE_MESSAGE struct { /** * close channel message * @MessageType - APF_CHANNEL_CLOSE - * @RecipientChannel - channel number given in the open request - **/ + * @RecipientChannel - channel number given in the open request. + *.*/ type APF_CHANNEL_CLOSE_MESSAGE struct { MessageType byte RecipientChannel uint32 @@ -150,8 +166,8 @@ type APF_CHANNEL_CLOSE_MESSAGE struct { * @MessageType - APF_CHANNEL_DATA * @RecipientChannel - channel number given in the open request * @Length - Length of the data in the message - * @Data - The data in the message - **/ + * @Data - The data in the message. + *.*/ type APF_CHANNEL_DATA_MESSAGE struct { MessageType byte RecipientChannel uint32 @@ -163,8 +179,8 @@ type APF_CHANNEL_DATA_MESSAGE struct { * used to adjust receive window size. * @MessageType - APF_WINDOW_ADJUST * @RecipientChannel - channel number given in the open request - * @BytesToAdd - number of bytes to add to current window size value - **/ + * @BytesToAdd - number of bytes to add to current window size value. + *.*/ type APF_CHANNEL_WINDOW_ADJUST_MESSAGE struct { MessageType byte RecipientChannel uint32 @@ -174,19 +190,19 @@ type APF_CHANNEL_WINDOW_ADJUST_MESSAGE struct { /** * This message causes immediate termination of the connection with AMT. * @ReasonCode - A Reason code for the disconnection event - * @Reserved - Reserved must be set to 0 - **/ + * @Reserved - Reserved must be set to 0. + *.*/ type APF_DISCONNECT_MESSAGE struct { MessageType byte ReasonCode uint32 - Reserved uint //short32 + Reserved uint // short32 } /** * Used to request a service identified by name * @ServiceNameLength - The length of the service name string. * @ServiceName - The name of the service being requested. - **/ + *.*/ type APF_SERVICE_REQUEST_MESSAGE struct { MessageType byte ServiceNameLength uint32 @@ -197,7 +213,7 @@ type APF_SERVICE_REQUEST_MESSAGE struct { * Used to send a service accept identified by name * @ServiceNameLength - The length of the service name string. * @ServiceName - The name of the service being requested. - **/ + *.*/ type APF_SERVICE_ACCEPT_MESSAGE struct { MessageType byte ServiceNameLength uint32 @@ -209,8 +225,8 @@ type APF_SERVICE_ACCEPT_MESSAGE struct { * @MajorVersion - Protocol's Major version * @MinorVersion - Protocol's Minor version * @Trigger - The open session reason - * @UUID - System Id - **/ + * @UUID - System Id. + *.*/ type APF_PROTOCOL_VERSION_MESSAGE struct { MessageType byte MajorVersion uint32 @@ -222,7 +238,7 @@ type APF_PROTOCOL_VERSION_MESSAGE struct { /** * holds the user authentication request success response. - **/ + *.*/ type APF_USERAUTH_SUCCESS_MESSAGE struct { MessageType byte } diff --git a/pkg/common/decoder.go b/pkg/common/decoder.go index c7ecce72..f70b0139 100644 --- a/pkg/common/decoder.go +++ b/pkg/common/decoder.go @@ -59,6 +59,7 @@ func Rstr2hex(input string) string { for i := 0; i < len(input); i++ { result += fmt.Sprintf("%02X", input[i]) } + return result } @@ -68,6 +69,7 @@ func Hex2rstr(d string) string { if err != nil { panic(err) // For simplicity, though you might want to handle errors more gracefully } + return string(bytes) } @@ -81,26 +83,35 @@ func ComputeDigesthash(username, password, realm, method, path, qop, nonce, nc, ha1 := md5.Sum([]byte(fmt.Sprintf("%s:%s:%s", username, realm, password))) ha2 := md5.Sum([]byte(fmt.Sprintf("%s:%s", method, path))) final := md5.Sum([]byte(fmt.Sprintf("%x:%s:%s:%s:%s:%x", ha1, nonce, nc, cnonce, qop, ha2))) + return fmt.Sprintf("%x", final) } // RandomValueHex generates a random hex string of a given length. -func RandomValueHex(len int) string { - b := make([]byte, (len+1)/2) // +1 to handle odd lengths +func RandomValueHex(i int) string { + b := make([]byte, (i+1)/2) // +1 to handle odd lengths if _, err := rand.Read(b); err != nil { panic(err) // For simplicity, though you might want to handle errors more gracefully } - return hex.EncodeToString(b)[:len] + + return hex.EncodeToString(b)[:i] } // GetSidString converts a byte array of SID into string. // Note: This function assumes sid is provided as a string for simplicity but should be []byte in a real Go implementation. func GetSidString(sid string) string { value := fmt.Sprintf("S-%d-%d", sid[0], sid[7]) + for i := 2; i < len(sid)/4; i++ { substr := sid[i*4 : (i+1)*4] - intValue, _ := strconv.ParseInt(strconv.Itoa(ReadIntX(substr, 0)), 10, 64) + + intValue, err := strconv.ParseInt(strconv.Itoa(ReadIntX(substr, 0)), 10, 64) + if err != nil { + return "" + } + value += fmt.Sprintf("-%d", intValue) } + return value } diff --git a/pkg/wsman/amt/alarmclock/decoder.go b/pkg/wsman/amt/alarmclock/decoder.go index 202cd21c..7bd8924f 100644 --- a/pkg/wsman/amt/alarmclock/decoder.go +++ b/pkg/wsman/amt/alarmclock/decoder.go @@ -5,22 +5,22 @@ package alarmclock -// INPUTS Constants +// INPUTS Constants. const ( - AMT_AlarmClockService string = "AMT_AlarmClockService" - AddAlarm string = "AddAlarm" + AMTAlarmClockService string = "AMT_AlarmClockService" + AddAlarm string = "AddAlarm" ) const ( Success ReturnValue = iota ) -// returnValueToString is a map of ReturnValue values to their string representations +// returnValueToString is a map of ReturnValue values to their string representations. var returnValueToString = map[ReturnValue]string{ Success: "Success", } -// String returns the string representation of the ReturnValue value +// String returns the string representation of the ReturnValue value. func (r ReturnValue) String() string { if value, exists := returnValueToString[r]; exists { return value diff --git a/pkg/wsman/amt/alarmclock/decoder_test.go b/pkg/wsman/amt/alarmclock/decoder_test.go index 60965160..c04d1e23 100644 --- a/pkg/wsman/amt/alarmclock/decoder_test.go +++ b/pkg/wsman/amt/alarmclock/decoder_test.go @@ -18,6 +18,7 @@ func TestReturnValue_String(t *testing.T) { for _, test := range tests { result := test.state.String() + if result != test.expected { t.Errorf("Expected %s, but got %s", test.expected, result) } diff --git a/pkg/wsman/amt/alarmclock/marshal.go b/pkg/wsman/amt/alarmclock/marshal.go index 9c82df6e..2b6c43c8 100644 --- a/pkg/wsman/amt/alarmclock/marshal.go +++ b/pkg/wsman/amt/alarmclock/marshal.go @@ -11,20 +11,22 @@ import ( "gopkg.in/yaml.v3" ) -// JSON marshals the type into JSON format +// JSON marshals the type into JSON format. func (r *Response) JSON() string { jsonOutput, err := json.Marshal(r.Body) if err != nil { return "" } + return string(jsonOutput) } -// YAML marshals the type into YAML format +// YAML marshals the type into YAML format. func (r *Response) YAML() string { yamlOutput, err := yaml.Marshal(r.Body) if err != nil { return "" } + return string(yamlOutput) } diff --git a/pkg/wsman/amt/alarmclock/service.go b/pkg/wsman/amt/alarmclock/service.go index 8f8b4f8b..022c120f 100644 --- a/pkg/wsman/amt/alarmclock/service.go +++ b/pkg/wsman/amt/alarmclock/service.go @@ -17,14 +17,14 @@ import ( "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/client" ) -// NewServiceWithClient instantiates a new Alarm Clock service +// NewServiceWithClient instantiates a new Alarm Clock service. func NewServiceWithClient(wsmanMessageCreator *message.WSManMessageCreator, client client.WSMan) Service { return Service{ - base: message.NewBaseWithClient(wsmanMessageCreator, AMT_AlarmClockService, client), + base: message.NewBaseWithClient(wsmanMessageCreator, AMTAlarmClockService, client), } } -// Get retrieves the representation of the instance +// Get retrieves the representation of the instance. func (acs Service) Get() (response Response, err error) { response = Response{ Message: &client.Message{ @@ -35,38 +35,39 @@ func (acs Service) Get() (response Response, err error) { // send the message to AMT err = acs.base.Execute(response.Message) if err != nil { - return + return response, err } // put the xml response into the go struct err = xml.Unmarshal([]byte(response.XMLOutput), &response) if err != nil { - return + return response, err } - return + return response, nil } -// Enumerate returns an enumeration context which is used in a subsequent Pull call +// Enumerate returns an enumeration context which is used in a subsequent Pull call. func (acs Service) Enumerate() (response Response, err error) { response = Response{ Message: &client.Message{ XMLInput: acs.base.Enumerate(), }, } + // send the message to AMT err = acs.base.Execute(response.Message) if err != nil { - return + return response, err } // put the xml response into the go struct err = xml.Unmarshal([]byte(response.XMLOutput), &response) if err != nil { - return + return response, err } - return + return response, nil } // Pull returns the instances of this class. An enumeration context provided by the Enumerate call is used as input. @@ -76,28 +77,30 @@ func (acs Service) Pull(enumerationContext string) (response Response, err error XMLInput: acs.base.Pull(enumerationContext), }, } + // send the message to AMT err = acs.base.Execute(response.Message) if err != nil { - return + return response, err } // put the xml response into the go struct err = xml.Unmarshal([]byte(response.XMLOutput), &response) if err != nil { - return + return response, err } - return + return response, nil } // AddAlarm creates an alarm that would wake the system at a given time. The method receives as input an embedded instance of type IPS_AlarmClockOccurrence, with the following fields set: StartTime, Interval, InstanceID, DeleteOnCompletion. Upon success, the method creates an instance of IPS_AlarmClockOccurrence which is associated with AlarmClockService. The method would fail if 5 instances or more of IPS_AlarmClockOccurrence already exist in the system. func (acs Service) AddAlarm(alarmClockOccurrence AlarmClockOccurrence) (response Response, err error) { - header := acs.base.WSManMessageCreator.CreateHeader(methods.GenerateAction(AMT_AlarmClockService, AddAlarm), AMT_AlarmClockService, nil, "", "") + header := acs.base.WSManMessageCreator.CreateHeader(methods.GenerateAction(AMTAlarmClockService, AddAlarm), AMTAlarmClockService, nil, "", "") startTime := alarmClockOccurrence.StartTime.UTC().Format(time.RFC3339Nano) startTime = strings.Split(startTime, ".")[0] var body strings.Builder + body.WriteString(``) @@ -135,17 +138,18 @@ func (acs Service) AddAlarm(alarmClockOccurrence AlarmClockOccurrence) (response XMLInput: acs.base.WSManMessageCreator.CreateXML(header, body.String()), }, } + // send the message to AMT err = acs.base.Execute(response.Message) if err != nil { - return + return response, err } // put the xml response into the go struct err = xml.Unmarshal([]byte(response.XMLOutput), &response) if err != nil { - return + return response, err } - return + return response, nil } diff --git a/pkg/wsman/amt/alarmclock/service_test.go b/pkg/wsman/amt/alarmclock/service_test.go index 55220ea8..4267d4fd 100644 --- a/pkg/wsman/amt/alarmclock/service_test.go +++ b/pkg/wsman/amt/alarmclock/service_test.go @@ -21,6 +21,7 @@ import ( const ( EnvelopeResponse = `http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous0` GetBody = `AMT_AlarmClockServiceIntel(r) AMT Alarm Clock ServiceIntel(r) AMT Alarm Clock ServiceCIM_ComputerSystemManagedSystem` + StartTime = "2022-12-31T23:59:00Z" ) func TestJson(t *testing.T) { @@ -47,12 +48,13 @@ func TestYaml(t *testing.T) { func TestPositiveAMT_AlarmClockService(t *testing.T) { messageID := 0 - resourceUriBase := "http://intel.com/wbem/wscim/1/amt-schema/1/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.AMTResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "amt/alarmclock", } elementUnderTest := NewServiceWithClient(wsmanMessageCreator, &client) + t.Run("amt_AlarmClockService Tests", func(t *testing.T) { tests := []struct { name string @@ -62,20 +64,21 @@ func TestPositiveAMT_AlarmClockService(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //GETS - {"should create and parse valid AMT_AlarmClockService Get call", - AMT_AlarmClockService, - wsmantesting.GET, + { + "should create and parse valid AMT_AlarmClockService Get call", + AMTAlarmClockService, + wsmantesting.Get, "", func() (Response, error) { - client.CurrentMessage = "Get" + client.CurrentMessage = wsmantesting.CurrentMessageGet + return elementUnderTest.Get() }, Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, GetResponse: AlarmClockService{ XMLName: xml.Name{Space: "http://intel.com/wbem/wscim/1/amt-schema/1/AMT_AlarmClockService", Local: "AMT_AlarmClockService"}, - CreationClassName: AMT_AlarmClockService, + CreationClassName: AMTAlarmClockService, ElementName: "Intel(r) AMT Alarm Clock Service", Name: "Intel(r) AMT Alarm Clock Service", SystemCreationClassName: "CIM_ComputerSystem", @@ -83,13 +86,15 @@ func TestPositiveAMT_AlarmClockService(t *testing.T) { }, }, }, - //ENUMERATES - {"should create and parse valid AMT_AlarmClockService Enumerate call", - AMT_AlarmClockService, - wsmantesting.ENUMERATE, - wsmantesting.ENUMERATE_BODY, + + { + "should create and parse valid AMT_AlarmClockService Enumerate call", + AMTAlarmClockService, + wsmantesting.Enumerate, + wsmantesting.EnumerateBody, func() (Response, error) { - client.CurrentMessage = "Enumerate" + client.CurrentMessage = wsmantesting.CurrentMessageEnumerate + return elementUnderTest.Enumerate() }, Body{ @@ -99,13 +104,15 @@ func TestPositiveAMT_AlarmClockService(t *testing.T) { }, }, }, - //PULLS - {"should create and parse valid AMT_AlarmClockService Pull call", - AMT_AlarmClockService, - wsmantesting.PULL, - wsmantesting.PULL_BODY, + + { + "should create and parse valid AMT_AlarmClockService Pull call", + AMTAlarmClockService, + wsmantesting.Pull, + wsmantesting.PullBody, func() (Response, error) { - client.CurrentMessage = "Pull" + client.CurrentMessage = wsmantesting.CurrentMessagePull + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -116,7 +123,7 @@ func TestPositiveAMT_AlarmClockService(t *testing.T) { { XMLName: xml.Name{Space: "http://intel.com/wbem/wscim/1/amt-schema/1/AMT_AlarmClockService", Local: "AMT_AlarmClockService"}, Name: "Intel(r) AMT Alarm Clock Service", - CreationClassName: AMT_AlarmClockService, + CreationClassName: AMTAlarmClockService, SystemName: "ManagedSystem", SystemCreationClassName: "CIM_ComputerSystem", ElementName: "Intel(r) AMT Alarm Clock Service", @@ -125,21 +132,25 @@ func TestPositiveAMT_AlarmClockService(t *testing.T) { }, }, }, - //AddAlarm + // AddAlarm { "should create and parse valid AMT_AlarmClockService AddAlarm call", - AMT_AlarmClockService, - methods.GenerateAction(AMT_AlarmClockService, AddAlarm), + AMTAlarmClockService, + methods.GenerateAction(AMTAlarmClockService, AddAlarm), `InstanceAlarm instance name2022-12-31T23:59:00ZP1DT23H59Mtrue`, func() (Response, error) { client.CurrentMessage = "AddAlarm" - startTime := "2022-12-31T23:59:00Z" + startTime := StartTime minutes := 59 hours := 23 days := 1 interval := minutes + hours*60 + days*1440 - startTimeFormatted, _ := time.Parse(time.RFC3339, startTime) + startTimeFormatted, err := time.Parse(time.RFC3339, startTime) + if err != nil { + return Response{}, err + } + return elementUnderTest.AddAlarm(AlarmClockOccurrence{ InstanceID: "Instance", StartTime: startTimeFormatted, @@ -171,7 +182,7 @@ func TestPositiveAMT_AlarmClockService(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, "", test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, "", test.body) messageID++ response, err := test.responseFunc() assert.NoError(t, err) @@ -184,12 +195,13 @@ func TestPositiveAMT_AlarmClockService(t *testing.T) { func TestNegativeAMT_AlarmClockService(t *testing.T) { messageID := 0 - resourceUriBase := "http://intel.com/wbem/wscim/1/amt-schema/1/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.AMTResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "amt/alarmclock", } elementUnderTest := NewServiceWithClient(wsmanMessageCreator, &client) + t.Run("amt_AlarmClockService Tests", func(t *testing.T) { tests := []struct { name string @@ -199,19 +211,20 @@ func TestNegativeAMT_AlarmClockService(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //GETS - {"should create and parse valid AMT_AlarmClockService Get call", - AMT_AlarmClockService, - wsmantesting.GET, + { + "should create and parse valid AMT_AlarmClockService Get call", + AMTAlarmClockService, + wsmantesting.Get, "", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Get() }, Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, GetResponse: AlarmClockService{ - CreationClassName: AMT_AlarmClockService, + CreationClassName: AMTAlarmClockService, ElementName: "Intel(r) AMT Alarm Clock Service", Name: "Intel(r) AMT Alarm Clock Service", SystemCreationClassName: "CIM_ComputerSystem", @@ -219,13 +232,15 @@ func TestNegativeAMT_AlarmClockService(t *testing.T) { }, }, }, - //ENUMERATES - {"should create and parse valid AMT_AlarmClockService Enumerate call", - AMT_AlarmClockService, - wsmantesting.ENUMERATE, - wsmantesting.ENUMERATE_BODY, + + { + "should create and parse valid AMT_AlarmClockService Enumerate call", + AMTAlarmClockService, + wsmantesting.Enumerate, + wsmantesting.EnumerateBody, func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Enumerate() }, Body{ @@ -235,13 +250,15 @@ func TestNegativeAMT_AlarmClockService(t *testing.T) { }, }, }, - //PULLS - {"should create and parse valid AMT_AlarmClockService Pull call", - AMT_AlarmClockService, - wsmantesting.PULL, - wsmantesting.PULL_BODY, + + { + "should create and parse valid AMT_AlarmClockService Pull call", + AMTAlarmClockService, + wsmantesting.Pull, + wsmantesting.PullBody, func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -252,7 +269,7 @@ func TestNegativeAMT_AlarmClockService(t *testing.T) { { XMLName: xml.Name{Space: "http://intel.com/wbem/wscim/1/amt-schema/1/AMT_AlarmClockService", Local: "AMT_AlarmClockService"}, Name: "Intel(r) AMT Alarm Clock Service", - CreationClassName: AMT_AlarmClockService, + CreationClassName: AMTAlarmClockService, SystemName: "ManagedSystem", SystemCreationClassName: "CIM_ComputerSystem", ElementName: "Intel(r) AMT Alarm Clock Service", @@ -261,20 +278,25 @@ func TestNegativeAMT_AlarmClockService(t *testing.T) { }, }, }, - //AddAlarm - {"should create and parse valid AMT_AlarmClockService AddAlarm call", - AMT_AlarmClockService, - methods.GenerateAction(AMT_AlarmClockService, AddAlarm), + + { + "should create and parse valid AMT_AlarmClockService AddAlarm call", + AMTAlarmClockService, + methods.GenerateAction(AMTAlarmClockService, AddAlarm), `InstanceAlarm instance name2022-12-31T23:59:00ZP1DT23H59Mtrue`, func() (Response, error) { - client.CurrentMessage = "Error" - startTime := "2022-12-31T23:59:00Z" + client.CurrentMessage = wsmantesting.CurrentMessageError + startTime := StartTime minutes := 59 hours := 23 days := 1 interval := minutes + hours*60 + days*1440 - startTimeFormatted, _ := time.Parse(time.RFC3339, startTime) + startTimeFormatted, err := time.Parse(time.RFC3339, startTime) + if err != nil { + return Response{}, err + } + return elementUnderTest.AddAlarm(AlarmClockOccurrence{ InstanceID: "Instance", StartTime: startTimeFormatted, @@ -306,7 +328,7 @@ func TestNegativeAMT_AlarmClockService(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, "", test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, "", test.body) messageID++ response, err := test.responseFunc() assert.Error(t, err) diff --git a/pkg/wsman/amt/alarmclock/types.go b/pkg/wsman/amt/alarmclock/types.go index 9ddca27b..ed9bb0ae 100644 --- a/pkg/wsman/amt/alarmclock/types.go +++ b/pkg/wsman/amt/alarmclock/types.go @@ -20,7 +20,7 @@ type Service struct { } // INPUTS -// AlarmClockOccurrence represents a single alarm clock setting +// AlarmClockOccurrence represents a single alarm clock setting. type AlarmClockOccurrence struct { ElementName string `json:"ElementName"` // Elementname is a user-friendly name for the object InstanceID string `json:"InstanceID"` // InstanceID is the instance key, set by the caller of AMT_AlarmClockService.AddAlarm. @@ -30,7 +30,7 @@ type AlarmClockOccurrence struct { } // OUTPUTS -// Response Types +// Response Types. type ( Response struct { *client.Message @@ -65,11 +65,11 @@ type ( ReturnValue ReturnValue // Return code. 0 indicates success } AlarmClock struct { - // Reference address to the created instance of IPS_AlarmClockOccurrence + // Reference address to the created instance of IPS_AlarmClockOccurrence. Address string ReferenceParameters models.ReferenceParameters_OUTPUT } - // ReturnValue is a return code. 0 indicates success + // ReturnValue is a return code. 0 indicates success. ReturnValue int ) diff --git a/pkg/wsman/amt/auditlog/decoder.go b/pkg/wsman/amt/auditlog/decoder.go index bc6a526f..ed5f995d 100644 --- a/pkg/wsman/amt/auditlog/decoder.go +++ b/pkg/wsman/amt/auditlog/decoder.go @@ -14,8 +14,9 @@ import ( ) const ( - AMT_AuditLog string = "AMT_AuditLog" - ReadRecords string = "ReadRecords" + AMTAuditLog string = "AMT_AuditLog" + ReadRecords string = "ReadRecords" + ValueNotFound string = "Value not found in map" ) const ( @@ -32,13 +33,13 @@ var OverwritePolicyToString = map[OverwritePolicy]string{ OverwritePolicyPartialRestrictedRollover: "PartialRestrictedRollover", } -// OverwritePolicyToString returns a string representation of a OverwritePolicy +// OverwritePolicyToString returns a string representation of a OverwritePolicy. func (r OverwritePolicy) String() string { if value, exists := OverwritePolicyToString[r]; exists { return value } - return "Value not found in map" + return ValueNotFound } const ( @@ -69,13 +70,13 @@ var EnabledStateToString = map[EnabledState]string{ EnabledStateStarting: "Starting", } -// EnabledStateToString returns a string representation of a EnabledState +// EnabledStateToString returns a string representation of a EnabledState. func (r EnabledState) String() string { if value, exists := EnabledStateToString[r]; exists { return value } - return "Value not found in map" + return ValueNotFound } const ( @@ -108,13 +109,13 @@ var RequestedStateToString = map[RequestedState]string{ RequestedStateNotApplicable: "NotApplicable", } -// RequestedStateToString returns a string representation of a RequestedState +// RequestedStateToString returns a string representation of a RequestedState. func (r RequestedState) String() string { if value, exists := RequestedStateToString[r]; exists { return value } - return "Value not found in map" + return ValueNotFound } const ( @@ -129,20 +130,26 @@ var StoragePolicyToString = map[StoragePolicy]string{ StoragePolicyRestrictedRollOver: "RestrictedRollOver", } -// StoragePolicyToString returns a string representation of a StoragePolicy +// StoragePolicyToString returns a string representation of a StoragePolicy. func (r StoragePolicy) String() string { if value, exists := StoragePolicyToString[r]; exists { return value } - return "Value not found in map" + return ValueNotFound } func convertToAuditLogResult(auditlogdata []string) []AuditLogRecord { records := []AuditLogRecord{} + for _, eventRecord := range auditlogdata { ptr := 0 - decodedEventRecord, _ := base64.StdEncoding.DecodeString(eventRecord) + + decodedEventRecord, err := base64.StdEncoding.DecodeString(eventRecord) + if err != nil { + continue + } + decodedEventRecordStr := string(decodedEventRecord) auditLogRecord := AuditLogRecord{} @@ -157,7 +164,7 @@ func convertToAuditLogResult(auditlogdata []string) []AuditLogRecord { // } initiatorType, initiator, pointer := getInitiatorInfo(decodedEventRecordStr) - auditLogRecord.InitiatorType = uint8(initiatorType) + auditLogRecord.InitiatorType = initiatorType auditLogRecord.Initiator = initiator ptr = pointer @@ -168,16 +175,16 @@ func convertToAuditLogResult(auditlogdata []string) []AuditLogRecord { // Read network access - auditLogRecord.MCLocationType = uint8([]byte(decodedEventRecordStr[ptr : ptr+1])[0]) - ptr = ptr + 1 - netlen := uint8([]byte(decodedEventRecordStr[ptr : ptr+1])[0]) - ptr = ptr + 1 - auditLogRecord.NetAddress = strings.Replace(decodedEventRecordStr[ptr:ptr+int(netlen)], "0000:0000:0000:0000:0000:0000:0000:0001", "::1", -1) + auditLogRecord.MCLocationType = []byte(decodedEventRecordStr[ptr : ptr+1])[0] + ptr++ + netlen := []byte(decodedEventRecordStr[ptr : ptr+1])[0] + ptr++ + auditLogRecord.NetAddress = strings.ReplaceAll(decodedEventRecordStr[ptr:ptr+int(netlen)], "0000:0000:0000:0000:0000:0000:0000:0001", "::1") // Read extended data ptr += int(netlen) - exlen := uint8([]byte(decodedEventRecordStr[ptr : ptr+1])[0]) - ptr = ptr + 1 + exlen := []byte(decodedEventRecordStr[ptr : ptr+1])[0] + ptr++ auditLogRecord.Ex = decodedEventRecordStr[ptr : ptr+int(exlen)] // auditLogRecord.ExStr = GetAuditLogExtendedDataString((auditLogRecord.AuditAppID*100)+auditLogRecord.EventID, auditLogRecord.Ex) @@ -188,16 +195,16 @@ func convertToAuditLogResult(auditlogdata []string) []AuditLogRecord { } const ( - AclEntryAdded = 1602 - AclEntryModified = 1603 - AclEntryRemoved = 1604 - AclAccessWithInvalidCredentials = 1605 - AclEntryStateChanged = 1606 - TlsStateChanged = 1607 + ACLEntryAdded = 1602 + ACLEntryModified = 1603 + ACLEntryRemoved = 1604 + ACLAccessWithInvalidCredentials = 1605 + ACLEntryStateChanged = 1606 + TLSStateChanged = 1607 SetRealmAuthenticationMode = 1617 - AmtUnprovisioningStarted = 1619 + AMTUnprovisioningStarted = 1619 FirmwareUpdate = 1900 - AmtTimeSet = 2100 + AMTTimeSet = 2100 OptInPolicyChange = 3000 SendConsentCode = 3001 ) @@ -265,26 +272,25 @@ const ( // } const ( - HttpDigest byte = 0 + HTTPDigest byte = 0 Kerberos byte = 1 Local byte = 2 KvmDefaultPort byte = 3 ) -// [initiatorType: number, initiator: string, ptr: number] need to type it -func getInitiatorInfo(decodedEventRecord string) (byte, string, int) { - initiator := "" +// [initiatorType: number, initiator: string, ptr: number] need to type it. +func getInitiatorInfo(decodedEventRecord string) (initatorType byte, initiator string, ptr int) { var userlen uint8 - ptr := 0 + initiatorType := []byte(decodedEventRecord[4:5])[0] switch initiatorType { - case HttpDigest: - userlen = uint8([]byte(decodedEventRecord[5:6])[0]) + case HTTPDigest: + userlen = []byte(decodedEventRecord[5:6])[0] initiator = decodedEventRecord[6 : 6+userlen] ptr = 6 + int(userlen) case Kerberos: - userlen = uint8([]byte(decodedEventRecord[9:10])[0]) + userlen = []byte(decodedEventRecord[9:10])[0] initiator = common.GetSidString(decodedEventRecord[10 : 10+userlen]) ptr = 10 + int(userlen) case Local: diff --git a/pkg/wsman/amt/auditlog/marshal.go b/pkg/wsman/amt/auditlog/marshal.go index 825197e5..bc087423 100644 --- a/pkg/wsman/amt/auditlog/marshal.go +++ b/pkg/wsman/amt/auditlog/marshal.go @@ -11,20 +11,22 @@ import ( "gopkg.in/yaml.v3" ) -// JSON marshals the type into JSON format +// JSON marshals the type into JSON format. func (r *Response) JSON() string { jsonOutput, err := json.Marshal(r.Body) if err != nil { return "" } + return string(jsonOutput) } -// YAML marshals the type into YAML format +// YAML marshals the type into YAML format. func (r *Response) YAML() string { yamlOutput, err := yaml.Marshal(r.Body) if err != nil { return "" } + return string(yamlOutput) } diff --git a/pkg/wsman/amt/auditlog/message.go b/pkg/wsman/amt/auditlog/message.go index 86702710..64da4dbb 100644 --- a/pkg/wsman/amt/auditlog/message.go +++ b/pkg/wsman/amt/auditlog/message.go @@ -14,14 +14,14 @@ import ( "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/client" ) -// NewAuditLogWithClient instantiates a new Audit Log service +// NewAuditLogWithClient instantiates a new Audit Log service. func NewAuditLogWithClient(wsmanMessageCreator *message.WSManMessageCreator, client client.WSMan) Service { return Service{ - base: message.NewBaseWithClient(wsmanMessageCreator, AMT_AuditLog, client), + base: message.NewBaseWithClient(wsmanMessageCreator, AMTAuditLog, client), } } -// Get retrieves the representation of the instance +// Get retrieves the representation of the instance. func (service Service) Get() (response Response, err error) { response = Response{ Message: &client.Message{ @@ -38,16 +38,18 @@ func (service Service) Get() (response Response, err error) { if err != nil { return } + return } -// Enumerate returns an enumeration context which is used in a subsequent Pull call +// Enumerate returns an enumeration context which is used in a subsequent Pull call. func (service Service) Enumerate() (response Response, err error) { response = Response{ Message: &client.Message{ XMLInput: service.base.Enumerate(), }, } + err = service.base.Execute(response.Message) if err != nil { return @@ -57,6 +59,7 @@ func (service Service) Enumerate() (response Response, err error) { if err != nil { return } + return } @@ -67,14 +70,17 @@ func (service Service) Pull(enumerationContext string) (response Response, err e XMLInput: service.base.Pull(enumerationContext), }, } + err = service.base.Execute(response.Message) if err != nil { return } + err = xml.Unmarshal([]byte(response.XMLOutput), &response) if err != nil { return } + return } @@ -85,22 +91,27 @@ func (service Service) ReadRecords(startIndex int) (response Response, err error if startIndex < 1 { startIndex = 0 } - header := service.base.WSManMessageCreator.CreateHeader(methods.GenerateAction(AMT_AuditLog, ReadRecords), AMT_AuditLog, nil, "", "") - body := service.base.WSManMessageCreator.CreateBody(methods.GenerateInputMethod(ReadRecords), AMT_AuditLog, &readRecords_INPUT{StartIndex: startIndex}) + + header := service.base.WSManMessageCreator.CreateHeader(methods.GenerateAction(AMTAuditLog, ReadRecords), AMTAuditLog, nil, "", "") + body := service.base.WSManMessageCreator.CreateBody(methods.GenerateInputMethod(ReadRecords), AMTAuditLog, &ReadRecordsInput{StartIndex: startIndex}) + response = Response{ Message: &client.Message{ XMLInput: service.base.WSManMessageCreator.CreateXML(header, body), }, } + err = service.base.Execute(response.Message) if err != nil { return } + err = xml.Unmarshal([]byte(response.XMLOutput), &response) if err != nil { return } response.Body.DecodedRecordsResponse = convertToAuditLogResult(response.Body.ReadRecordsResponse.EventRecords) + return } diff --git a/pkg/wsman/amt/auditlog/message_test.go b/pkg/wsman/amt/auditlog/message_test.go index 18bdc74c..621efaaf 100644 --- a/pkg/wsman/amt/auditlog/message_test.go +++ b/pkg/wsman/amt/auditlog/message_test.go @@ -10,11 +10,10 @@ import ( "testing" "time" - "github.com/stretchr/testify/assert" - "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/internal/message" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/common" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/wsmantesting" + "github.com/stretchr/testify/assert" ) func TestJson(t *testing.T) { @@ -41,8 +40,8 @@ func TestYaml(t *testing.T) { func TestPositiveAMT_AuditLog(t *testing.T) { messageID := 0 - resourceUriBase := "http://intel.com/wbem/wscim/1/amt-schema/1/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.AMTResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "amt/auditlog", } @@ -57,14 +56,15 @@ func TestPositiveAMT_AuditLog(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //GETS + // GETS { "should create a valid AMT_AuditLog Get wsman message", - AMT_AuditLog, - wsmantesting.GET, + AMTAuditLog, + wsmantesting.Get, "", func() (Response, error) { - client.CurrentMessage = "Get" + client.CurrentMessage = wsmantesting.CurrentMessageGet + return elementUnderTest.Get() }, Body{ @@ -88,14 +88,15 @@ func TestPositiveAMT_AuditLog(t *testing.T) { }, }, }, - //ENUMERATES + // ENUMERATES { "should create a valid AMT_AuditLog Enumerate wsman message", - AMT_AuditLog, - wsmantesting.ENUMERATE, - wsmantesting.ENUMERATE_BODY, + AMTAuditLog, + wsmantesting.Enumerate, + wsmantesting.EnumerateBody, func() (Response, error) { - client.CurrentMessage = "Enumerate" + client.CurrentMessage = wsmantesting.CurrentMessageEnumerate + return elementUnderTest.Enumerate() }, Body{ @@ -105,14 +106,15 @@ func TestPositiveAMT_AuditLog(t *testing.T) { }, }, }, - //PULLS + // PULLS { "should create a valid AMT_AuditLog Pull wsman message", - AMT_AuditLog, - wsmantesting.PULL, - wsmantesting.PULL_BODY, + AMTAuditLog, + wsmantesting.Pull, + wsmantesting.PullBody, func() (Response, error) { - client.CurrentMessage = "Pull" + client.CurrentMessage = wsmantesting.CurrentMessagePull + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -141,14 +143,15 @@ func TestPositiveAMT_AuditLog(t *testing.T) { }, }, }, - //READ RECORDS + // READ RECORDS { "should create a valid AMT_AuditLog Read Records wsman message", - AMT_AuditLog, + AMTAuditLog, `http://intel.com/wbem/wscim/1/amt-schema/1/AMT_AuditLog/ReadRecords`, `1`, func() (Response, error) { client.CurrentMessage = "ReadRecords" + return elementUnderTest.ReadRecords(1) }, Body{ @@ -194,7 +197,7 @@ func TestPositiveAMT_AuditLog(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, "", test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, "", test.body) messageID++ response, err := test.responseFunc() assert.NoError(t, err) @@ -204,10 +207,11 @@ func TestPositiveAMT_AuditLog(t *testing.T) { } }) } + func TestNegativeAMT_AuditLog(t *testing.T) { messageID := 0 - resourceUriBase := "http://intel.com/wbem/wscim/1/amt-schema/1/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.AMTResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "amt/auditlog", } @@ -222,14 +226,15 @@ func TestNegativeAMT_AuditLog(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //GETS + // GETS { "should create a valid AMT_AuditLog Get wsman message", - AMT_AuditLog, - wsmantesting.GET, + AMTAuditLog, + wsmantesting.Get, "", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Get() }, Body{ @@ -253,14 +258,15 @@ func TestNegativeAMT_AuditLog(t *testing.T) { }, }, }, - //ENUMERATES + // ENUMERATES { "should create a valid AMT_AuditLog Enumerate wsman message", - AMT_AuditLog, - wsmantesting.ENUMERATE, - wsmantesting.ENUMERATE_BODY, + AMTAuditLog, + wsmantesting.Enumerate, + wsmantesting.EnumerateBody, func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Enumerate() }, Body{ @@ -270,14 +276,15 @@ func TestNegativeAMT_AuditLog(t *testing.T) { }, }, }, - //PULLS + // PULLS { "should create a valid AMT_AuditLog Pull wsman message", - AMT_AuditLog, - wsmantesting.PULL, - wsmantesting.PULL_BODY, + AMTAuditLog, + wsmantesting.Pull, + wsmantesting.PullBody, func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -306,14 +313,15 @@ func TestNegativeAMT_AuditLog(t *testing.T) { }, }, }, - //READ RECORDS + // READ RECORDS { "should create a valid AMT_AuditLog Read Records wsman message", - AMT_AuditLog, + AMTAuditLog, `http://intel.com/wbem/wscim/1/amt-schema/1/AMT_AuditLog/ReadRecords`, `1`, func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.ReadRecords(1) }, Body{ @@ -331,7 +339,7 @@ func TestNegativeAMT_AuditLog(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, "", test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, "", test.body) messageID++ response, err := test.responseFunc() assert.Error(t, err) diff --git a/pkg/wsman/amt/auditlog/types.go b/pkg/wsman/amt/auditlog/types.go index cade5807..859e94d6 100644 --- a/pkg/wsman/amt/auditlog/types.go +++ b/pkg/wsman/amt/auditlog/types.go @@ -19,15 +19,15 @@ type Service struct { } // INPUTS -// Request Types -type readRecords_INPUT struct { +// Request Types. +type ReadRecordsInput struct { XMLName xml.Name `xml:"h:ReadRecords_INPUT"` H string `xml:"xmlns:h,attr"` StartIndex int `xml:"h:StartIndex" json:"StartIndex"` } // OUTPUTS -// Response Types +// Response Types. type ( Response struct { *client.Message diff --git a/pkg/wsman/amt/authorization/decoder.go b/pkg/wsman/amt/authorization/decoder.go index 60125ae7..2c74f007 100644 --- a/pkg/wsman/amt/authorization/decoder.go +++ b/pkg/wsman/amt/authorization/decoder.go @@ -5,20 +5,22 @@ package authorization -// INPUTS Constants +const ValueNotFound string = "Value not found in map" + +// INPUTS Constants. const ( - AMT_AuthorizationService string = "AMT_AuthorizationService" - EnumerateUserAclEntries string = "EnumerateUserAclEntries" - GetUserAclEntryEx string = "GetUserAclEntryEx" - UpdateUserAclEntryEx string = "UpdateUserAclEntryEx" - RemoveUserAclEntry string = "RemoveUserAclEntry" - GetAdminAclEntry string = "GetAdminAclEntry" - GetAdminAclEntryStatus string = "GetAdminAclEntryStatus" - GetAdminNetAclEntryStatus string = "GetAdminNetAclEntryStatus" - SetAclEnabledState string = "SetAclEnabledState" - GetAclEnabledState string = "GetAclEnabledState" - SetAdminAclEntryEx string = "SetAdminAclEntryEx" - AddUserAclEntryEx string = "AddUserAclEntryEx" + AMTAuthorizationService string = "AMT_AuthorizationService" + EnumerateUserACLEntries string = "EnumerateUserAclEntries" + GetUserACLEntryEx string = "GetUserAclEntryEx" + UpdateUserACLEntryEx string = "UpdateUserAclEntryEx" + RemoveUserACLEntry string = "RemoveUserAclEntry" + GetAdminACLEntry string = "GetAdminAclEntry" + GetAdminACLEntryStatus string = "GetAdminAclEntryStatus" + GetAdminNetACLEntryStatus string = "GetAdminNetAclEntryStatus" + SetACLEnabledState string = "SetAclEnabledState" + GetACLEnabledState string = "GetAclEnabledState" + SetAdminACLEntryEx string = "SetAdminAclEntryEx" + AddUserACLEntryEx string = "AddUserAclEntryEx" ) const ( @@ -69,7 +71,7 @@ const ( EnabledStateStarting ) -// enabledStateStrings is a map of EnabledState values to their string representations +// enabledStateStrings is a map of EnabledState values to their string representations. var enabledStateToString = map[EnabledState]string{ EnabledStateUnknown: "Unknown", EnabledStateOther: "Other", @@ -84,12 +86,13 @@ var enabledStateToString = map[EnabledState]string{ EnabledStateStarting: "Starting", } -// String returns the string representation of an EnabledState value +// String returns the string representation of an EnabledState value. func (e EnabledState) String() string { if value, exists := enabledStateToString[e]; exists { return value } - return "Value not found in map" + + return ValueNotFound } const ( @@ -107,7 +110,7 @@ const ( RequestedStateNotApplicable ) -// RequestedStateStrings is a map of RequestedState values to their string representations +// RequestedStateStrings is a map of RequestedState values to their string representations. var requestedStateToString = map[RequestedState]string{ RequestedStateUnknown: "Unknown", RequestedStateEnabled: "Enabled", @@ -123,12 +126,13 @@ var requestedStateToString = map[RequestedState]string{ RequestedStateNotApplicable: "NotApplicable", } -// String returns the string representation of a RequestedState value +// String returns the string representation of a RequestedState value. func (r RequestedState) String() string { if value, exists := requestedStateToString[r]; exists { return value } - return "Value not found in map" + + return ValueNotFound } const ( @@ -147,7 +151,7 @@ const ( PTStatusAuditFail ReturnValue = 2075 ) -// returnValuesToString is a map of return values to their string representation +// returnValuesToString is a map of return values to their string representation. var returnValuesToString = map[ReturnValue]string{ PTStatusSuccess: "Success", PTStatusInternalError: "InternalError", @@ -164,10 +168,11 @@ var returnValuesToString = map[ReturnValue]string{ PTStatusAuditFail: "AuditFail", } -// String returns the string representation of the return value +// String returns the string representation of the return value. func (r ReturnValue) String() string { if value, exists := returnValuesToString[r]; exists { return value } - return "Value not found in map" + + return ValueNotFound } diff --git a/pkg/wsman/amt/authorization/marshal.go b/pkg/wsman/amt/authorization/marshal.go index 6ce48582..4c1f3b41 100644 --- a/pkg/wsman/amt/authorization/marshal.go +++ b/pkg/wsman/amt/authorization/marshal.go @@ -11,20 +11,22 @@ import ( "gopkg.in/yaml.v3" ) -// JSON marshals the type into JSON format +// JSON marshals the type into JSON format. func (r *Response) JSON() string { jsonOutput, err := json.Marshal(r.Body) if err != nil { return "" } + return string(jsonOutput) } -// YAML marshals the type into YAML format +// YAML marshals the type into YAML format. func (r *Response) YAML() string { yamlOutput, err := yaml.Marshal(r.Body) if err != nil { return "" } + return string(yamlOutput) } diff --git a/pkg/wsman/amt/authorization/service.go b/pkg/wsman/amt/authorization/service.go index 004f78c7..64ceae66 100644 --- a/pkg/wsman/amt/authorization/service.go +++ b/pkg/wsman/amt/authorization/service.go @@ -22,85 +22,97 @@ import ( "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/client" ) -// Instantiates a new Authorization service -func NewServiceWithClient(wsmanMessageCreator *message.WSManMessageCreator, client client.WSMan) AuthorizationService { - return AuthorizationService{ - base: message.NewBaseWithClient(wsmanMessageCreator, AMT_AuthorizationService, client), +// Instantiates a new Authorization service. +func NewServiceWithClient(wsmanMessageCreator *message.WSManMessageCreator, client client.WSMan) Service { + return Service{ + base: message.NewBaseWithClient(wsmanMessageCreator, AMTAuthorizationService, client), } } -// Get retrieves the representation of the instance -func (as AuthorizationService) Get() (response Response, err error) { +// Get retrieves the representation of the instance. +func (as Service) Get() (response Response, err error) { response = Response{ Message: &client.Message{ XMLInput: as.base.Get(nil), }, } + // send the message to AMT err = as.base.Execute(response.Message) if err != nil { return } + // put the xml response into the go struct err = xml.Unmarshal([]byte(response.XMLOutput), &response) if err != nil { return } + return } -// Enumerate returns an enumeration context which is used in a subsequent Pull call -func (as AuthorizationService) Enumerate() (response Response, err error) { +// Enumerate returns an enumeration context which is used in a subsequent Pull call. +func (as Service) Enumerate() (response Response, err error) { response = Response{ Message: &client.Message{ XMLInput: as.base.Enumerate(), }, } + // send the message to AMT err = as.base.Execute(response.Message) if err != nil { return } + // put the xml response into the go struct err = xml.Unmarshal([]byte(response.XMLOutput), &response) if err != nil { return } + return } // Pull returns the instances of this class. An enumeration context provided by the Enumerate call is used as input. -func (as AuthorizationService) Pull(enumerationContext string) (response Response, err error) { +func (as Service) Pull(enumerationContext string) (response Response, err error) { response = Response{ Message: &client.Message{ XMLInput: as.base.Pull(enumerationContext), }, } + // send the message to AMT err = as.base.Execute(response.Message) if err != nil { return } + // put the xml response into the go struct err = xml.Unmarshal([]byte(response.XMLOutput), &response) if err != nil { return } + return } -// EnumerateUserAclEntries enumerates entries in the User Access Control List (ACL). -func (as AuthorizationService) EnumerateUserAclEntries(startIndex int) (response Response, err error) { +// EnumerateUserACLEntries enumerates entries in the User Access Control List (ACL). +func (as Service) EnumerateUserACLEntries(startIndex int) (response Response, err error) { if startIndex == 0 { startIndex = 1 } - header := as.base.WSManMessageCreator.CreateHeader(methods.GenerateAction(AMT_AuthorizationService, EnumerateUserAclEntries), AMT_AuthorizationService, nil, "", "") - body := as.base.WSManMessageCreator.CreateBody(methods.GenerateInputMethod(EnumerateUserAclEntries), AMT_AuthorizationService, &EnumerateUserAclEntries_INPUT{StartIndex: startIndex}) + + header := as.base.WSManMessageCreator.CreateHeader(methods.GenerateAction(AMTAuthorizationService, EnumerateUserACLEntries), AMTAuthorizationService, nil, "", "") + body := as.base.WSManMessageCreator.CreateBody(methods.GenerateInputMethod(EnumerateUserACLEntries), AMTAuthorizationService, &EnumerateUserAclEntries_INPUT{StartIndex: startIndex}) + response = Response{ Message: &client.Message{ XMLInput: as.base.WSManMessageCreator.CreateXML(header, body), }, } + err = as.base.Execute(response.Message) if err != nil { return @@ -111,18 +123,21 @@ func (as AuthorizationService) EnumerateUserAclEntries(startIndex int) (response if err != nil { return } + return } -// Gets the state of a user ACL entry (enabled/disabled) -func (as AuthorizationService) GetAclEnabledState(handle int) (response Response, err error) { - header := as.base.WSManMessageCreator.CreateHeader(methods.GenerateAction(AMT_AuthorizationService, GetAclEnabledState), AMT_AuthorizationService, nil, "", "") - body := as.base.WSManMessageCreator.CreateBody(methods.GenerateInputMethod(GetAclEnabledState), AMT_AuthorizationService, &GetAclEnabledState_INPUT{Handle: handle}) +// Gets the state of a user ACL entry (enabled/disabled). +func (as Service) GetACLEnabledState(handle int) (response Response, err error) { + header := as.base.WSManMessageCreator.CreateHeader(methods.GenerateAction(AMTAuthorizationService, GetACLEnabledState), AMTAuthorizationService, nil, "", "") + body := as.base.WSManMessageCreator.CreateBody(methods.GenerateInputMethod(GetACLEnabledState), AMTAuthorizationService, &GetAclEnabledState_INPUT{Handle: handle}) + response = Response{ Message: &client.Message{ XMLInput: as.base.WSManMessageCreator.CreateXML(header, body), }, } + err = as.base.Execute(response.Message) if err != nil { return @@ -133,18 +148,21 @@ func (as AuthorizationService) GetAclEnabledState(handle int) (response Response if err != nil { return } + return } -// Returns the username attribute of the Admin ACL -func (as AuthorizationService) GetAdminAclEntry() (response Response, err error) { - header := as.base.WSManMessageCreator.CreateHeader(methods.GenerateAction(AMT_AuthorizationService, GetAdminAclEntry), AMT_AuthorizationService, nil, "", "") - body := as.base.WSManMessageCreator.CreateBody(methods.GenerateInputMethod(GetAdminAclEntry), AMT_AuthorizationService, nil) +// Returns the username attribute of the Admin ACL. +func (as Service) GetAdminACLEntry() (response Response, err error) { + header := as.base.WSManMessageCreator.CreateHeader(methods.GenerateAction(AMTAuthorizationService, GetAdminACLEntry), AMTAuthorizationService, nil, "", "") + body := as.base.WSManMessageCreator.CreateBody(methods.GenerateInputMethod(GetAdminACLEntry), AMTAuthorizationService, nil) + response = Response{ Message: &client.Message{ XMLInput: as.base.WSManMessageCreator.CreateXML(header, body), }, } + err = as.base.Execute(response.Message) if err != nil { return @@ -155,18 +173,21 @@ func (as AuthorizationService) GetAdminAclEntry() (response Response, err error) if err != nil { return } + return } // Reads the Admin ACL Entry status from Intel® AMT. The return state changes as a function of the admin password. -func (as AuthorizationService) GetAdminAclEntryStatus() (response Response, err error) { - header := as.base.WSManMessageCreator.CreateHeader(methods.GenerateAction(AMT_AuthorizationService, GetAdminAclEntryStatus), AMT_AuthorizationService, nil, "", "") - body := as.base.WSManMessageCreator.CreateBody(methods.GenerateInputMethod(GetAdminAclEntryStatus), AMT_AuthorizationService, nil) +func (as Service) GetAdminACLEntryStatus() (response Response, err error) { + header := as.base.WSManMessageCreator.CreateHeader(methods.GenerateAction(AMTAuthorizationService, GetAdminACLEntryStatus), AMTAuthorizationService, nil, "", "") + body := as.base.WSManMessageCreator.CreateBody(methods.GenerateInputMethod(GetAdminACLEntryStatus), AMTAuthorizationService, nil) + response = Response{ Message: &client.Message{ XMLInput: as.base.WSManMessageCreator.CreateXML(header, body), }, } + err = as.base.Execute(response.Message) if err != nil { return @@ -177,18 +198,21 @@ func (as AuthorizationService) GetAdminAclEntryStatus() (response Response, err if err != nil { return } + return } // Reads the remote Admin ACL Entry status from Intel® AMT. The return state changes as a function of the remote admin password. -func (as AuthorizationService) GetAdminNetAclEntryStatus() (response Response, err error) { - header := as.base.WSManMessageCreator.CreateHeader(methods.GenerateAction(AMT_AuthorizationService, GetAdminNetAclEntryStatus), AMT_AuthorizationService, nil, "", "") - body := as.base.WSManMessageCreator.CreateBody(methods.GenerateInputMethod(GetAdminNetAclEntryStatus), AMT_AuthorizationService, nil) +func (as Service) GetAdminNetACLEntryStatus() (response Response, err error) { + header := as.base.WSManMessageCreator.CreateHeader(methods.GenerateAction(AMTAuthorizationService, GetAdminNetACLEntryStatus), AMTAuthorizationService, nil, "", "") + body := as.base.WSManMessageCreator.CreateBody(methods.GenerateInputMethod(GetAdminNetACLEntryStatus), AMTAuthorizationService, nil) + response = Response{ Message: &client.Message{ XMLInput: as.base.WSManMessageCreator.CreateXML(header, body), }, } + err = as.base.Execute(response.Message) if err != nil { return @@ -199,18 +223,21 @@ func (as AuthorizationService) GetAdminNetAclEntryStatus() (response Response, e if err != nil { return } + return } // Reads a user entry from the Intel® AMT device. Note: confidential information, such as password (hash) is omitted or zeroed in the response. -func (as AuthorizationService) GetUserAclEntryEx(handle int) (response Response, err error) { - header := as.base.WSManMessageCreator.CreateHeader(methods.GenerateAction(AMT_AuthorizationService, GetUserAclEntryEx), AMT_AuthorizationService, nil, "", "") - body := as.base.WSManMessageCreator.CreateBody(methods.GenerateInputMethod(GetUserAclEntryEx), AMT_AuthorizationService, &GetUserAclEntryEx_INPUT{Handle: handle}) +func (as Service) GetUserACLEntryEx(handle int) (response Response, err error) { + header := as.base.WSManMessageCreator.CreateHeader(methods.GenerateAction(AMTAuthorizationService, GetUserACLEntryEx), AMTAuthorizationService, nil, "", "") + body := as.base.WSManMessageCreator.CreateBody(methods.GenerateInputMethod(GetUserACLEntryEx), AMTAuthorizationService, &GetUserAclEntryEx_INPUT{Handle: handle}) + response = Response{ Message: &client.Message{ XMLInput: as.base.WSManMessageCreator.CreateXML(header, body), }, } + err = as.base.Execute(response.Message) if err != nil { return @@ -221,18 +248,21 @@ func (as AuthorizationService) GetUserAclEntryEx(handle int) (response Response, if err != nil { return } + return } // Removes an entry from the User Access Control List (ACL), given a handle. -func (as AuthorizationService) RemoveUserAclEntry(handle int) (response Response, err error) { - header := as.base.WSManMessageCreator.CreateHeader(methods.GenerateAction(AMT_AuthorizationService, RemoveUserAclEntry), AMT_AuthorizationService, nil, "", "") - body := as.base.WSManMessageCreator.CreateBody(methods.GenerateInputMethod(RemoveUserAclEntry), AMT_AuthorizationService, &RemoveUserAclEntry_INPUT{Handle: handle}) +func (as Service) RemoveUserACLEntry(handle int) (response Response, err error) { + header := as.base.WSManMessageCreator.CreateHeader(methods.GenerateAction(AMTAuthorizationService, RemoveUserACLEntry), AMTAuthorizationService, nil, "", "") + body := as.base.WSManMessageCreator.CreateBody(methods.GenerateInputMethod(RemoveUserACLEntry), AMTAuthorizationService, &RemoveUserAclEntry_INPUT{Handle: handle}) + response = Response{ Message: &client.Message{ XMLInput: as.base.WSManMessageCreator.CreateXML(header, body), }, } + err = as.base.Execute(response.Message) if err != nil { return @@ -243,18 +273,21 @@ func (as AuthorizationService) RemoveUserAclEntry(handle int) (response Response if err != nil { return } + return } // Enables or disables a user ACL entry. Disabling ACL entries is useful when accounts that cannot be removed (system accounts - starting with $$) are required to be disabled. -func (as AuthorizationService) SetAclEnabledState(handle int, enabled bool) (response Response, err error) { - header := as.base.WSManMessageCreator.CreateHeader(methods.GenerateAction(AMT_AuthorizationService, SetAclEnabledState), AMT_AuthorizationService, nil, "", "") - body := as.base.WSManMessageCreator.CreateBody(methods.GenerateInputMethod(SetAclEnabledState), AMT_AuthorizationService, &SetAclEnabledState_INPUT{Handle: handle, Enabled: enabled}) +func (as Service) SetACLEnabledState(handle int, enabled bool) (response Response, err error) { + header := as.base.WSManMessageCreator.CreateHeader(methods.GenerateAction(AMTAuthorizationService, SetACLEnabledState), AMTAuthorizationService, nil, "", "") + body := as.base.WSManMessageCreator.CreateBody(methods.GenerateInputMethod(SetACLEnabledState), AMTAuthorizationService, &SetAclEnabledState_INPUT{Handle: handle, Enabled: enabled}) + response = Response{ Message: &client.Message{ XMLInput: as.base.WSManMessageCreator.CreateXML(header, body), }, } + err = as.base.Execute(response.Message) if err != nil { return @@ -265,18 +298,21 @@ func (as AuthorizationService) SetAclEnabledState(handle int, enabled bool) (res if err != nil { return } + return } // Updates an Admin entry in the Intel® AMT device. -func (as AuthorizationService) SetAdminAclEntryEx(username, digestPassword string) (response Response, err error) { - header := as.base.WSManMessageCreator.CreateHeader(methods.GenerateAction(AMT_AuthorizationService, SetAdminAclEntryEx), AMT_AuthorizationService, nil, "", "") - body := as.base.WSManMessageCreator.CreateBody(methods.GenerateInputMethod(SetAdminAclEntryEx), AMT_AuthorizationService, &SetAdminAclEntryEx_INPUT{Username: username, DigestPassword: digestPassword}) +func (as Service) SetAdminAclEntryEx(username, digestPassword string) (response Response, err error) { + header := as.base.WSManMessageCreator.CreateHeader(methods.GenerateAction(AMTAuthorizationService, SetAdminACLEntryEx), AMTAuthorizationService, nil, "", "") + body := as.base.WSManMessageCreator.CreateBody(methods.GenerateInputMethod(SetAdminACLEntryEx), AMTAuthorizationService, &SetAdminAclEntryEx_INPUT{Username: username, DigestPassword: digestPassword}) + response = Response{ Message: &client.Message{ XMLInput: as.base.WSManMessageCreator.CreateXML(header, body), }, } + err = as.base.Execute(response.Message) if err != nil { return @@ -287,5 +323,6 @@ func (as AuthorizationService) SetAdminAclEntryEx(username, digestPassword strin if err != nil { return } + return } diff --git a/pkg/wsman/amt/authorization/service_test.go b/pkg/wsman/amt/authorization/service_test.go index bb12de68..1b17cf4d 100644 --- a/pkg/wsman/amt/authorization/service_test.go +++ b/pkg/wsman/amt/authorization/service_test.go @@ -21,7 +21,7 @@ func TestJson(t *testing.T) { GetResponse: AuthorizationOccurrence{}, }, } - expectedResult := "{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"GetResponse\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"AllowHttpQopAuthOnly\":0,\"CreationClassName\":\"\",\"ElementName\":\"\",\"EnabledState\":0,\"Name\":\"\",\"RequestedState\":0,\"SystemCreationClassName\":\"\",\"SystemName\":\"\"},\"EnumerateResponse\":{\"EnumerationContext\":\"\"},\"PullResponse\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"AuthorizationOccurrenceItems\":null},\"SetAdminResponse\":{\"ReturnValue\":0}}" + expectedResult := "{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"GetResponse\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"AllowHTTPQopAuthOnly\":0,\"CreationClassName\":\"\",\"ElementName\":\"\",\"EnabledState\":0,\"Name\":\"\",\"RequestedState\":0,\"SystemCreationClassName\":\"\",\"SystemName\":\"\"},\"EnumerateResponse\":{\"EnumerationContext\":\"\"},\"PullResponse\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"AuthorizationOccurrenceItems\":null},\"SetAdminResponse\":{\"ReturnValue\":0}}" result := response.JSON() assert.Equal(t, expectedResult, result) } @@ -39,12 +39,13 @@ func TestYaml(t *testing.T) { func TestPositiveAMT_AuthorizationService(t *testing.T) { messageID := 0 - resourceUriBase := "http://intel.com/wbem/wscim/1/amt-schema/1/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.AMTResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "amt/authorization", } elementUnderTest := NewServiceWithClient(wsmanMessageCreator, &client) + t.Run("amt_AuthorizationService Tests", func(t *testing.T) { tests := []struct { name string @@ -54,13 +55,14 @@ func TestPositiveAMT_AuthorizationService(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //GETS - {"should create a valid AMT_AuthorizationService Get wsman message", - AMT_AuthorizationService, - wsmantesting.GET, + { + "should create a valid AMT_AuthorizationService Get wsman message", + AMTAuthorizationService, + wsmantesting.Get, "", func() (Response, error) { - client.CurrentMessage = "Get" + client.CurrentMessage = wsmantesting.CurrentMessageGet + return elementUnderTest.Get() }, Body{ @@ -68,7 +70,7 @@ func TestPositiveAMT_AuthorizationService(t *testing.T) { GetResponse: AuthorizationOccurrence{ XMLName: xml.Name{Space: "http://intel.com/wbem/wscim/1/amt-schema/1/AMT_AuthorizationService", Local: "AMT_AuthorizationService"}, AllowHttpQopAuthOnly: 1, - CreationClassName: AMT_AuthorizationService, + CreationClassName: AMTAuthorizationService, ElementName: "Intel(r) AMT Authorization Service", EnabledState: 5, Name: "Intel(r) AMT Authorization Service", @@ -78,13 +80,15 @@ func TestPositiveAMT_AuthorizationService(t *testing.T) { }, }, }, - //ENUMERATES - {"should create a valid AMT_AuthorizationService Enumerate wsman message", - AMT_AuthorizationService, - wsmantesting.ENUMERATE, - wsmantesting.ENUMERATE_BODY, + + { + "should create a valid AMT_AuthorizationService Enumerate wsman message", + AMTAuthorizationService, + wsmantesting.Enumerate, + wsmantesting.EnumerateBody, func() (Response, error) { - client.CurrentMessage = "Enumerate" + client.CurrentMessage = wsmantesting.CurrentMessageEnumerate + return elementUnderTest.Enumerate() }, Body{ @@ -94,14 +98,15 @@ func TestPositiveAMT_AuthorizationService(t *testing.T) { }, }, }, - //PULLS + // PULLS { "should create a valid AMT_AuthorizationService Pull wsman message", - AMT_AuthorizationService, - wsmantesting.PULL, - wsmantesting.PULL_BODY, + AMTAuthorizationService, + wsmantesting.Pull, + wsmantesting.PullBody, func() (Response, error) { - client.CurrentMessage = "Pull" + client.CurrentMessage = wsmantesting.CurrentMessagePull + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -112,7 +117,7 @@ func TestPositiveAMT_AuthorizationService(t *testing.T) { { XMLName: xml.Name{Space: "http://intel.com/wbem/wscim/1/amt-schema/1/AMT_AuthorizationService", Local: "AMT_AuthorizationService"}, AllowHttpQopAuthOnly: 1, - CreationClassName: AMT_AuthorizationService, + CreationClassName: AMTAuthorizationService, ElementName: "Intel(r) AMT Authorization Service", EnabledState: 5, Name: "Intel(r) AMT Authorization Service", @@ -128,10 +133,10 @@ func TestPositiveAMT_AuthorizationService(t *testing.T) { // // ADD USER ACL ENTRY EX // // Verify with Matt - Typescript is referring to wrong realm values - // // {"should return a valid amt_AuthorizationService ADD_USER_ACL_ENTRY_EX wsman message using digest", AMT_AuthorizationService, ADD_USER_ACL_ENTRY_EX, fmt.Sprintf(`%s%s%d%d`, "test", "P@ssw0rd", 2, 3), func() string { + // // {"should return a valid amt_AuthorizationService ADD_USER_ACL_ENTRY_EX wsman message using digest", AMT_AuthorizationService, ADD_USER_ACL_ENTRY_EX, logrus.Sprintf(`%s%s%d%d`, "test", "P@ssw0rd", 2, 3), func() string { // // return elementUnderTest.AddUserAclEntryEx(authorization.AccessPermissionLocalAndNetworkAccess, []authorization.RealmValues{authorization.RedirectionRealm}, "test", "P@ssw0rd", "") // // }}, - // // {"should return a valid amt_AuthorizationService ADD_USER_ACL_ENTRY_EX wsman message using kerberos", AMT_AuthorizationService, ADD_USER_ACL_ENTRY_EX, fmt.Sprintf(`%d%d%d3`, 64, 2, 3), func() string { + // // {"should return a valid amt_AuthorizationService ADD_USER_ACL_ENTRY_EX wsman message using kerberos", AMT_AuthorizationService, ADD_USER_ACL_ENTRY_EX, logrus.Sprintf(`%d%d%d3`, 64, 2, 3), func() string { // // return elementUnderTest.AddUserAclEntryEx(authorization.AccessPermissionLocalAndNetworkAccess, []authorization.RealmValues{authorization.RedirectionRealm}, "", "", "64") // // }}, // // // Check how to verify for exceptions @@ -139,11 +144,11 @@ func TestPositiveAMT_AuthorizationService(t *testing.T) { // // // return elementUnderTest.AddUserAclEntryEx(2, []models.RealmValues{models.RedirectionRealm}, "thisusernameistoolong", "test", "") // // // }}, // // ENUMERATE USER ACL ENTRIES - // {"should return a valid amt_AuthorizationService EnumerateUserAclEntries wsman message when startIndex is undefined", AMT_AuthorizationService, `http://intel.com/wbem/wscim/1/amt-schema/1/AMT_AuthorizationService/EnumerateUserAclEntries`, fmt.Sprintf(`%d`, 1), func() string { + // {"should return a valid amt_AuthorizationService EnumerateUserAclEntries wsman message when startIndex is undefined", AMT_AuthorizationService, `http://intel.com/wbem/wscim/1/amt-schema/1/AMT_AuthorizationService/EnumerateUserAclEntries`, logrus.Sprintf(`%d`, 1), func() string { // var index int // return elementUnderTest.EnumerateUserAclEntries(index) // }}, - // {"should return a valid amt_AuthorizationService EnumerateUserAclEntries wsman message when startIndex is not 1", AMT_AuthorizationService, `http://intel.com/wbem/wscim/1/amt-schema/1/AMT_AuthorizationService/EnumerateUserAclEntries`, fmt.Sprintf(`%d`, 50), func() string { + // {"should return a valid amt_AuthorizationService EnumerateUserAclEntries wsman message when startIndex is not 1", AMT_AuthorizationService, `http://intel.com/wbem/wscim/1/amt-schema/1/AMT_AuthorizationService/EnumerateUserAclEntries`, logrus.Sprintf(`%d`, 50), func() string { // return elementUnderTest.EnumerateUserAclEntries(50) // }}, // // GET USER ACL ENTRY EX @@ -188,11 +193,12 @@ func TestPositiveAMT_AuthorizationService(t *testing.T) { // SET ADMIN ACL ENTRY { "should return a valid amt_AuthorizationService SetAdminAclEntryEx wsman message", - AMT_AuthorizationService, + AMTAuthorizationService, `http://intel.com/wbem/wscim/1/amt-schema/1/AMT_AuthorizationService/SetAdminAclEntryEx`, `adminAMviB05zT+twP2E9Tn/hPA==`, func() (Response, error) { client.CurrentMessage = "SetAdminAclEntryEx" + return elementUnderTest.SetAdminAclEntryEx("admin", "AMviB05zT+twP2E9Tn/hPA==") }, Body{ @@ -205,7 +211,7 @@ func TestPositiveAMT_AuthorizationService(t *testing.T) { } for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, "", test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, "", test.body) messageID++ response, err := test.responseFunc() assert.NoError(t, err) @@ -215,14 +221,16 @@ func TestPositiveAMT_AuthorizationService(t *testing.T) { } }) } + func TestNegativeAMT_AuthorizationService(t *testing.T) { messageID := 0 - resourceUriBase := "http://intel.com/wbem/wscim/1/amt-schema/1/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.AMTResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "amt/authorization", } elementUnderTest := NewServiceWithClient(wsmanMessageCreator, &client) + t.Run("amt_AuthorizationService Tests", func(t *testing.T) { tests := []struct { name string @@ -236,11 +244,12 @@ func TestNegativeAMT_AuthorizationService(t *testing.T) { { "should create an invalid AMT_EthernetPortSettings Get wsman message", "AMT_EthernetPortSettings", - wsmantesting.GET, + wsmantesting.Get, "", "", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Get() }, Body{ @@ -248,7 +257,7 @@ func TestNegativeAMT_AuthorizationService(t *testing.T) { GetResponse: AuthorizationOccurrence{ XMLName: xml.Name{Space: "http://intel.com/wbem/wscim/1/amt-schema/1/AMT_AuthorizationService", Local: "AMT_AuthorizationService"}, AllowHttpQopAuthOnly: 1, - CreationClassName: AMT_AuthorizationService, + CreationClassName: AMTAuthorizationService, ElementName: "Intel(r) AMT Authorization Service", EnabledState: 5, Name: "Intel(r) AMT Authorization Service", @@ -261,11 +270,12 @@ func TestNegativeAMT_AuthorizationService(t *testing.T) { { "should create an invalid AMT_EthernetPortSettings Pull wsman message", "AMT_EthernetPortSettings", - wsmantesting.PULL, - wsmantesting.PULL_BODY, + wsmantesting.Pull, + wsmantesting.PullBody, "", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Pull("") }, Body{ @@ -276,7 +286,7 @@ func TestNegativeAMT_AuthorizationService(t *testing.T) { { XMLName: xml.Name{Space: "http://intel.com/wbem/wscim/1/amt-schema/1/AMT_AuthorizationService", Local: "AMT_AuthorizationService"}, AllowHttpQopAuthOnly: 1, - CreationClassName: AMT_AuthorizationService, + CreationClassName: AMTAuthorizationService, ElementName: "Intel(r) AMT Authorization Service", EnabledState: 5, Name: "Intel(r) AMT Authorization Service", @@ -292,7 +302,7 @@ func TestNegativeAMT_AuthorizationService(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, test.extraHeader, test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, test.extraHeader, test.body) messageID++ response, err := test.responseFunc() assert.Error(t, err) diff --git a/pkg/wsman/amt/authorization/types.go b/pkg/wsman/amt/authorization/types.go index 734b3173..6eb3fcc9 100644 --- a/pkg/wsman/amt/authorization/types.go +++ b/pkg/wsman/amt/authorization/types.go @@ -13,12 +13,12 @@ import ( "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/common" ) -type AuthorizationService struct { +type Service struct { base message.Base } // OUTPUTS -// Response Types +// Response Types. type ( Response struct { *client.Message @@ -64,16 +64,16 @@ type ( // ValueMap={0, 1, 2} // -// Values={LocalAccessPermission, NetworkAccessPermission, AnyAccessPermission} +// Values={LocalAccessPermission, NetworkAccessPermission, AnyAccessPermission}. type AccessPermission int // ValueMap={0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, ..} // -// Values={InvalidRealm, ReservedRealm0, RedirectionRealm, PTAdministrationRealm, HardwareAssetRealm, RemoteControlRealm, StorageRealm, EventManagerRealm, StorageAdminRealm, AgentPresenceLocalRealm, AgentPresenceRemoteRealm, CircuitBreakerRealm, NetworkTimeRealm, GeneralInfoRealm, FirmwareUpdateRealm, EITRealm, LocalUN, EndpointAccessControlRealm, EndpointAccessControlAdminRealm, EventLogReaderRealm, AuditLogRealm, ACLRealm, ReservedRealm1, ReservedRealm2, LocalSystemRealm, Reserved} +// Values={InvalidRealm, ReservedRealm0, RedirectionRealm, PTAdministrationRealm, HardwareAssetRealm, RemoteControlRealm, StorageRealm, EventManagerRealm, StorageAdminRealm, AgentPresenceLocalRealm, AgentPresenceRemoteRealm, CircuitBreakerRealm, NetworkTimeRealm, GeneralInfoRealm, FirmwareUpdateRealm, EITRealm, LocalUN, EndpointAccessControlRealm, EndpointAccessControlAdminRealm, EventLogReaderRealm, AuditLogRealm, ACLRealm, ReservedRealm1, ReservedRealm2, LocalSystemRealm, Reserved}. type RealmValues int // INPUTS -// Request Types +// Request Types. type ( EnumerateUserAclEntries_INPUT struct { XMLName xml.Name `xml:"h:EnumerateUserAclEntries_INPUT"` diff --git a/pkg/wsman/amt/boot/capabilities.go b/pkg/wsman/amt/boot/capabilities.go index 6f3eb282..4cda250c 100644 --- a/pkg/wsman/amt/boot/capabilities.go +++ b/pkg/wsman/amt/boot/capabilities.go @@ -17,14 +17,14 @@ import ( "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/client" ) -// NewBootCapabilitiesWithClient instantiates a new Boot Capabilities service +// NewBootCapabilitiesWithClient instantiates a new Boot Capabilities service. func NewBootCapabilitiesWithClient(wsmanMessageCreator *message.WSManMessageCreator, client client.WSMan) Capabilities { return Capabilities{ - base: message.NewBaseWithClient(wsmanMessageCreator, AMT_BootCapabilities, client), + base: message.NewBaseWithClient(wsmanMessageCreator, AMTBootCapabilities, client), } } -// Get retrieves the representation of the instance +// Get retrieves the representation of the instance. func (bootCapabilities Capabilities) Get() (response Response, err error) { response = Response{ Message: &client.Message{ @@ -41,10 +41,11 @@ func (bootCapabilities Capabilities) Get() (response Response, err error) { if err != nil { return } + return } -// Enumerate returns an enumeration context which is used in a subsequent Pull call +// Enumerate returns an enumeration context which is used in a subsequent Pull call. func (bootCapabilities Capabilities) Enumerate() (response Response, err error) { response = Response{ Message: &client.Message{ @@ -61,6 +62,7 @@ func (bootCapabilities Capabilities) Enumerate() (response Response, err error) if err != nil { return } + return } @@ -81,5 +83,6 @@ func (bootCapabilities Capabilities) Pull(enumerationContext string) (response R if err != nil { return } + return } diff --git a/pkg/wsman/amt/boot/capabilities_test.go b/pkg/wsman/amt/boot/capabilities_test.go index c4cb6060..68e19517 100644 --- a/pkg/wsman/amt/boot/capabilities_test.go +++ b/pkg/wsman/amt/boot/capabilities_test.go @@ -9,11 +9,10 @@ import ( "encoding/xml" "testing" - "github.com/stretchr/testify/assert" - "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/internal/message" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/common" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/wsmantesting" + "github.com/stretchr/testify/assert" ) func TestJson(t *testing.T) { @@ -40,8 +39,8 @@ func TestYaml(t *testing.T) { func TestPositiveAMT_BootCapabilities(t *testing.T) { messageID := 0 - resourceUriBase := "http://intel.com/wbem/wscim/1/amt-schema/1/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.AMTResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "amt/boot/capabilities", } @@ -56,14 +55,15 @@ func TestPositiveAMT_BootCapabilities(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //GETS + // GETS { "should create a valid AMT_BootCapabilities Get wsman message", - AMT_BootCapabilities, - wsmantesting.GET, + AMTBootCapabilities, + wsmantesting.Get, "", func() (Response, error) { - client.CurrentMessage = "Get" + client.CurrentMessage = wsmantesting.CurrentMessageGet + return elementUnderTest.Get() }, Body{ @@ -97,14 +97,15 @@ func TestPositiveAMT_BootCapabilities(t *testing.T) { }, }, }, - //ENUMERATES + // ENUMERATES { "should create a valid AMT_BootCapabilities Enumerate wsman message", - AMT_BootCapabilities, - wsmantesting.ENUMERATE, - wsmantesting.ENUMERATE_BODY, + AMTBootCapabilities, + wsmantesting.Enumerate, + wsmantesting.EnumerateBody, func() (Response, error) { - client.CurrentMessage = "Enumerate" + client.CurrentMessage = wsmantesting.CurrentMessageEnumerate + return elementUnderTest.Enumerate() }, Body{ @@ -114,14 +115,15 @@ func TestPositiveAMT_BootCapabilities(t *testing.T) { }, }, }, - //PULLS + // PULLS { "should create a valid AMT_BootCapabilities Pull wsman message", - AMT_BootCapabilities, - wsmantesting.PULL, - wsmantesting.PULL_BODY, + AMTBootCapabilities, + wsmantesting.Pull, + wsmantesting.PullBody, func() (Response, error) { - client.CurrentMessage = "Pull" + client.CurrentMessage = wsmantesting.CurrentMessagePull + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -164,7 +166,7 @@ func TestPositiveAMT_BootCapabilities(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, "", test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, "", test.body) messageID++ response, err := test.responseFunc() assert.NoError(t, err) @@ -177,8 +179,8 @@ func TestPositiveAMT_BootCapabilities(t *testing.T) { func TestNegativeAMT_BootCapabilities(t *testing.T) { messageID := 0 - resourceUriBase := "http://intel.com/wbem/wscim/1/amt-schema/1/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.AMTResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "amt/boot/capabilities", } @@ -193,14 +195,15 @@ func TestNegativeAMT_BootCapabilities(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //GETS + // GETS { "should create a valid AMT_BootCapabilities Get wsman message", - AMT_BootCapabilities, - wsmantesting.GET, + AMTBootCapabilities, + wsmantesting.Get, "", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Get() }, Body{ @@ -240,14 +243,15 @@ func TestNegativeAMT_BootCapabilities(t *testing.T) { }, }, }, - //ENUMERATES + // ENUMERATES { "should create a valid AMT_BootCapabilities Enumerate wsman message", - AMT_BootCapabilities, - wsmantesting.ENUMERATE, + AMTBootCapabilities, + wsmantesting.Enumerate, "", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Enumerate() }, Body{ @@ -257,14 +261,15 @@ func TestNegativeAMT_BootCapabilities(t *testing.T) { }, }, }, - //PULLS + // PULLS { "should create a valid AMT_BootCapabilities Pull wsman message", - AMT_BootCapabilities, - wsmantesting.PULL, + AMTBootCapabilities, + wsmantesting.Pull, "", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -313,7 +318,7 @@ func TestNegativeAMT_BootCapabilities(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, "", test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, "", test.body) messageID++ response, err := test.responseFunc() assert.Error(t, err) diff --git a/pkg/wsman/amt/boot/decoder.go b/pkg/wsman/amt/boot/decoder.go index 1be35fb9..186ffddd 100644 --- a/pkg/wsman/amt/boot/decoder.go +++ b/pkg/wsman/amt/boot/decoder.go @@ -5,10 +5,11 @@ package boot -// INPUTS Constants +// INPUTS Constants. const ( - AMT_BootSettingData string = "AMT_BootSettingData" - AMT_BootCapabilities string = "AMT_BootCapabilities" + AMTBootSettingData string = "AMT_BootSettingData" + AMTBootCapabilities string = "AMT_BootCapabilities" + ValueNotFound string = "Value not found in map" ) const ( @@ -23,7 +24,7 @@ const ( CDBoot ) -// FirmwareVerbosityToString is a map of FirmwareVerbosity values to their string representations +// FirmwareVerbosityToString is a map of FirmwareVerbosity values to their string representations. var firmwareVerbosityToString = map[FirmwareVerbosity]string{ SystemDefault: "SystemDefault", QuietMinimal: "QuietMinimal", @@ -31,26 +32,26 @@ var firmwareVerbosityToString = map[FirmwareVerbosity]string{ ScreenBlank: "ScreenBlank", } -// String returns the string representation of the FirmwareVerbosity value +// String returns the string representation of the FirmwareVerbosity value. func (f FirmwareVerbosity) String() string { if value, exists := firmwareVerbosityToString[f]; exists { return value } - return "Value not found in map" + return ValueNotFound } -// iderBootDeviceToString is a map of IDERBootDevice values to their string representations +// iderBootDeviceToString is a map of IDERBootDevice values to their string representations. var iderBootDeviceToString = map[IDERBootDevice]string{ FloppyBoot: "FloppyBoot", CDBoot: "CDBoot", } -// String returns the string representation of the IDERBootDevice value +// String returns the string representation of the IDERBootDevice value. func (i IDERBootDevice) String() string { if value, exists := iderBootDeviceToString[i]; exists { return value } - return "Value not found in map" + return ValueNotFound } diff --git a/pkg/wsman/amt/boot/marshal.go b/pkg/wsman/amt/boot/marshal.go index 8b27da02..5770d38e 100644 --- a/pkg/wsman/amt/boot/marshal.go +++ b/pkg/wsman/amt/boot/marshal.go @@ -11,20 +11,22 @@ import ( "gopkg.in/yaml.v3" ) -// JSON marshals the type into JSON format +// JSON marshals the type into JSON format. func (r *Response) JSON() string { jsonOutput, err := json.Marshal(r.Body) if err != nil { return "" } + return string(jsonOutput) } -// YAML marshals the type into YAML format +// YAML marshals the type into YAML format. func (r *Response) YAML() string { yamlOutput, err := yaml.Marshal(r.Body) if err != nil { return "" } + return string(yamlOutput) } diff --git a/pkg/wsman/amt/boot/settingdata.go b/pkg/wsman/amt/boot/settingdata.go index 600d12cc..dfe0b3c3 100644 --- a/pkg/wsman/amt/boot/settingdata.go +++ b/pkg/wsman/amt/boot/settingdata.go @@ -13,50 +13,56 @@ import ( "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/client" ) -// Instantiates a new Boot Setting Data service +// Instantiates a new Boot Setting Data service. func NewBootSettingDataWithClient(wsmanMessageCreator *message.WSManMessageCreator, client client.WSMan) SettingData { return SettingData{ - base: message.NewBaseWithClient(wsmanMessageCreator, AMT_BootSettingData, client), + base: message.NewBaseWithClient(wsmanMessageCreator, AMTBootSettingData, client), } } -// Get retrieves the representation of the instance +// Get retrieves the representation of the instance. func (settingData SettingData) Get() (response Response, err error) { response = Response{ Message: &client.Message{ XMLInput: settingData.base.Get(nil), }, } + // send the message to AMT err = settingData.base.Execute(response.Message) if err != nil { return } + // put the xml response into the go struct err = xml.Unmarshal([]byte(response.XMLOutput), &response) if err != nil { return } + return } -// Enumerate returns an enumeration context which is used in a subsequent Pull call +// Enumerate returns an enumeration context which is used in a subsequent Pull call. func (settingData SettingData) Enumerate() (response Response, err error) { response = Response{ Message: &client.Message{ XMLInput: settingData.base.Enumerate(), }, } + // send the message to AMT err = settingData.base.Execute(response.Message) if err != nil { return } + // put the xml response into the go struct err = xml.Unmarshal([]byte(response.XMLOutput), &response) if err != nil { return } + return } @@ -67,36 +73,42 @@ func (settingData SettingData) Pull(enumerationContext string) (response Respons XMLInput: settingData.base.Pull(enumerationContext), }, } + // send the message to AMT err = settingData.base.Execute(response.Message) if err != nil { return } + // put the xml response into the go struct err = xml.Unmarshal([]byte(response.XMLOutput), &response) if err != nil { return } + return } -// Put will change properties of the selected instance +// Put will change properties of the selected instance. func (settingData SettingData) Put(bootSettingData BootSettingDataRequest) (response Response, err error) { - bootSettingData.H = fmt.Sprintf("%s%s", message.AMTSchema, AMT_BootSettingData) + bootSettingData.H = fmt.Sprintf("%s%s", message.AMTSchema, AMTBootSettingData) response = Response{ Message: &client.Message{ XMLInput: settingData.base.Put(bootSettingData, false, nil), }, } + // send the message to AMT err = settingData.base.Execute(response.Message) if err != nil { return } + // put the xml response into the go struct err = xml.Unmarshal([]byte(response.XMLOutput), &response) if err != nil { return } + return } diff --git a/pkg/wsman/amt/boot/settingdata_test.go b/pkg/wsman/amt/boot/settingdata_test.go index 4f85701c..7411e675 100644 --- a/pkg/wsman/amt/boot/settingdata_test.go +++ b/pkg/wsman/amt/boot/settingdata_test.go @@ -9,20 +9,21 @@ import ( "encoding/xml" "testing" - "github.com/stretchr/testify/assert" - "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/internal/message" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/common" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/wsmantesting" + "github.com/stretchr/testify/assert" ) func TestPositiveAMT_BootSettingData(t *testing.T) { messageID := 0 - resourceUriBase := "http://intel.com/wbem/wscim/1/amt-schema/1/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.AMTResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) + client := wsmantesting.MockClient{ PackageUnderTest: "amt/boot/settingdata", } + elementUnderTest := NewBootSettingDataWithClient(wsmanMessageCreator, &client) t.Run("amt_BootSettingData Tests", func(t *testing.T) { @@ -34,14 +35,15 @@ func TestPositiveAMT_BootSettingData(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //GETS + // GETS { "should create a valid AMT_BootSettingData Get wsman message", - AMT_BootSettingData, - wsmantesting.GET, + AMTBootSettingData, + wsmantesting.Get, "", func() (Response, error) { - client.CurrentMessage = "Get" + client.CurrentMessage = wsmantesting.CurrentMessageGet + return elementUnderTest.Get() }, Body{ @@ -83,14 +85,15 @@ func TestPositiveAMT_BootSettingData(t *testing.T) { }, }, }, - //ENUMERATES + // ENUMERATES { "should create a valid AMT_BootSettingData Enumerate wsman message", - AMT_BootSettingData, - wsmantesting.ENUMERATE, - wsmantesting.ENUMERATE_BODY, + AMTBootSettingData, + wsmantesting.Enumerate, + wsmantesting.EnumerateBody, func() (Response, error) { - client.CurrentMessage = "Enumerate" + client.CurrentMessage = wsmantesting.CurrentMessageEnumerate + return elementUnderTest.Enumerate() }, Body{ @@ -100,14 +103,15 @@ func TestPositiveAMT_BootSettingData(t *testing.T) { }, }, }, - //PULLS + // PULLS { "should create a valid AMT_BootSettingData Pull wsman message", - AMT_BootSettingData, - wsmantesting.PULL, - wsmantesting.PULL_BODY, + AMTBootSettingData, + wsmantesting.Pull, + wsmantesting.PullBody, func() (Response, error) { - client.CurrentMessage = "Pull" + client.CurrentMessage = wsmantesting.CurrentMessagePull + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -158,7 +162,7 @@ func TestPositiveAMT_BootSettingData(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, "", test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, "", test.body) messageID++ response, err := test.responseFunc() assert.NoError(t, err) @@ -171,8 +175,8 @@ func TestPositiveAMT_BootSettingData(t *testing.T) { func TestNegativeAMT_BootSettingData(t *testing.T) { messageID := 0 - resourceUriBase := "http://intel.com/wbem/wscim/1/amt-schema/1/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.AMTResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "amt/boot/settingdata", } @@ -187,14 +191,15 @@ func TestNegativeAMT_BootSettingData(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //GETS + // GETS { "should create a valid AMT_BootSettingData Get wsman message", - AMT_BootSettingData, - wsmantesting.GET, + AMTBootSettingData, + wsmantesting.Get, "", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Get() }, Body{ @@ -237,14 +242,15 @@ func TestNegativeAMT_BootSettingData(t *testing.T) { }, }, }, - //ENUMERATES + // ENUMERATES { "should create a valid AMT_BootSettingData Enumerate wsman message", - AMT_BootSettingData, - wsmantesting.ENUMERATE, - wsmantesting.ENUMERATE_BODY, + AMTBootSettingData, + wsmantesting.Enumerate, + wsmantesting.EnumerateBody, func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Enumerate() }, Body{ @@ -254,14 +260,15 @@ func TestNegativeAMT_BootSettingData(t *testing.T) { }, }, }, - //PULLS + // PULLS { "should create a valid AMT_BootSettingData Pull wsman message", - AMT_BootSettingData, - wsmantesting.PULL, - wsmantesting.PULL_BODY, + AMTBootSettingData, + wsmantesting.Pull, + wsmantesting.PullBody, func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -303,7 +310,8 @@ func TestNegativeAMT_BootSettingData(t *testing.T) { UEFIBootParametersArray: []int{0}, UEFIBootNumberOfParams: 0, RPEEnabled: false, - PlatformErase: false}, + PlatformErase: false, + }, }, }, }, @@ -312,7 +320,7 @@ func TestNegativeAMT_BootSettingData(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, "", test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, "", test.body) messageID++ response, err := test.responseFunc() assert.Error(t, err) diff --git a/pkg/wsman/amt/boot/types.go b/pkg/wsman/amt/boot/types.go index 7d2f97c2..1cd6432f 100644 --- a/pkg/wsman/amt/boot/types.go +++ b/pkg/wsman/amt/boot/types.go @@ -22,7 +22,7 @@ type Capabilities struct { } // OUTPUTS -// Response Types +// Response Types. type ( Response struct { *client.Message @@ -116,7 +116,7 @@ type ( ) // INPUTS -// Request Types +// Request Types. type BootSettingDataRequest struct { XMLName xml.Name `xml:"h:AMT_BootSettingData"` H string `xml:"xmlns:h,attr"` @@ -151,12 +151,12 @@ type BootSettingDataRequest struct { // // ValueMap={0, 1, 2, 3} // -// Values={System default, Quiet - minimal screen activity, Verbose - all messages appear on the screen, Screen blank - no messages appear on the screen} +// Values={System default, Quiet - minimal screen activity, Verbose - all messages appear on the screen, Screen blank - no messages appear on the screen}. type FirmwareVerbosity int // Specifies the device to use when UseIder is set. 0 - Floppy Boot, 1- CD Boot. // // ValueMap={0, 1} // -// Values={Floppy Boot, CD Boot} +// Values={Floppy Boot, CD Boot}. type IDERBootDevice int diff --git a/pkg/wsman/amt/environmentdetection/decoder.go b/pkg/wsman/amt/environmentdetection/decoder.go index 04c61df2..b7df8386 100644 --- a/pkg/wsman/amt/environmentdetection/decoder.go +++ b/pkg/wsman/amt/environmentdetection/decoder.go @@ -5,9 +5,9 @@ package environmentdetection -// INPUTS Constants +// INPUTS Constants. const ( - AMT_EnvironmentDetectionSettingData string = "AMT_EnvironmentDetectionSettingData" + AMTEnvironmentDetectionSettingData string = "AMT_EnvironmentDetectionSettingData" ) const ( @@ -15,13 +15,13 @@ const ( RemoteURLs ) -// DetectionAlgorithmToString is a map of DetectionAlgorithm values to their string representations +// DetectionAlgorithmToString is a map of DetectionAlgorithm values to their string representations. var detectionAlgorithmToString = map[DetectionAlgorithm]string{ LocalDomains: "LocalDomains", RemoteURLs: "RemoteURLs", } -// String returns the string representation of the DetectionAlgorithm value +// String returns the string representation of the DetectionAlgorithm value. func (d DetectionAlgorithm) String() string { if value, exists := detectionAlgorithmToString[d]; exists { return value diff --git a/pkg/wsman/amt/environmentdetection/marshal.go b/pkg/wsman/amt/environmentdetection/marshal.go index 49c4102b..eaeb7ccf 100644 --- a/pkg/wsman/amt/environmentdetection/marshal.go +++ b/pkg/wsman/amt/environmentdetection/marshal.go @@ -11,20 +11,22 @@ import ( "gopkg.in/yaml.v3" ) -// JSON marshals the type into JSON format +// JSON marshals the type into JSON format. func (r *Response) JSON() string { jsonOutput, err := json.Marshal(r.Body) if err != nil { return "" } + return string(jsonOutput) } -// YAML marshals the type into YAML format +// YAML marshals the type into YAML format. func (r *Response) YAML() string { yamlOutput, err := yaml.Marshal(r.Body) if err != nil { return "" } + return string(yamlOutput) } diff --git a/pkg/wsman/amt/environmentdetection/settingdata.go b/pkg/wsman/amt/environmentdetection/settingdata.go index 79286648..cd6ecbac 100644 --- a/pkg/wsman/amt/environmentdetection/settingdata.go +++ b/pkg/wsman/amt/environmentdetection/settingdata.go @@ -14,14 +14,14 @@ import ( "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/client" ) -// NewEnvironmentDetectionSettingDataWithClient instantiates a new Environment Detection Setting Data service +// NewEnvironmentDetectionSettingDataWithClient instantiates a new Environment Detection Setting Data service. func NewEnvironmentDetectionSettingDataWithClient(wsmanMessageCreator *message.WSManMessageCreator, client client.WSMan) SettingData { return SettingData{ - base: message.NewBaseWithClient(wsmanMessageCreator, AMT_EnvironmentDetectionSettingData, client), + base: message.NewBaseWithClient(wsmanMessageCreator, AMTEnvironmentDetectionSettingData, client), } } -// Get retrieves the representation of the instance +// Get retrieves the representation of the instance. func (sd SettingData) Get() (response Response, err error) { response = Response{ Message: &client.Message{ @@ -38,10 +38,11 @@ func (sd SettingData) Get() (response Response, err error) { if err != nil { return } + return } -// Enumerate returns an enumeration context which is used in a subsequent Pull call +// Enumerate returns an enumeration context which is used in a subsequent Pull call. func (sd SettingData) Enumerate() (response Response, err error) { response = Response{ Message: &client.Message{ @@ -58,6 +59,7 @@ func (sd SettingData) Enumerate() (response Response, err error) { if err != nil { return } + return } @@ -78,12 +80,13 @@ func (sd SettingData) Pull(enumerationContext string) (response Response, err er if err != nil { return } + return } -// Put will change properties of the selected instance +// Put will change properties of the selected instance. func (sd SettingData) Put(environmentDetectionSettingData EnvironmentDetectionSettingDataRequest) (response Response, err error) { - environmentDetectionSettingData.H = fmt.Sprintf("%s%s", message.AMTSchema, AMT_EnvironmentDetectionSettingData) + environmentDetectionSettingData.H = fmt.Sprintf("%s%s", message.AMTSchema, AMTEnvironmentDetectionSettingData) selector := message.Selector{ Name: "InstanceID", Value: "Intel(r) AMT Environment Detection Settings", @@ -103,5 +106,6 @@ func (sd SettingData) Put(environmentDetectionSettingData EnvironmentDetectionSe if err != nil { return } + return } diff --git a/pkg/wsman/amt/environmentdetection/settingdata_test.go b/pkg/wsman/amt/environmentdetection/settingdata_test.go index 0e94eba0..18b559aa 100644 --- a/pkg/wsman/amt/environmentdetection/settingdata_test.go +++ b/pkg/wsman/amt/environmentdetection/settingdata_test.go @@ -12,6 +12,7 @@ import ( "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/internal/message" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/common" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/wsmantesting" + "github.com/sirupsen/logrus" "github.com/stretchr/testify/assert" ) @@ -21,7 +22,7 @@ func TestJson(t *testing.T) { GetAndPutResponse: EnvironmentDetectionSettingDataResponse{}, }, } - expectedResult := "{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"GetAndPutResponse\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"ElementName\":\"\",\"InstanceID\":\"\",\"DetectionAlgorithm\":0,\"DetectionStrings\":null,\"DetectionIPv6LocalPrefixes\":null},\"EnumerateResponse\":{\"EnumerationContext\":\"\"},\"PullResponse\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"EnvironmentDetectionSettingDataItems\":null}}" + expectedResult := "{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"GetAndPutResponse\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"ElementName\":\"\",\"InstanceID\":\"\",\"DetectionAlgorithm\":0,\"DetectionStrings\":null,\"DetectionIPv6LocalPrefixes\":null},\"EnumerateResponse\":{\"EnumerationContext\":\"\"},\"PullResponse\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"SettingDataItems\":null}}" result := response.JSON() assert.Equal(t, expectedResult, result) } @@ -32,19 +33,20 @@ func TestYaml(t *testing.T) { GetAndPutResponse: EnvironmentDetectionSettingDataResponse{}, }, } - expectedResult := "xmlname:\n space: \"\"\n local: \"\"\ngetandputresponse:\n xmlname:\n space: \"\"\n local: \"\"\n elementname: \"\"\n instanceid: \"\"\n detectionalgorithm: 0\n detectionstrings: []\n detectionipv6localprefixes: []\nenumerateresponse:\n enumerationcontext: \"\"\npullresponse:\n xmlname:\n space: \"\"\n local: \"\"\n environmentdetectionsettingdataitems: []\n" + expectedResult := "xmlname:\n space: \"\"\n local: \"\"\ngetandputresponse:\n xmlname:\n space: \"\"\n local: \"\"\n elementname: \"\"\n instanceid: \"\"\n detectionalgorithm: 0\n detectionstrings: []\n detectionipv6localprefixes: []\nenumerateresponse:\n enumerationcontext: \"\"\npullresponse:\n xmlname:\n space: \"\"\n local: \"\"\n settingdataitems: []\n" result := response.YAML() assert.Equal(t, expectedResult, result) } func TestPositiveAMT_EnvironmentDetectionSettingData(t *testing.T) { messageID := 0 - resourceUriBase := "http://intel.com/wbem/wscim/1/amt-schema/1/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.AMTResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "amt/environmentdetection", } elementUnderTest := NewEnvironmentDetectionSettingDataWithClient(wsmanMessageCreator, &client) + t.Run("amt_EnvironmentDetectionSettingData Tests", func(t *testing.T) { tests := []struct { name string @@ -55,15 +57,16 @@ func TestPositiveAMT_EnvironmentDetectionSettingData(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //GETS + // GETS { "should create a valid AMT_EnvironmentDetectionSettingData Get wsman message", - AMT_EnvironmentDetectionSettingData, - wsmantesting.GET, + AMTEnvironmentDetectionSettingData, + wsmantesting.Get, "", "", func() (Response, error) { - client.CurrentMessage = "Get" + client.CurrentMessage = wsmantesting.CurrentMessageGet + return elementUnderTest.Get() }, Body{ @@ -77,18 +80,19 @@ func TestPositiveAMT_EnvironmentDetectionSettingData(t *testing.T) { }, }, }, - //ENUMERATES + // ENUMERATES { "should create a valid AMT_EnvironmentDetectionSettingData Enumerate wsman message", - AMT_EnvironmentDetectionSettingData, - wsmantesting.ENUMERATE, + AMTEnvironmentDetectionSettingData, + wsmantesting.Enumerate, "", - wsmantesting.ENUMERATE_BODY, + wsmantesting.EnumerateBody, func() (Response, error) { - client.CurrentMessage = "Enumerate" + client.CurrentMessage = wsmantesting.CurrentMessageEnumerate if elementUnderTest.base.WSManMessageCreator == nil { - print("Error") + logrus.Println("Error") } + return elementUnderTest.Enumerate() }, Body{ @@ -98,15 +102,16 @@ func TestPositiveAMT_EnvironmentDetectionSettingData(t *testing.T) { }, }, }, - //PULLS + // PULLS { "should create a valid AMT_EnvironmentDetectionSettingData Pull wsman message", - AMT_EnvironmentDetectionSettingData, - wsmantesting.PULL, + AMTEnvironmentDetectionSettingData, + wsmantesting.Pull, "", - wsmantesting.PULL_BODY, + wsmantesting.PullBody, func() (Response, error) { - client.CurrentMessage = "Pull" + client.CurrentMessage = wsmantesting.CurrentMessagePull + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -125,15 +130,15 @@ func TestPositiveAMT_EnvironmentDetectionSettingData(t *testing.T) { }, }, }, - //PUT + // PUT { "should create a valid AMT_EnvironmentDetectionSettingData Put wsman message", - AMT_EnvironmentDetectionSettingData, - wsmantesting.PUT, + AMTEnvironmentDetectionSettingData, + wsmantesting.Put, "Intel(r) AMT Environment Detection Settings", "Intel(r) AMT Environment Detection SettingsIntel(r) AMT Environment Detection Settings02b14eacc-7f20-4a11-99bc-fdc6a162160b.com", func() (Response, error) { - client.CurrentMessage = "Put" + client.CurrentMessage = wsmantesting.CurrentMessagePut edsd := EnvironmentDetectionSettingDataRequest{ H: "http://intel.com/wbem/wscim/1/amt-schema/1/AMT_EnvironmentDetectionSettingData", ElementName: "Intel(r) AMT Environment Detection Settings", @@ -141,6 +146,7 @@ func TestPositiveAMT_EnvironmentDetectionSettingData(t *testing.T) { DetectionAlgorithm: 0, DetectionStrings: []string{"2b14eacc-7f20-4a11-99bc-fdc6a162160b.com"}, } + return elementUnderTest.Put(edsd) }, Body{ @@ -157,7 +163,7 @@ func TestPositiveAMT_EnvironmentDetectionSettingData(t *testing.T) { } for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, test.extraHeader, test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, test.extraHeader, test.body) messageID++ response, err := test.responseFunc() assert.NoError(t, err) @@ -167,14 +173,16 @@ func TestPositiveAMT_EnvironmentDetectionSettingData(t *testing.T) { } }) } + func TestNegativeAMT_EnvironmentDetectionSettingData(t *testing.T) { messageID := 0 - resourceUriBase := "http://intel.com/wbem/wscim/1/amt-schema/1/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.AMTResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "amt/environmentdetection", } elementUnderTest := NewEnvironmentDetectionSettingDataWithClient(wsmanMessageCreator, &client) + t.Run("amt_EnvironmentDetectionSettingData Tests", func(t *testing.T) { tests := []struct { name string @@ -185,15 +193,16 @@ func TestNegativeAMT_EnvironmentDetectionSettingData(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //GETS + // GETS { "should create a valid AMT_EnvironmentDetectionSettingData Get wsman message", - AMT_EnvironmentDetectionSettingData, - wsmantesting.GET, + AMTEnvironmentDetectionSettingData, + wsmantesting.Get, "", "", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Get() }, Body{ @@ -207,18 +216,19 @@ func TestNegativeAMT_EnvironmentDetectionSettingData(t *testing.T) { }, }, }, - //ENUMERATES + // ENUMERATES { "should create a valid AMT_EnvironmentDetectionSettingData Enumerate wsman message", - AMT_EnvironmentDetectionSettingData, - wsmantesting.ENUMERATE, + AMTEnvironmentDetectionSettingData, + wsmantesting.Enumerate, "", - wsmantesting.ENUMERATE_BODY, + wsmantesting.EnumerateBody, func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError if elementUnderTest.base.WSManMessageCreator == nil { - print("Error") + logrus.Print("Error") } + return elementUnderTest.Enumerate() }, Body{ @@ -228,15 +238,16 @@ func TestNegativeAMT_EnvironmentDetectionSettingData(t *testing.T) { }, }, }, - //PULLS + // PULLS { "should create a valid AMT_EnvironmentDetectionSettingData Pull wsman message", - AMT_EnvironmentDetectionSettingData, - wsmantesting.PULL, + AMTEnvironmentDetectionSettingData, + wsmantesting.Pull, "", - wsmantesting.PULL_BODY, + wsmantesting.PullBody, func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -255,15 +266,15 @@ func TestNegativeAMT_EnvironmentDetectionSettingData(t *testing.T) { }, }, }, - //PUT + // PUT { "should create a valid AMT_EnvironmentDetectionSettingData Put wsman message", - AMT_EnvironmentDetectionSettingData, - wsmantesting.PUT, + AMTEnvironmentDetectionSettingData, + wsmantesting.Put, "Intel(r) AMT Environment Detection Settings", "Intel(r) AMT Environment Detection SettingsIntel(r) AMT Environment Detection Settings02b14eacc-7f20-4a11-99bc-fdc6a162160b.com", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError edsd := EnvironmentDetectionSettingDataRequest{ H: "http://intel.com/wbem/wscim/1/amt-schema/1/AMT_EnvironmentDetectionSettingData", ElementName: "Intel(r) AMT Environment Detection Settings", @@ -271,6 +282,7 @@ func TestNegativeAMT_EnvironmentDetectionSettingData(t *testing.T) { DetectionAlgorithm: 0, DetectionStrings: []string{"2b14eacc-7f20-4a11-99bc-fdc6a162160b.com"}, } + return elementUnderTest.Put(edsd) }, Body{ @@ -287,7 +299,7 @@ func TestNegativeAMT_EnvironmentDetectionSettingData(t *testing.T) { } for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, test.extraHeader, test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, test.extraHeader, test.body) messageID++ response, err := test.responseFunc() assert.Error(t, err) diff --git a/pkg/wsman/amt/environmentdetection/types.go b/pkg/wsman/amt/environmentdetection/types.go index 29f60a9d..b0517a9d 100644 --- a/pkg/wsman/amt/environmentdetection/types.go +++ b/pkg/wsman/amt/environmentdetection/types.go @@ -18,7 +18,7 @@ type SettingData struct { } // OUTPUTS -// Response Types +// Response Types. type ( Response struct { *client.Message @@ -48,7 +48,7 @@ type ( ) // INPUTS -// Request Types +// Request Types. type EnvironmentDetectionSettingDataRequest struct { XMLName xml.Name `xml:"h:AMT_EnvironmentDetectionSettingData"` H string `xml:"xmlns:h,attr"` @@ -65,5 +65,5 @@ type EnvironmentDetectionSettingDataRequest struct { // // ValueMap={0, 1} // -// Values={Local Domains, Remote URLs} +// Values={Local Domains, Remote URLs}. type DetectionAlgorithm int diff --git a/pkg/wsman/amt/ethernetport/decoder.go b/pkg/wsman/amt/ethernetport/decoder.go index 9defdbf0..8f53e5e8 100644 --- a/pkg/wsman/amt/ethernetport/decoder.go +++ b/pkg/wsman/amt/ethernetport/decoder.go @@ -6,13 +6,14 @@ package ethernetport const ( - AMT_EthernetPortSettings string = "AMT_EthernetPortSettings" + AMTEthernetPortSettings string = "AMT_EthernetPortSettings" + ValueNotFound string = "Value not found in map" ) const ( - ConsoleTcpMaxRetransmissions_5 ConsoleTcpMaxRetransmissions = iota + 5 - ConsoleTcpMaxRetransmissions_6 - ConsoleTcpMaxRetransmissions_7 + ConsoleTCPMaxRetransmissions5 ConsoleTCPMaxRetransmissions = iota + 5 + ConsoleTCPMaxRetransmissions6 + ConsoleTCPMaxRetransmissions7 ) const ( @@ -22,7 +23,7 @@ const ( LinkPolicySxDC LinkPolicy = 224 // available on Sx DC ) -// linkPolicyToString is a map of LinkPolicy values to their string representations +// linkPolicyToString is a map of LinkPolicy values to their string representations. var linkPolicyToString = map[LinkPolicy]string{ LinkPolicyS0AC: "LinkPolicyS0AC", LinkPolicySxAC: "LinkPolicySxAC", @@ -30,13 +31,13 @@ var linkPolicyToString = map[LinkPolicy]string{ LinkPolicySxDC: "LinkPolicySxDC", } -// String returns the string representation of the LinkPolicy value +// String returns the string representation of the LinkPolicy value. func (l LinkPolicy) String() string { if value, exists := linkPolicyToString[l]; exists { return value } - return "Value not found in map" + return ValueNotFound } const ( @@ -44,19 +45,19 @@ const ( LinkPreferenceHOST ) -// linkPreferenceToString is a map of LinkPreference values to their string representations +// linkPreferenceToString is a map of LinkPreference values to their string representations. var linkPreferenceToString = map[LinkPreference]string{ LinkPreferenceME: "LinkPreferenceME", LinkPreferenceHOST: "LinkPreferenceHOST", } -// String returns the string representation of the LinkPreference value +// String returns the string representation of the LinkPreference value. func (l LinkPreference) String() string { if value, exists := linkPreferenceToString[l]; exists { return value } - return "Value not found in map" + return ValueNotFound } const ( @@ -64,19 +65,19 @@ const ( LinkControlHOST ) -// linkControlToString is a map of LinkControl values to their string representations +// linkControlToString is a map of LinkControl values to their string representations. var linkControlToString = map[LinkControl]string{ LinkControlME: "LinkControlME", LinkControlHOST: "LinkControlHOST", } -// String returns the string representation of the LinkControl value +// String returns the string representation of the LinkControl value. func (l LinkControl) String() string { if value, exists := linkControlToString[l]; exists { return value } - return "Value not found in map" + return ValueNotFound } const ( @@ -86,7 +87,7 @@ const ( WLANLinkProtectionLevelHigh ) -// wlanLinkProtectionLevelToString is a map of WLANLinkProtectionLevel values to their string representations +// wlanLinkProtectionLevelToString is a map of WLANLinkProtectionLevel values to their string representations. var wlanLinkProtectionLevelToString = map[WLANLinkProtectionLevel]string{ WLANLinkProtectionLevelOverride: "WLANLinkProtectionLevelOverride", WLANLinkProtectionLevelNone: "WLANLinkProtectionLevelNone", @@ -94,13 +95,13 @@ var wlanLinkProtectionLevelToString = map[WLANLinkProtectionLevel]string{ WLANLinkProtectionLevelHigh: "WLANLinkProtectionLevelHigh", } -// String returns the string representation of the WLANLinkProtectionLevel value +// String returns the string representation of the WLANLinkProtectionLevel value. func (w WLANLinkProtectionLevel) String() string { if value, exists := wlanLinkProtectionLevelToString[w]; exists { return value } - return "Value not found in map" + return ValueNotFound } const ( @@ -110,7 +111,7 @@ const ( PhysicalConnectionWirelessLAN ) -// PhysicalConnectionTypeToString is a map of PhysicalConnectionType values to their string representations +// PhysicalConnectionTypeToString is a map of PhysicalConnectionType values to their string representations. var PhysicalConnectionTypeToString = map[PhysicalConnectionType]string{ PhysicalConnectionIntegratedLANNIC: "PhysicalConnectionIntegratedLANNIC", PhysicalConnectionDiscreteLANNIC: "PhysicalConnectionDiscreteLANNIC", @@ -118,13 +119,13 @@ var PhysicalConnectionTypeToString = map[PhysicalConnectionType]string{ PhysicalConnectionWirelessLAN: "PhysicalConnectionWirelessLAN", } -// String returns the string representation of the PhysicalConnectionType value +// String returns the string representation of the PhysicalConnectionType value. func (p PhysicalConnectionType) String() string { if value, exists := PhysicalConnectionTypeToString[p]; exists { return value } - return "Value not found in map" + return ValueNotFound } const ( @@ -132,17 +133,17 @@ const ( PhysicalNicMediumPCIe ) -// PhysicalNicMediumToString is a map of PhysicalNicMedium values to their string representations +// PhysicalNicMediumToString is a map of PhysicalNicMedium values to their string representations. var PhysicalNicMediumToString = map[PhysicalNicMedium]string{ PhysicalNicMediumSMBUS: "PhysicalNicMediumSMBUS", PhysicalNicMediumPCIe: "PhysicalNicMediumPCIe", } -// String returns the string representation of the PhysicalNicMedium value +// String returns the string representation of the PhysicalNicMedium value. func (p PhysicalNicMedium) String() string { if value, exists := PhysicalNicMediumToString[p]; exists { return value } - return "Value not found in map" + return ValueNotFound } diff --git a/pkg/wsman/amt/ethernetport/marshal.go b/pkg/wsman/amt/ethernetport/marshal.go index 4024a40f..0d2e12eb 100644 --- a/pkg/wsman/amt/ethernetport/marshal.go +++ b/pkg/wsman/amt/ethernetport/marshal.go @@ -11,20 +11,22 @@ import ( "gopkg.in/yaml.v3" ) -// JSON marshals the type into JSON format +// JSON marshals the type into JSON format. func (r *Response) JSON() string { jsonOutput, err := json.Marshal(r.Body) if err != nil { return "" } + return string(jsonOutput) } -// YAML marshals the type into YAML format +// YAML marshals the type into YAML format. func (r *Response) YAML() string { yamlOutput, err := yaml.Marshal(r.Body) if err != nil { return "" } + return string(yamlOutput) } diff --git a/pkg/wsman/amt/ethernetport/settings.go b/pkg/wsman/amt/ethernetport/settings.go index c6fcd649..815da701 100644 --- a/pkg/wsman/amt/ethernetport/settings.go +++ b/pkg/wsman/amt/ethernetport/settings.go @@ -16,14 +16,14 @@ import ( "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/client" ) -// NewEthernetPortSettingsWithClient instantiates a new Ethernet Port Settings service +// NewEthernetPortSettingsWithClient instantiates a new Ethernet Port Settings service. func NewEthernetPortSettingsWithClient(wsmanMessageCreator *message.WSManMessageCreator, client client.WSMan) Settings { return Settings{ - base: message.NewBaseWithClient(wsmanMessageCreator, AMT_EthernetPortSettings, client), + base: message.NewBaseWithClient(wsmanMessageCreator, AMTEthernetPortSettings, client), } } -// Get retrieves the representation of the instance +// Get retrieves the representation of the instance. func (s Settings) Get(instanceID string) (response Response, err error) { selector := message.Selector{ Name: "InstanceID", @@ -44,10 +44,11 @@ func (s Settings) Get(instanceID string) (response Response, err error) { if err != nil { return } + return } -// Enumerate returns an enumeration context which is used in a subsequent Pull call +// Enumerate returns an enumeration context which is used in a subsequent Pull call. func (s Settings) Enumerate() (response Response, err error) { response = Response{ Message: &client.Message{ @@ -64,6 +65,7 @@ func (s Settings) Enumerate() (response Response, err error) { if err != nil { return } + return } @@ -84,15 +86,16 @@ func (s Settings) Pull(enumerationContext string) (response Response, err error) if err != nil { return } + return } -// Put will change properties of the selected instance -func (s Settings) Put(instanceId string, ethernetPortSettings SettingsRequest) (response Response, err error) { - ethernetPortSettings.H = fmt.Sprintf("%s%s", message.AMTSchema, AMT_EthernetPortSettings) +// Put will change properties of the selected instance. +func (s Settings) Put(instanceID string, ethernetPortSettings SettingsRequest) (response Response, err error) { + ethernetPortSettings.H = fmt.Sprintf("%s%s", message.AMTSchema, AMTEthernetPortSettings) selector := message.Selector{ Name: "InstanceID", - Value: instanceId, + Value: instanceID, } response = Response{ Message: &client.Message{ @@ -110,5 +113,6 @@ func (s Settings) Put(instanceId string, ethernetPortSettings SettingsRequest) ( if err != nil { return } + return } diff --git a/pkg/wsman/amt/ethernetport/settings_test.go b/pkg/wsman/amt/ethernetport/settings_test.go index 2ab1d168..6960b3b9 100644 --- a/pkg/wsman/amt/ethernetport/settings_test.go +++ b/pkg/wsman/amt/ethernetport/settings_test.go @@ -21,7 +21,7 @@ func TestJson(t *testing.T) { GetAndPutResponse: SettingsResponse{}, }, } - expectedResult := "{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"GetAndPutResponse\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"ElementName\":\"\",\"InstanceID\":\"\",\"VLANTag\":0,\"SharedMAC\":false,\"MACAddress\":\"\",\"LinkIsUp\":false,\"LinkPolicy\":null,\"LinkPreference\":0,\"LinkControl\":0,\"SharedStaticIp\":false,\"SharedDynamicIP\":false,\"IpSyncEnabled\":false,\"DHCPEnabled\":false,\"IPAddress\":\"\",\"SubnetMask\":\"\",\"DefaultGateway\":\"\",\"PrimaryDNS\":\"\",\"SecondaryDNS\":\"\",\"ConsoleTcpMaxRetransmissions\":0,\"WLANLinkProtectionLevel\":0,\"PhysicalConnectionType\":0,\"PhysicalNicMedium\":0},\"EnumerateResponse\":{\"EnumerationContext\":\"\"},\"PullResponse\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"EthernetPortItems\":null}}" + expectedResult := "{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"GetAndPutResponse\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"ElementName\":\"\",\"InstanceID\":\"\",\"VLANTag\":0,\"SharedMAC\":false,\"MACAddress\":\"\",\"LinkIsUp\":false,\"LinkPolicy\":null,\"LinkPreference\":0,\"LinkControl\":0,\"SharedStaticIP\":false,\"SharedDynamicIP\":false,\"IPSyncEnabled\":false,\"DHCPEnabled\":false,\"IPAddress\":\"\",\"SubnetMask\":\"\",\"DefaultGateway\":\"\",\"PrimaryDNS\":\"\",\"SecondaryDNS\":\"\",\"ConsoleTCPMaxRetransmissions\":0,\"WLANLinkProtectionLevel\":0,\"PhysicalConnectionType\":0,\"PhysicalNicMedium\":0},\"EnumerateResponse\":{\"EnumerationContext\":\"\"},\"PullResponse\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"EthernetPortItems\":null}}" result := response.JSON() assert.Equal(t, expectedResult, result) } @@ -39,12 +39,13 @@ func TestYaml(t *testing.T) { func TestPositiveAMT_EthernetPortSettings(t *testing.T) { messageID := 0 - resourceUriBase := "http://intel.com/wbem/wscim/1/amt-schema/1/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.AMTResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "amt/ethernetport", } elementUnderTest := NewEthernetPortSettingsWithClient(wsmanMessageCreator, &client) + t.Run("amt_EthernetPortSettings Tests", func(t *testing.T) { tests := []struct { name string @@ -55,15 +56,16 @@ func TestPositiveAMT_EthernetPortSettings(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //GETS + // GETS { "should create a valid AMT_EthernetPortSettings Get wsman message", - AMT_EthernetPortSettings, - wsmantesting.GET, + AMTEthernetPortSettings, + wsmantesting.Get, "", "Intel(r) AMT Ethernet Port Settings 0", func() (Response, error) { - client.CurrentMessage = "Get" + client.CurrentMessage = wsmantesting.CurrentMessageGet + return elementUnderTest.Get("Intel(r) AMT Ethernet Port Settings 0") }, Body{ @@ -89,15 +91,16 @@ func TestPositiveAMT_EthernetPortSettings(t *testing.T) { }, }, - //ENUMERATES + // ENUMERATES { "should create a valid AMT_EthernetPortSettings Enumerate wsman message", - AMT_EthernetPortSettings, - wsmantesting.ENUMERATE, - wsmantesting.ENUMERATE_BODY, + AMTEthernetPortSettings, + wsmantesting.Enumerate, + wsmantesting.EnumerateBody, "", func() (Response, error) { - client.CurrentMessage = "Enumerate" + client.CurrentMessage = wsmantesting.CurrentMessageEnumerate + return elementUnderTest.Enumerate() }, Body{ @@ -107,15 +110,16 @@ func TestPositiveAMT_EthernetPortSettings(t *testing.T) { }, }, }, - //PULLS + // PULLS { "should create a valid AMT_EthernetPortSettings Pull wsman message", - AMT_EthernetPortSettings, - wsmantesting.PULL, - wsmantesting.PULL_BODY, + AMTEthernetPortSettings, + wsmantesting.Pull, + wsmantesting.PullBody, "", func() (Response, error) { - client.CurrentMessage = "Pull" + client.CurrentMessage = wsmantesting.CurrentMessagePull + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -159,11 +163,11 @@ func TestPositiveAMT_EthernetPortSettings(t *testing.T) { }, }, }, - //PUTS + // PUTS { "should create a valid AMT_EthernetPortSettings Put wsman message", - AMT_EthernetPortSettings, - wsmantesting.PUT, + AMTEthernetPortSettings, + wsmantesting.Put, "Intel(r) AMT Ethernet Port SettingsIntel(r) AMT Ethernet Port Settings 0truefalsetruetruetrue", "Intel(r) AMT Ethernet Port Settings 0", func() (Response, error) { @@ -176,7 +180,8 @@ func TestPositiveAMT_EthernetPortSettings(t *testing.T) { SharedMAC: true, SharedStaticIp: true, } - client.CurrentMessage = "Put" + client.CurrentMessage = wsmantesting.CurrentMessagePut + return elementUnderTest.Put(ethernetPortSettings.InstanceID, ethernetPortSettings) }, Body{ @@ -206,7 +211,7 @@ func TestPositiveAMT_EthernetPortSettings(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, test.extraHeader, test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, test.extraHeader, test.body) messageID++ response, err := test.responseFunc() assert.NoError(t, err) @@ -219,12 +224,13 @@ func TestPositiveAMT_EthernetPortSettings(t *testing.T) { func TestNegativeAMT_EthernetPortSettings(t *testing.T) { messageID := 0 - resourceUriBase := "http://intel.com/wbem/wscim/1/amt-schema/1/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.AMTResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "amt/ethernetport", } elementUnderTest := NewEthernetPortSettingsWithClient(wsmanMessageCreator, &client) + t.Run("amt_EthernetPortSettings Tests", func(t *testing.T) { tests := []struct { name string @@ -235,15 +241,16 @@ func TestNegativeAMT_EthernetPortSettings(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //GETS + // GETS { "should create a valid AMT_EthernetPortSettings Get wsman message", - AMT_EthernetPortSettings, - wsmantesting.GET, + AMTEthernetPortSettings, + wsmantesting.Get, "", "Intel(r) AMT Ethernet Port Settings 0", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Get("Intel(r) AMT Ethernet Port Settings 0") }, Body{ @@ -269,15 +276,16 @@ func TestNegativeAMT_EthernetPortSettings(t *testing.T) { }, }, - //ENUMERATES + // ENUMERATES { "should create a valid AMT_EthernetPortSettings Enumerate wsman message", - AMT_EthernetPortSettings, - wsmantesting.ENUMERATE, - wsmantesting.ENUMERATE_BODY, + AMTEthernetPortSettings, + wsmantesting.Enumerate, + wsmantesting.EnumerateBody, "", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Enumerate() }, Body{ @@ -287,15 +295,16 @@ func TestNegativeAMT_EthernetPortSettings(t *testing.T) { }, }, }, - //PULLS + // PULLS { "should create a valid AMT_EthernetPortSettings Pull wsman message", - AMT_EthernetPortSettings, - wsmantesting.PULL, - wsmantesting.PULL_BODY, + AMTEthernetPortSettings, + wsmantesting.Pull, + wsmantesting.PullBody, "", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -339,11 +348,11 @@ func TestNegativeAMT_EthernetPortSettings(t *testing.T) { }, }, }, - //PUTS + // PUTS { "should create a valid AMT_EthernetPortSettings Put wsman message", - AMT_EthernetPortSettings, - wsmantesting.PUT, + AMTEthernetPortSettings, + wsmantesting.Put, "Intel(r) AMT Ethernet Port SettingsIntel(r) AMT Ethernet Port Settings 0truefalsetruetruetrue", "Intel(r) AMT Ethernet Port Settings 0", func() (Response, error) { @@ -356,7 +365,8 @@ func TestNegativeAMT_EthernetPortSettings(t *testing.T) { SharedMAC: true, SharedStaticIp: true, } - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Put(ethernetPortSettings.InstanceID, ethernetPortSettings) }, Body{ @@ -386,7 +396,7 @@ func TestNegativeAMT_EthernetPortSettings(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, test.extraHeader, test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, test.extraHeader, test.body) messageID++ response, err := test.responseFunc() assert.Error(t, err) diff --git a/pkg/wsman/amt/ethernetport/types.go b/pkg/wsman/amt/ethernetport/types.go index 823e99d2..d9a6d05f 100644 --- a/pkg/wsman/amt/ethernetport/types.go +++ b/pkg/wsman/amt/ethernetport/types.go @@ -18,7 +18,7 @@ type Settings struct { } // OUTPUTS -// Response Types +// Response Types. type ( Response struct { *client.Message @@ -67,7 +67,7 @@ type ( ) // INPUTS -// Request Types +// Request Types. type SettingsRequest struct { XMLName xml.Name `xml:"h:AMT_EthernetPortSettings"` H string `xml:"xmlns:h,attr"` @@ -86,7 +86,7 @@ type SettingsRequest struct { DefaultGateway string `xml:"h:DefaultGateway,omitempty"` // Default Gateway in a string format. For example: 10.12.232.1 PrimaryDNS string `xml:"h:PrimaryDNS,omitempty"` // Primary DNS in a string format. For example: 10.12.232.1 SecondaryDNS string `xml:"h:SecondaryDNS,omitempty"` // Secondary DNS in a string format. For example: 10.12.232.1 - ConsoleTcpMaxRetransmissions ConsoleTcpMaxRetransmissions `xml:"h:ConsoleTcpMaxRetransmissions,omitempty"` // Indicates the number of retransmissions host TCP SW tries if no ack is accepted + ConsoleTcpMaxRetransmissions ConsoleTCPMaxRetransmissions `xml:"h:ConsoleTcpMaxRetransmissions,omitempty"` // Indicates the number of retransmissions host TCP SW tries if no ack is accepted PhysicalConnectionType PhysicalConnectionType `xml:"h:PhysicalConnectionType,omitempty"` // Indicates the physical connection type of this network interface. Note: Applicable in Intel AMT 15.0 and later. PhysicalNicMedium PhysicalNicMedium `xml:"h:PhysicalNicMedium,omitempty"` // Indicates which medium is currently used by Intel® AMT to communicate with the NIC. Note: Applicable in Intel AMT 15.0 and later. } @@ -95,47 +95,47 @@ type SettingsRequest struct { // // ValueMap={1, 14, 16, 224} // -// Values={available on S0 AC, available on Sx AC, available on S0 DC, available on Sx DC} +// Values={available on S0 AC, available on Sx AC, available on S0 DC, available on Sx DC}. type LinkPolicy int // Indicates the number of retransmissions host TCP SW tries if no ack is accepted // // MinValue=5 // -// MaxValue=7 -type ConsoleTcpMaxRetransmissions int +// MaxValue=7. +type ConsoleTCPMaxRetransmissions int // Determines whether the link is preferred to be owned by ME or host // // ValueMap={1, 2, 3..} // -// Values={ME, HOST, Reserved} +// Values={ME, HOST, Reserved}. type LinkPreference int // Determines whether the link is owned by ME or host. Additional Notes: This property is read-only. // // ValueMap={1, 2, 3..} // -// Values={ME, HOST, Reserved} +// Values={ME, HOST, Reserved}. type LinkControl int // Defines the level of the link protection feature activation. Read only property. // // ValueMap={0, 1, 2, 3, 4..} // -// Values={OVERRIDE, NONE, PASSIVE, HIGH, RESERVED} +// Values={OVERRIDE, NONE, PASSIVE, HIGH, RESERVED}. type WLANLinkProtectionLevel int // Indicates the physical connection type of this network interface. Note: Applicable in Intel AMT 15.0 and later. // // ValueMap={"0", "1", "2", "3", "4.."} // -// Values={"Integrated LAN NIC", "Discrete LAN NIC", "LAN via a Thunderbolt dock", "Wireless LAN", "Reserved"} +// Values={"Integrated LAN NIC", "Discrete LAN NIC", "LAN via a Thunderbolt dock", "Wireless LAN", "Reserved"}. type PhysicalConnectionType int // Indicates which medium is currently used by Intel® AMT to communicate with the NIC. Note: Applicable in Intel AMT 15.0 and later. // // ValueMap={"0", "1", "2.."} // -// Values={"SMBUS", "PCIe", "Reserved"} +// Values={"SMBUS", "PCIe", "Reserved"}. type PhysicalNicMedium int diff --git a/pkg/wsman/amt/general/decoder.go b/pkg/wsman/amt/general/decoder.go index 3bdb0f40..99b84455 100644 --- a/pkg/wsman/amt/general/decoder.go +++ b/pkg/wsman/amt/general/decoder.go @@ -6,7 +6,8 @@ package general const ( - AMT_GeneralSettings string = "AMT_GeneralSettings" + AMTGeneralSettings string = "AMT_GeneralSettings" + ValueNotFound string = "Value not found in map" ) const ( @@ -15,20 +16,20 @@ const ( Extreme ) -// privacyLevelToString is a map of PrivacyLevel to their string representation +// privacyLevelToString is a map of PrivacyLevel to their string representation. var privacyLevelToString = map[PrivacyLevel]string{ Default: "Default", Enhanced: "Enhanced", Extreme: "Extreme", } -// String returns the string representation of the PrivacyLevel value +// String returns the string representation of the PrivacyLevel value. func (p PrivacyLevel) String() string { if value, exists := privacyLevelToString[p]; exists { return value } - return "Value not found in map" + return ValueNotFound } const ( @@ -36,19 +37,19 @@ const ( DC ) -// powerSourceToString is a map of PowerSource to their string representation +// powerSourceToString is a map of PowerSource to their string representation. var powerSourceToString = map[PowerSource]string{ AC: "AC", DC: "DC", } -// String returns the string representation of the PowerSource value +// String returns the string representation of the PowerSource value. func (p PowerSource) String() string { if value, exists := powerSourceToString[p]; exists { return value } - return "Value not found in map" + return ValueNotFound } const ( @@ -56,19 +57,19 @@ const ( IPv6 ) -// preferredAddressFamilyToString is a map of PreferredAddressFamily to their string representation +// preferredAddressFamilyToString is a map of PreferredAddressFamily to their string representation. var preferredAddressFamilyToString = map[PreferredAddressFamily]string{ IPv4: "IPv4", IPv6: "IPv6", } -// String returns the string representation of the PreferredAddressFamily value +// String returns the string representation of the PreferredAddressFamily value. func (p PreferredAddressFamily) String() string { if value, exists := preferredAddressFamilyToString[p]; exists { return value } - return "Value not found in map" + return ValueNotFound } const ( @@ -76,19 +77,19 @@ const ( AMTNetworkEnabled ) -// amtNetworkEnabledToString is a map of FeatureEnabled values to their string representations +// amtNetworkEnabledToString is a map of FeatureEnabled values to their string representations. var amtNetworkEnabledToString = map[AMTNetwork]string{ AMTNetworkDisabled: "Disabled", AMTNetworkEnabled: "Enabled", } -// String returns the string representation of the FeatureEnabled value +// String returns the string representation of the FeatureEnabled value. func (a AMTNetwork) String() string { if value, exists := amtNetworkEnabledToString[a]; exists { return value } - return "Value not found in map" + return ValueNotFound } const ( @@ -96,19 +97,19 @@ const ( ThunderboltDockEnabled ) -// thunderboltDockEnabledToString is a map of FeatureEnabled values to their string representations +// thunderboltDockEnabledToString is a map of FeatureEnabled values to their string representations. var thunderboltDockEnabledToString = map[ThunderboltDock]string{ ThunderboltDockDisabled: "Disabled", ThunderboltDockEnabled: "Enabled", } -// String returns the string representation of the FeatureEnabled value +// String returns the string representation of the FeatureEnabled value. func (t ThunderboltDock) String() string { if value, exists := thunderboltDockEnabledToString[t]; exists { return value } - return "Value not found in map" + return ValueNotFound } const ( @@ -116,17 +117,17 @@ const ( DHCPSyncRequiresHostnameEnabled ) -// dhcpSyncRequiresHostnameToString is a map of DHCPSyncRequiresHostname values to their string representations +// dhcpSyncRequiresHostnameToString is a map of DHCPSyncRequiresHostname values to their string representations. var dhcpSyncRequiresHostnameToString = map[DHCPSyncRequiresHostname]string{ DHCPSyncRequiresHostnameDisabled: "Disabled", DHCPSyncRequiresHostnameEnabled: "Enabled", } -// String returns the string representation of the DHCPSyncRequiresHostname value +// String returns the string representation of the DHCPSyncRequiresHostname value. func (d DHCPSyncRequiresHostname) String() string { if value, exists := dhcpSyncRequiresHostnameToString[d]; exists { return value } - return "Value not found in map" + return ValueNotFound } diff --git a/pkg/wsman/amt/general/marshal.go b/pkg/wsman/amt/general/marshal.go index 84d46376..9dff46ac 100644 --- a/pkg/wsman/amt/general/marshal.go +++ b/pkg/wsman/amt/general/marshal.go @@ -11,20 +11,22 @@ import ( "gopkg.in/yaml.v3" ) -// JSON marshals the type into JSON format +// JSON marshals the type into JSON format. func (r *Response) JSON() string { jsonOutput, err := json.Marshal(r.Body) if err != nil { return "" } + return string(jsonOutput) } -// YAML marshals the type into YAML format +// YAML marshals the type into YAML format. func (r *Response) YAML() string { yamlOutput, err := yaml.Marshal(r.Body) if err != nil { return "" } + return string(yamlOutput) } diff --git a/pkg/wsman/amt/general/settings.go b/pkg/wsman/amt/general/settings.go index 6c03dfd8..410c248a 100644 --- a/pkg/wsman/amt/general/settings.go +++ b/pkg/wsman/amt/general/settings.go @@ -13,22 +13,22 @@ import ( "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/client" ) -// NewGeneralSettingsWithClient instantiates a new General Settings service +// NewGeneralSettingsWithClient instantiates a new General Settings service. func NewGeneralSettingsWithClient(wsmanMessageCreator *message.WSManMessageCreator, client client.WSMan) Settings { return Settings{ - base: message.NewBaseWithClient(wsmanMessageCreator, AMT_GeneralSettings, client), + base: message.NewBaseWithClient(wsmanMessageCreator, AMTGeneralSettings, client), } } -// Get retrieves the representation of the instance -func (GeneralSettings Settings) Get() (response Response, err error) { +// Get retrieves the representation of the instance. +func (s Settings) Get() (response Response, err error) { response = Response{ Message: &client.Message{ - XMLInput: GeneralSettings.base.Get(nil), + XMLInput: s.base.Get(nil), }, } // send the message to AMT - err = GeneralSettings.base.Execute(response.Message) + err = s.base.Execute(response.Message) if err != nil { return } @@ -38,18 +38,19 @@ func (GeneralSettings Settings) Get() (response Response, err error) { if err != nil { return } + return } -// Enumerate returns an enumeration context which is used in a subsequent Pull call -func (GeneralSettings Settings) Enumerate() (response Response, err error) { +// Enumerate returns an enumeration context which is used in a subsequent Pull call. +func (s Settings) Enumerate() (response Response, err error) { response = Response{ Message: &client.Message{ - XMLInput: GeneralSettings.base.Enumerate(), + XMLInput: s.base.Enumerate(), }, } // send the message to AMT - err = GeneralSettings.base.Execute(response.Message) + err = s.base.Execute(response.Message) if err != nil { return } @@ -64,14 +65,14 @@ func (GeneralSettings Settings) Enumerate() (response Response, err error) { } // Pull returns the instances of this class. An enumeration context provided by the Enumerate call is used as input. -func (GeneralSettings Settings) Pull(enumerationContext string) (response Response, err error) { +func (s Settings) Pull(enumerationContext string) (response Response, err error) { response = Response{ Message: &client.Message{ - XMLInput: GeneralSettings.base.Pull(enumerationContext), + XMLInput: s.base.Pull(enumerationContext), }, } // send the message to AMT - err = GeneralSettings.base.Execute(response.Message) + err = s.base.Execute(response.Message) if err != nil { return } @@ -85,15 +86,15 @@ func (GeneralSettings Settings) Pull(enumerationContext string) (response Respon return } -// Put will change properties of the selected instance -func (GeneralSettings Settings) Put(generalSettings GeneralSettingsResponse) (response Response, err error) { +// Put will change properties of the selected instance. +func (s Settings) Put(generalSettings GeneralSettingsResponse) (response Response, err error) { response = Response{ Message: &client.Message{ - XMLInput: GeneralSettings.base.Put(generalSettings, false, nil), + XMLInput: s.base.Put(generalSettings, false, nil), }, } // send the message to AMT - err = GeneralSettings.base.Execute(response.Message) + err = s.base.Execute(response.Message) if err != nil { return } @@ -102,5 +103,6 @@ func (GeneralSettings Settings) Put(generalSettings GeneralSettingsResponse) (re if err != nil { return } + return } diff --git a/pkg/wsman/amt/general/settings_test.go b/pkg/wsman/amt/general/settings_test.go index 10eb35c5..e8af92b9 100644 --- a/pkg/wsman/amt/general/settings_test.go +++ b/pkg/wsman/amt/general/settings_test.go @@ -39,13 +39,14 @@ func TestYaml(t *testing.T) { func TestPositiveAMT_GeneralSettings(t *testing.T) { messageID := 0 - resourceUriBase := "http://intel.com/wbem/wscim/1/amt-schema/1/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.AMTResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "amt/general", } elementUnderTest := NewGeneralSettingsWithClient(wsmanMessageCreator, &client) + t.Run("amt_* Tests", func(t *testing.T) { tests := []struct { name string @@ -55,20 +56,21 @@ func TestPositiveAMT_GeneralSettings(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //GETS + // GETS { "should create a valid AMT_GeneralSettings Get wsman message", - AMT_GeneralSettings, - wsmantesting.GET, + AMTGeneralSettings, + wsmantesting.Get, "", func() (Response, error) { - client.CurrentMessage = "Get" + client.CurrentMessage = wsmantesting.CurrentMessageGet + return elementUnderTest.Get() }, Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, GetResponse: GeneralSettingsResponse{ - XMLName: xml.Name{Space: "http://intel.com/wbem/wscim/1/amt-schema/1/AMT_GeneralSettings", Local: AMT_GeneralSettings}, + XMLName: xml.Name{Space: "http://intel.com/wbem/wscim/1/amt-schema/1/AMT_GeneralSettings", Local: AMTGeneralSettings}, ElementName: "Intel(r) AMT: General Settings", InstanceID: "Intel(r) AMT: General Settings", AMTNetworkEnabled: 1, @@ -76,7 +78,7 @@ func TestPositiveAMT_GeneralSettings(t *testing.T) { DDNSTTL: 900, DDNSUpdateByDHCPServerEnabled: true, DDNSUpdateEnabled: false, - DHCPSyncRequiresHostname: 1, //Intel SDK documentation missing + DHCPSyncRequiresHostname: 1, // Intel SDK documentation missing DHCPv6ConfigurationTimeout: 0, DigestRealm: "Digest:F3EB554784E729164447A89F60B641C5", DomainName: "Test Domain Name", @@ -96,14 +98,15 @@ func TestPositiveAMT_GeneralSettings(t *testing.T) { }, }, }, - //ENUMERATES + // ENUMERATES { "should create a valid AMT_GeneralSettings Enumerate wsman message", - AMT_GeneralSettings, - wsmantesting.ENUMERATE, - wsmantesting.ENUMERATE_BODY, + AMTGeneralSettings, + wsmantesting.Enumerate, + wsmantesting.EnumerateBody, func() (Response, error) { - client.CurrentMessage = "Enumerate" + client.CurrentMessage = wsmantesting.CurrentMessageEnumerate + return elementUnderTest.Enumerate() }, Body{ @@ -113,14 +116,15 @@ func TestPositiveAMT_GeneralSettings(t *testing.T) { }, }, }, - //PULLS + // PULLS { "should create a valid AMT_GeneralSettings Pull wsman message", - AMT_GeneralSettings, - wsmantesting.PULL, - wsmantesting.PULL_BODY, + AMTGeneralSettings, + wsmantesting.Pull, + wsmantesting.PullBody, func() (Response, error) { - client.CurrentMessage = "Pull" + client.CurrentMessage = wsmantesting.CurrentMessagePull + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -129,7 +133,7 @@ func TestPositiveAMT_GeneralSettings(t *testing.T) { XMLName: xml.Name{Space: "http://schemas.xmlsoap.org/ws/2004/09/enumeration", Local: "PullResponse"}, GeneralSettingsItems: []GeneralSettingsResponse{ { - XMLName: xml.Name{Space: "http://intel.com/wbem/wscim/1/amt-schema/1/AMT_GeneralSettings", Local: AMT_GeneralSettings}, + XMLName: xml.Name{Space: "http://intel.com/wbem/wscim/1/amt-schema/1/AMT_GeneralSettings", Local: AMTGeneralSettings}, ElementName: "Intel(r) AMT: General Settings", InstanceID: "Intel(r) AMT: General Settings", AMTNetworkEnabled: 1, @@ -159,7 +163,7 @@ func TestPositiveAMT_GeneralSettings(t *testing.T) { } for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, "", test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, "", test.body) messageID++ response, err := test.responseFunc() assert.NoError(t, err) @@ -169,15 +173,17 @@ func TestPositiveAMT_GeneralSettings(t *testing.T) { } }) } + func TestNegativeAMT_GeneralSettings(t *testing.T) { messageID := 0 - resourceUriBase := "http://intel.com/wbem/wscim/1/amt-schema/1/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.AMTResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "amt/general", } elementUnderTest := NewGeneralSettingsWithClient(wsmanMessageCreator, &client) + t.Run("amt_* Tests", func(t *testing.T) { tests := []struct { name string @@ -187,20 +193,21 @@ func TestNegativeAMT_GeneralSettings(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //GETS + // GETS { "should create a valid AMT_GeneralSettings Get wsman message", - AMT_GeneralSettings, - wsmantesting.GET, + AMTGeneralSettings, + wsmantesting.Get, "", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Get() }, Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, GetResponse: GeneralSettingsResponse{ - XMLName: xml.Name{Space: "http://intel.com/wbem/wscim/1/amt-schema/1/AMT_GeneralSettings", Local: AMT_GeneralSettings}, + XMLName: xml.Name{Space: "http://intel.com/wbem/wscim/1/amt-schema/1/AMT_GeneralSettings", Local: AMTGeneralSettings}, ElementName: "Intel(r) AMT: General Settings", InstanceID: "Intel(r) AMT: General Settings", AMTNetworkEnabled: 1, @@ -208,7 +215,7 @@ func TestNegativeAMT_GeneralSettings(t *testing.T) { DDNSTTL: 900, DDNSUpdateByDHCPServerEnabled: true, DDNSUpdateEnabled: false, - DHCPSyncRequiresHostname: 1, //Intel SDK documentation missing + DHCPSyncRequiresHostname: 1, // Intel SDK documentation missing DHCPv6ConfigurationTimeout: 0, DigestRealm: "Digest:F3EB554784E729164447A89F60B641C5", DomainName: "Test Domain Name", @@ -228,14 +235,15 @@ func TestNegativeAMT_GeneralSettings(t *testing.T) { }, }, }, - //ENUMERATES + // ENUMERATES { "should create a valid AMT_GeneralSettings Enumerate wsman message", - AMT_GeneralSettings, - wsmantesting.ENUMERATE, - wsmantesting.ENUMERATE_BODY, + AMTGeneralSettings, + wsmantesting.Enumerate, + wsmantesting.EnumerateBody, func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Enumerate() }, Body{ @@ -245,14 +253,15 @@ func TestNegativeAMT_GeneralSettings(t *testing.T) { }, }, }, - //PULLS + // PULLS { "should create a valid AMT_GeneralSettings Pull wsman message", - AMT_GeneralSettings, - wsmantesting.PULL, - wsmantesting.PULL_BODY, + AMTGeneralSettings, + wsmantesting.Pull, + wsmantesting.PullBody, func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -261,7 +270,7 @@ func TestNegativeAMT_GeneralSettings(t *testing.T) { XMLName: xml.Name{Space: "http://schemas.xmlsoap.org/ws/2004/09/enumeration", Local: "PullResponse"}, GeneralSettingsItems: []GeneralSettingsResponse{ { - XMLName: xml.Name{Space: "http://intel.com/wbem/wscim/1/amt-schema/1/AMT_GeneralSettings", Local: AMT_GeneralSettings}, + XMLName: xml.Name{Space: "http://intel.com/wbem/wscim/1/amt-schema/1/AMT_GeneralSettings", Local: AMTGeneralSettings}, ElementName: "Intel(r) AMT: General Settings", InstanceID: "Intel(r) AMT: General Settings", AMTNetworkEnabled: 1, @@ -291,7 +300,7 @@ func TestNegativeAMT_GeneralSettings(t *testing.T) { } for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, "", test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, "", test.body) messageID++ response, err := test.responseFunc() assert.Error(t, err) diff --git a/pkg/wsman/amt/general/types.go b/pkg/wsman/amt/general/types.go index 7f06bffa..2aee5ad2 100644 --- a/pkg/wsman/amt/general/types.go +++ b/pkg/wsman/amt/general/types.go @@ -18,7 +18,7 @@ type Settings struct { } // OUTPUTS -// Response Types +// Response Types. type ( Response struct { *client.Message @@ -68,12 +68,11 @@ type ( DHCPSyncRequiresHostname DHCPSyncRequiresHostname `xml:"DHCPSyncRequiresHostname,omitempty"` // When set to Enabled, the Intel AMT device will require the client to provide a hostname when requesting an IP address from a DHCP server. This setting is only applicable when DHCP is enabled. Values: 0=Disabled, 1=Enabled. Default: Disabled. } - PutResponse struct { - } + PutResponse struct{} ) // INPUTS -// Request Types +// Request Types. type ( GeneralSettingsRequest struct { XMLName xml.Name `xml:"h:AMT_GeneralSettings"` @@ -106,14 +105,14 @@ type ( // // ValueMap={0, 1, 2..} // -// Values={IPv4, IPv6, Reserved} +// Values={IPv4, IPv6, Reserved}. type PreferredAddressFamily int // When set to Disabled, the AMT OOB network interfaces (LAN and WLAN) are disabled including AMT user initiated applications, Environment Detection and RMCPPing. Since OOB networking is disabled, there will not be an option to enable it back remotely. // // ValueMap={0, 1, 2..} // -// Values={Disabled, Enabled, Reserved} +// Values={Disabled, Enabled, Reserved}. type AMTNetwork int // When set to Disabled, a management console cannot communicate with Intel AMT via a Thunderbolt dock. Available in Release 15.0 and later releases. @@ -130,7 +129,7 @@ type ThunderboltDock int // Extreme: SOL enabled = false, IDER enabled = false, KVM enabled = false, Opt-in can be disabled = false, opt-in configurable remotely = false. From Intel ME 8: Also Client Control Mode allowed=false and RCFG enabled = false. type PrivacyLevel int -// The system current power source +// The system current power source. type PowerSource int // When set to Enabled, the Intel AMT device will require the client to provide a hostname when requesting an IP address from a DHCP server. This setting is only applicable when DHCP is enabled. Values: 0=Disabled, 1=Enabled. Default: Disabled. diff --git a/pkg/wsman/amt/ieee8021x/credentialcontext.go b/pkg/wsman/amt/ieee8021x/credentialcontext.go index 4eb5c521..0bf2ed58 100644 --- a/pkg/wsman/amt/ieee8021x/credentialcontext.go +++ b/pkg/wsman/amt/ieee8021x/credentialcontext.go @@ -24,14 +24,14 @@ type CredentialContext struct { // NewIEEE8021xCredentialContextWithClient instantiates a new CredentialContext service. func NewIEEE8021xCredentialContextWithClient(wsmanMessageCreator *message.WSManMessageCreator, client client.WSMan) CredentialContext { return CredentialContext{ - base: message.NewBaseWithClient(wsmanMessageCreator, AMT_IEEE8021xCredentialContext, client), + base: message.NewBaseWithClient(wsmanMessageCreator, AMTIEEE8021xCredentialContext, client), } } // TODO: Handle GET input // Get retrieves the representation of the instance -// Enumerate returns an enumeration context which is used in a subsequent Pull call +// Enumerate returns an enumeration context which is used in a subsequent Pull call. func (credentialContext CredentialContext) Enumerate() (response Response, err error) { response = Response{ Message: &client.Message{ @@ -48,6 +48,7 @@ func (credentialContext CredentialContext) Enumerate() (response Response, err e if err != nil { return } + return } @@ -68,5 +69,6 @@ func (credentialContext CredentialContext) Pull(enumerationContext string) (resp if err != nil { return } + return } diff --git a/pkg/wsman/amt/ieee8021x/credentialcontext_test.go b/pkg/wsman/amt/ieee8021x/credentialcontext_test.go index ac4f046c..fa671e7c 100644 --- a/pkg/wsman/amt/ieee8021x/credentialcontext_test.go +++ b/pkg/wsman/amt/ieee8021x/credentialcontext_test.go @@ -9,11 +9,10 @@ import ( "encoding/xml" "testing" - "github.com/stretchr/testify/assert" - "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/internal/message" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/common" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/wsmantesting" + "github.com/stretchr/testify/assert" ) func TestJson(t *testing.T) { @@ -40,8 +39,8 @@ func TestYaml(t *testing.T) { func TestPositiveAMT_8021xCredentialContext(t *testing.T) { messageID := 0 - resourceUriBase := "http://intel.com/wbem/wscim/1/amt-schema/1/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.AMTResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "amt/ieee8021x/credentialcontext", } @@ -56,14 +55,15 @@ func TestPositiveAMT_8021xCredentialContext(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //ENUMERATES + // ENUMERATES { "should create a valid AMT_8021xCredentialContext Enumerate wsman message", - AMT_IEEE8021xCredentialContext, - wsmantesting.ENUMERATE, - wsmantesting.ENUMERATE_BODY, + AMTIEEE8021xCredentialContext, + wsmantesting.Enumerate, + wsmantesting.EnumerateBody, func() (Response, error) { - client.CurrentMessage = "Enumerate" + client.CurrentMessage = wsmantesting.CurrentMessageEnumerate + return elementUnderTest.Enumerate() }, Body{ @@ -73,14 +73,15 @@ func TestPositiveAMT_8021xCredentialContext(t *testing.T) { }, }, }, - //PULLS + // PULLS { "should create a valid AMT_8021xCredentialContext Pull wsman message", - AMT_IEEE8021xCredentialContext, - wsmantesting.PULL, - wsmantesting.PULL_BODY, + AMTIEEE8021xCredentialContext, + wsmantesting.Pull, + wsmantesting.PullBody, func() (Response, error) { - client.CurrentMessage = "Pull" + client.CurrentMessage = wsmantesting.CurrentMessagePull + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -93,7 +94,7 @@ func TestPositiveAMT_8021xCredentialContext(t *testing.T) { } for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, "", test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, "", test.body) messageID++ response, err := test.responseFunc() assert.NoError(t, err) @@ -106,8 +107,8 @@ func TestPositiveAMT_8021xCredentialContext(t *testing.T) { func TestNegativeAMT_8021xCredentialContext(t *testing.T) { messageID := 0 - resourceUriBase := "http://intel.com/wbem/wscim/1/amt-schema/1/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.AMTResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "amt/ieee8021x/credentialcontext", } @@ -122,14 +123,15 @@ func TestNegativeAMT_8021xCredentialContext(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //ENUMERATES + // ENUMERATES { "should create a valid AMT_8021xCredentialContext Enumerate wsman message", - AMT_IEEE8021xCredentialContext, - wsmantesting.ENUMERATE, - wsmantesting.ENUMERATE_BODY, + AMTIEEE8021xCredentialContext, + wsmantesting.Enumerate, + wsmantesting.EnumerateBody, func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Enumerate() }, Body{ @@ -139,14 +141,15 @@ func TestNegativeAMT_8021xCredentialContext(t *testing.T) { }, }, }, - //PULLS + // PULLS { "should create a valid AMT_8021xCredentialContext Pull wsman message", - AMT_IEEE8021xCredentialContext, - wsmantesting.PULL, - wsmantesting.PULL_BODY, + AMTIEEE8021xCredentialContext, + wsmantesting.Pull, + wsmantesting.PullBody, func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -159,7 +162,7 @@ func TestNegativeAMT_8021xCredentialContext(t *testing.T) { } for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, "", test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, "", test.body) messageID++ response, err := test.responseFunc() assert.Error(t, err) diff --git a/pkg/wsman/amt/ieee8021x/decoder.go b/pkg/wsman/amt/ieee8021x/decoder.go index 8e5035e8..c34d2ef8 100644 --- a/pkg/wsman/amt/ieee8021x/decoder.go +++ b/pkg/wsman/amt/ieee8021x/decoder.go @@ -6,8 +6,9 @@ package ieee8021x const ( - AMT_IEEE8021xCredentialContext string = "AMT_8021xCredentialContext" - AMT_IEEE8021xProfile string = "AMT_8021XProfile" + AMTIEEE8021xCredentialContext string = "AMT_8021xCredentialContext" + AMTIEEE8021xProfile string = "AMT_8021XProfile" + ValueNotFound string = "Value not found in map" ) const ( @@ -20,7 +21,7 @@ const ( AuthenticationProtocolEAPFASTTLS ) -// authenticationProtocolString is a map of AuthenticationProtocol to their string representation +// authenticationProtocolString is a map of AuthenticationProtocol to their string representation. var authenticationProtocolString = map[AuthenticationProtocol]string{ AuthenticationProtocolTLS: "TLS", AuthenticationProtocolTTLSMSCHAPv2: "TTLSMSCHAPv2", @@ -31,13 +32,13 @@ var authenticationProtocolString = map[AuthenticationProtocol]string{ AuthenticationProtocolEAPFASTTLS: "EAPFASTTLS", } -// String returns the string representation of the AuthenticationProtocol value +// String returns the string representation of the AuthenticationProtocol value. func (a AuthenticationProtocol) String() string { if value, exists := authenticationProtocolString[a]; exists { return value } - return "Value not found in map" + return ValueNotFound } const ( @@ -45,17 +46,17 @@ const ( DomainSuffix ) -// serverCertificateNameComparisonString is a map of ServerCertificateNameComparison to their string representation +// serverCertificateNameComparisonString is a map of ServerCertificateNameComparison to their string representation. var serverCertificateNameComparisonString = map[ServerCertificateNameComparison]string{ FullName: "FullName", DomainSuffix: "DomainSuffix", } -// String returns the string representation of the ServerCertificateNameComparison value +// String returns the string representation of the ServerCertificateNameComparison value. func (s ServerCertificateNameComparison) String() string { if value, exists := serverCertificateNameComparisonString[s]; exists { return value } - return "Value not found in map" + return ValueNotFound } diff --git a/pkg/wsman/amt/ieee8021x/marshal.go b/pkg/wsman/amt/ieee8021x/marshal.go index e23c3e2d..0636e0f7 100644 --- a/pkg/wsman/amt/ieee8021x/marshal.go +++ b/pkg/wsman/amt/ieee8021x/marshal.go @@ -11,20 +11,22 @@ import ( "gopkg.in/yaml.v3" ) -// JSON marshals the type into JSON format +// JSON marshals the type into JSON format. func (r *Response) JSON() string { jsonOutput, err := json.Marshal(r.Body) if err != nil { return "" } + return string(jsonOutput) } -// YAML marshals the type into YAML format +// YAML marshals the type into YAML format. func (r *Response) YAML() string { yamlOutput, err := yaml.Marshal(r.Body) if err != nil { return "" } + return string(yamlOutput) } diff --git a/pkg/wsman/amt/ieee8021x/profile.go b/pkg/wsman/amt/ieee8021x/profile.go index d05f4520..4275349d 100644 --- a/pkg/wsman/amt/ieee8021x/profile.go +++ b/pkg/wsman/amt/ieee8021x/profile.go @@ -17,14 +17,14 @@ type Profile struct { base message.Base } -// NewIEEE8021xProfileWithClient instantiates a new Profile service +// NewIEEE8021xProfileWithClient instantiates a new Profile service. func NewIEEE8021xProfileWithClient(wsmanMessageCreator *message.WSManMessageCreator, client client.WSMan) Profile { return Profile{ - base: message.NewBaseWithClient(wsmanMessageCreator, AMT_IEEE8021xProfile, client), + base: message.NewBaseWithClient(wsmanMessageCreator, AMTIEEE8021xProfile, client), } } -// Get retrieves the representation of the instance +// Get retrieves the representation of the instance. func (profile Profile) Get() (response Response, err error) { response = Response{ Message: &client.Message{ @@ -41,10 +41,11 @@ func (profile Profile) Get() (response Response, err error) { if err != nil { return } + return } -// Enumerate returns an enumeration context which is used in a subsequent Pull call +// Enumerate returns an enumeration context which is used in a subsequent Pull call. func (profile Profile) Enumerate() (response Response, err error) { response = Response{ Message: &client.Message{ @@ -61,6 +62,7 @@ func (profile Profile) Enumerate() (response Response, err error) { if err != nil { return } + return } @@ -81,12 +83,13 @@ func (profile Profile) Pull(enumerationContext string) (response Response, err e if err != nil { return } + return } -// Put will change properties of the selected instance +// Put will change properties of the selected instance. func (profile Profile) Put(ieee8021xProfile ProfileRequest) (response Response, err error) { - ieee8021xProfile.H = fmt.Sprintf("%s%s", message.AMTSchema, AMT_IEEE8021xProfile) + ieee8021xProfile.H = fmt.Sprintf("%s%s", message.AMTSchema, AMTIEEE8021xProfile) response = Response{ Message: &client.Message{ XMLInput: profile.base.Put(ieee8021xProfile, false, nil), @@ -102,5 +105,6 @@ func (profile Profile) Put(ieee8021xProfile ProfileRequest) (response Response, if err != nil { return } + return } diff --git a/pkg/wsman/amt/ieee8021x/profile_test.go b/pkg/wsman/amt/ieee8021x/profile_test.go index b8507bc9..ceff7058 100644 --- a/pkg/wsman/amt/ieee8021x/profile_test.go +++ b/pkg/wsman/amt/ieee8021x/profile_test.go @@ -9,17 +9,16 @@ import ( "encoding/xml" "testing" - "github.com/stretchr/testify/assert" - "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/internal/message" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/common" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/wsmantesting" + "github.com/stretchr/testify/assert" ) func TestPositiveAMT_8021XProfile(t *testing.T) { messageID := 0 - resourceUriBase := "http://intel.com/wbem/wscim/1/amt-schema/1/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.AMTResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "amt/ieee8021x/profile", } @@ -34,14 +33,15 @@ func TestPositiveAMT_8021XProfile(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //GETS + // GETS { "should create a valid AMT_8021XProfile Get wsman message", - AMT_IEEE8021xProfile, - wsmantesting.GET, + AMTIEEE8021xProfile, + wsmantesting.Get, "", func() (Response, error) { - client.CurrentMessage = "Get" + client.CurrentMessage = wsmantesting.CurrentMessageGet + return elementUnderTest.Get() }, Body{ @@ -56,14 +56,15 @@ func TestPositiveAMT_8021XProfile(t *testing.T) { }, }, }, - //ENUMERATES + // ENUMERATES { "should create a valid AMT_8021XProfile Enumerate wsman message", - AMT_IEEE8021xProfile, - wsmantesting.ENUMERATE, - wsmantesting.ENUMERATE_BODY, + AMTIEEE8021xProfile, + wsmantesting.Enumerate, + wsmantesting.EnumerateBody, func() (Response, error) { - client.CurrentMessage = "Enumerate" + client.CurrentMessage = wsmantesting.CurrentMessageEnumerate + return elementUnderTest.Enumerate() }, Body{ @@ -73,14 +74,15 @@ func TestPositiveAMT_8021XProfile(t *testing.T) { }, }, }, - //PULLS + // PULLS { "should create a valid AMT_8021XProfile Pull wsman message", - AMT_IEEE8021xProfile, - wsmantesting.PULL, - wsmantesting.PULL_BODY, + AMTIEEE8021xProfile, + wsmantesting.Pull, + wsmantesting.PullBody, func() (Response, error) { - client.CurrentMessage = "Pull" + client.CurrentMessage = wsmantesting.CurrentMessagePull + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -100,11 +102,11 @@ func TestPositiveAMT_8021XProfile(t *testing.T) { }, }, }, - //PUTS + // PUTS { "should create a valid AMT_8021XProfile Put wsman message", - AMT_IEEE8021xProfile, - wsmantesting.PUT, + AMTIEEE8021xProfile, + wsmantesting.Put, "Intel(r) AMT 802.1x ProfileIntel(r) AMT 802.1x Profile 0falsefalse00", func() (Response, error) { profileRequest := ProfileRequest{ @@ -114,7 +116,8 @@ func TestPositiveAMT_8021XProfile(t *testing.T) { Enabled: false, InstanceID: "Intel(r) AMT 802.1x Profile 0", } - client.CurrentMessage = "Put" + client.CurrentMessage = wsmantesting.CurrentMessagePut + return elementUnderTest.Put(profileRequest) }, Body{ @@ -132,7 +135,7 @@ func TestPositiveAMT_8021XProfile(t *testing.T) { } for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, "", test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, "", test.body) messageID++ response, err := test.responseFunc() assert.NoError(t, err) @@ -142,10 +145,11 @@ func TestPositiveAMT_8021XProfile(t *testing.T) { } }) } + func TestNegativeAMT_8021XProfile(t *testing.T) { messageID := 0 - resourceUriBase := "http://intel.com/wbem/wscim/1/amt-schema/1/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.AMTResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "amt/ieee8021x/profile", } @@ -160,14 +164,15 @@ func TestNegativeAMT_8021XProfile(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //GETS + // GETS { "should create a valid AMT_8021XProfile Get wsman message", - AMT_IEEE8021xProfile, - wsmantesting.GET, + AMTIEEE8021xProfile, + wsmantesting.Get, "", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Get() }, Body{ @@ -182,14 +187,15 @@ func TestNegativeAMT_8021XProfile(t *testing.T) { }, }, }, - //ENUMERATES + // ENUMERATES { "should create a valid AMT_8021XProfile Enumerate wsman message", - AMT_IEEE8021xProfile, - wsmantesting.ENUMERATE, - wsmantesting.ENUMERATE_BODY, + AMTIEEE8021xProfile, + wsmantesting.Enumerate, + wsmantesting.EnumerateBody, func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Enumerate() }, Body{ @@ -199,14 +205,15 @@ func TestNegativeAMT_8021XProfile(t *testing.T) { }, }, }, - //PULLS + // PULLS { "should create a valid AMT_8021XProfile Pull wsman message", - AMT_IEEE8021xProfile, - wsmantesting.PULL, - wsmantesting.PULL_BODY, + AMTIEEE8021xProfile, + wsmantesting.Pull, + wsmantesting.PullBody, func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -226,11 +233,11 @@ func TestNegativeAMT_8021XProfile(t *testing.T) { }, }, }, - //PUTS + // PUTS { "should create a valid AMT_8021XProfile Put wsman message", - AMT_IEEE8021xProfile, - wsmantesting.PUT, + AMTIEEE8021xProfile, + wsmantesting.Put, "Intel(r) AMT 802.1x ProfileIntel(r) AMT 802.1x Profile 0falsefalse00", func() (Response, error) { profileRequest := ProfileRequest{ @@ -240,7 +247,8 @@ func TestNegativeAMT_8021XProfile(t *testing.T) { Enabled: false, InstanceID: "Intel(r) AMT 802.1x Profile 0", } - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Put(profileRequest) }, Body{ @@ -258,7 +266,7 @@ func TestNegativeAMT_8021XProfile(t *testing.T) { } for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, "", test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, "", test.body) messageID++ response, err := test.responseFunc() assert.Error(t, err) diff --git a/pkg/wsman/amt/ieee8021x/types.go b/pkg/wsman/amt/ieee8021x/types.go index 22b1bdb4..9b4f2587 100644 --- a/pkg/wsman/amt/ieee8021x/types.go +++ b/pkg/wsman/amt/ieee8021x/types.go @@ -14,7 +14,7 @@ import ( ) // OUTPUTS -// Response Types +// Response Types. type ( Response struct { *client.Message @@ -87,12 +87,12 @@ type ProfileRequest struct { // // ValueMap={0, 1, 2, 3, 4, 5, 6} // -// Values={TLS, TTLS_MSCHAPv2, PEAP_MSCHAPv2, EAP_GTC, EAPFAST_MSCHAPv2, EAPFAST_GTC, EAPFAST_TLS} +// Values={TLS, TTLS_MSCHAPv2, PEAP_MSCHAPv2, EAP_GTC, EAPFAST_MSCHAPv2, EAPFAST_GTC, EAPFAST_TLS}. type AuthenticationProtocol int // Determines the comparison algorithm used between the ServerCertificateName value and the subject name field of the certificate presented by the AAA server. This field is mandatory if ServerCertificateName is defined. // // ValueMap={0, 1} // -// Values={FullName, DomainSuffix} +// Values={FullName, DomainSuffix}. type ServerCertificateNameComparison int diff --git a/pkg/wsman/amt/kerberos/decoder.go b/pkg/wsman/amt/kerberos/decoder.go index ff4c1bcc..7f0b94fd 100644 --- a/pkg/wsman/amt/kerberos/decoder.go +++ b/pkg/wsman/amt/kerberos/decoder.go @@ -6,9 +6,10 @@ package kerberos const ( - AMT_KerberosSettingData string = "AMT_KerberosSettingData" + AMTKerberosSettingData string = "AMT_KerberosSettingData" SetCredentialCacheState string = "SetCredentialCacheState" GetCredentialCacheState string = "GetCredentialCacheState" + ValueNotFound string = "Value not found in map" ) const ( @@ -35,7 +36,7 @@ const ( ReturnValueNoConfiguredEncryptionAlgorithms ) -// returnValueString is a map of ReturnValue to string. These values are estimated return values from the AMT device +// returnValueString is a map of ReturnValue to string. These values are estimated return values from the AMT device. var returnValueString = map[ReturnValue]string{ ReturnValueSuccess: "Success", ReturnValueNotSupported: "NotSupported", @@ -56,13 +57,13 @@ var returnValueString = map[ReturnValue]string{ ReturnValueNoConfiguredEncryptionAlgorithms: "NoConfiguredEncryptionAlgorithms", } -// ConvertReturnValueToString returns the string representation of the ReturnValue value +// ConvertReturnValueToString returns the string representation of the ReturnValue value. func (r ReturnValue) String() string { if value, exists := returnValueString[r]; exists { return value } - return "Value not found in map" + return ValueNotFound } const ( @@ -72,7 +73,7 @@ const ( ServicePrincipalProtocolSOLAndIDERProtocolDefinitionUsingSSL ) -// servicePrincipalProtocolToString is a map of ServicePrincipalProtocol to string +// servicePrincipalProtocolToString is a map of ServicePrincipalProtocol to string. var servicePrincipalProtocolToString = map[ServicePrincipalProtocol]string{ ServicePrincipalProtocolHTTPProtocolDefinition: "HTTPProtocolDefinition", ServicePrincipalProtocolHTTPSProtocolDefinition: "HTTPSProtocolDefinition", @@ -80,13 +81,13 @@ var servicePrincipalProtocolToString = map[ServicePrincipalProtocol]string{ ServicePrincipalProtocolSOLAndIDERProtocolDefinitionUsingSSL: "SOL&IDERProtocolDefinitionUsingSSL", } -// String returns the string representation of the ServicePrincipalProtocol value +// String returns the string representation of the ServicePrincipalProtocol value. func (s ServicePrincipalProtocol) String() string { if value, exists := servicePrincipalProtocolToString[s]; exists { return value } - return "Value not found in map" + return ValueNotFound } const ( @@ -95,20 +96,20 @@ const ( SupportedEncryptionAlgorithmsAES256CTSHMACSHA196 ) -// supportedEncryptionAlgorithmsToString is a map of SupportedEncryptionAlgorithms to string +// supportedEncryptionAlgorithmsToString is a map of SupportedEncryptionAlgorithms to string. var supportedEncryptionAlgorithmsToString = map[SupportedEncryptionAlgorithms]string{ SupportedEncryptionAlgorithmsRC4HMAC: "RC4-HMAC", SupportedEncryptionAlgorithmsAES128CTSHMACSHA196: "AES128-CTS-HMAC-SHA1-96", SupportedEncryptionAlgorithmsAES256CTSHMACSHA196: "AES256-CTS-HMAC-SHA1-96", } -// String returns the string representation of the SupportedEncryptionAlgorithms value +// String returns the string representation of the SupportedEncryptionAlgorithms value. func (s SupportedEncryptionAlgorithms) String() string { if value, exists := supportedEncryptionAlgorithmsToString[s]; exists { return value } - return "Value not found in map" + return ValueNotFound } const ( @@ -117,18 +118,18 @@ const ( ConfiguredEncryptionAlgorithmsAES256CTSHMACSHA196 ) -// configuredEncryptionAlgorithmsToString is a map of ConfiguredEncryptionAlgorithms to string +// configuredEncryptionAlgorithmsToString is a map of ConfiguredEncryptionAlgorithms to string. var configuredEncryptionAlgorithmsToString = map[ConfiguredEncryptionAlgorithms]string{ ConfiguredEncryptionAlgorithmsRC4HMAC: "RC4-HMAC", ConfiguredEncryptionAlgorithmsAES128CTSHMACSHA196: "AES128-CTS-HMAC-SHA1-96", ConfiguredEncryptionAlgorithmsAES256CTSHMACSHA196: "AES256-CTS-HMAC-SHA1-96", } -// String returns the string representation of the ConfiguredEncryptionAlgorithms value +// String returns the string representation of the ConfiguredEncryptionAlgorithms value. func (c ConfiguredEncryptionAlgorithms) String() string { if value, exists := configuredEncryptionAlgorithmsToString[c]; exists { return value } - return "Value not found in map" + return ValueNotFound } diff --git a/pkg/wsman/amt/kerberos/marshal.go b/pkg/wsman/amt/kerberos/marshal.go index 8a0798eb..a9781d44 100644 --- a/pkg/wsman/amt/kerberos/marshal.go +++ b/pkg/wsman/amt/kerberos/marshal.go @@ -11,20 +11,22 @@ import ( "gopkg.in/yaml.v3" ) -// JSON marshals the type into JSON format +// JSON marshals the type into JSON format. func (r *Response) JSON() string { jsonOutput, err := json.Marshal(r.Body) if err != nil { return "" } + return string(jsonOutput) } -// YAML marshals the type into YAML format +// YAML marshals the type into YAML format. func (r *Response) YAML() string { yamlOutput, err := yaml.Marshal(r.Body) if err != nil { return "" } + return string(yamlOutput) } diff --git a/pkg/wsman/amt/kerberos/settingdata.go b/pkg/wsman/amt/kerberos/settingdata.go index f215ada0..799b9abc 100644 --- a/pkg/wsman/amt/kerberos/settingdata.go +++ b/pkg/wsman/amt/kerberos/settingdata.go @@ -15,14 +15,14 @@ import ( "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/client" ) -// NewKerberosSettingDataWithClient instantiates a new kerberos SettingData +// NewKerberosSettingDataWithClient instantiates a new kerberos SettingData. func NewKerberosSettingDataWithClient(wsmanMessageCreator *message.WSManMessageCreator, client client.WSMan) SettingData { return SettingData{ - base: message.NewBaseWithClient(wsmanMessageCreator, AMT_KerberosSettingData, client), + base: message.NewBaseWithClient(wsmanMessageCreator, AMTKerberosSettingData, client), } } -// Get retrieves the representation of the instance +// Get retrieves the representation of the instance. func (settingData SettingData) Get() (response Response, err error) { response = Response{ Message: &client.Message{ @@ -39,10 +39,11 @@ func (settingData SettingData) Get() (response Response, err error) { if err != nil { return } + return } -// Enumerate returns an enumeration context which is used in a subsequent Pull call +// Enumerate returns an enumeration context which is used in a subsequent Pull call. func (settingData SettingData) Enumerate() (response Response, err error) { response = Response{ Message: &client.Message{ @@ -59,6 +60,7 @@ func (settingData SettingData) Enumerate() (response Response, err error) { if err != nil { return } + return } @@ -79,13 +81,14 @@ func (settingData SettingData) Pull(enumerationContext string) (response Respons if err != nil { return } + return } -// GetCredentialCacheState gets the current state of the credential caching functionality +// GetCredentialCacheState gets the current state of the credential caching functionality. func (settingData SettingData) GetCredentialCacheState() (response Response, err error) { - header := settingData.base.WSManMessageCreator.CreateHeader(methods.GenerateAction(AMT_KerberosSettingData, GetCredentialCacheState), AMT_KerberosSettingData, nil, "", "") - body := settingData.base.WSManMessageCreator.CreateBody(methods.GenerateInputMethod(GetCredentialCacheState), AMT_KerberosSettingData, nil) + header := settingData.base.WSManMessageCreator.CreateHeader(methods.GenerateAction(AMTKerberosSettingData, GetCredentialCacheState), AMTKerberosSettingData, nil, "", "") + body := settingData.base.WSManMessageCreator.CreateBody(methods.GenerateInputMethod(GetCredentialCacheState), AMTKerberosSettingData, nil) response = Response{ Message: &client.Message{ @@ -102,18 +105,19 @@ func (settingData SettingData) GetCredentialCacheState() (response Response, err if err != nil { return } + return } // SetCredentialCacheState enables/disables the credential caching functionality -// TODO: Current gets SOAP schema violation from AMT +// TODO: Current gets SOAP schema violation from AMT. func (settingData SettingData) SetCredentialCacheState(enabled bool) (response Response, err error) { - credentialCasheState := SetCredentialCacheState_INPUT{ - H: fmt.Sprintf("%s%s", message.AMTSchema, AMT_KerberosSettingData), + credentialCasheState := SetCredentialCacheStateInput{ + H: fmt.Sprintf("%s%s", message.AMTSchema, AMTKerberosSettingData), Enabled: enabled, } - header := settingData.base.WSManMessageCreator.CreateHeader(methods.GenerateAction(AMT_KerberosSettingData, SetCredentialCacheState), AMT_KerberosSettingData, nil, "", "") - body := settingData.base.WSManMessageCreator.CreateBody(methods.GenerateInputMethod(SetCredentialCacheState), AMT_KerberosSettingData, credentialCasheState) + header := settingData.base.WSManMessageCreator.CreateHeader(methods.GenerateAction(AMTKerberosSettingData, SetCredentialCacheState), AMTKerberosSettingData, nil, "", "") + body := settingData.base.WSManMessageCreator.CreateBody(methods.GenerateInputMethod(SetCredentialCacheState), AMTKerberosSettingData, credentialCasheState) response = Response{ Message: &client.Message{ @@ -130,5 +134,6 @@ func (settingData SettingData) SetCredentialCacheState(enabled bool) (response R if err != nil { return } + return } diff --git a/pkg/wsman/amt/kerberos/settingdata_test.go b/pkg/wsman/amt/kerberos/settingdata_test.go index 580aceb7..ec5e8856 100644 --- a/pkg/wsman/amt/kerberos/settingdata_test.go +++ b/pkg/wsman/amt/kerberos/settingdata_test.go @@ -10,11 +10,10 @@ import ( "fmt" "testing" - "github.com/stretchr/testify/assert" - "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/internal/message" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/common" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/wsmantesting" + "github.com/stretchr/testify/assert" ) func TestJson(t *testing.T) { @@ -23,7 +22,7 @@ func TestJson(t *testing.T) { GetResponse: KerberosSettingDataResponse{}, }, } - expectedResult := "{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"GetResponse\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"ElementName\":\"\",\"InstanceID\":\"\",\"RealmName\":\"\",\"ServicePrincipalName\":null,\"ServicePrincipalProtocol\":null,\"KeyVersion\":0,\"EncryptionAlgorithm\":0,\"MasterKey\":null,\"MaximumClockTolerance\":0,\"KrbEnabled\":false,\"Passphrase\":\"\",\"Salt\":\"\",\"IterationCount\":0,\"SupportedEncryptionAlgorithms\":null,\"ConfiguredEncryptionAlgorithms\":null},\"EnumerateResponse\":{\"EnumerationContext\":\"\"},\"PullResponse\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"KerberosSettingDataItems\":null},\"GetCredentialCacheState_OUTPUT\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"Enabled\":false,\"ReturnValue\":0},\"SetCredentialCacheState_OUTPUT\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"ReturnValue\":0}}" + expectedResult := "{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"GetResponse\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"ElementName\":\"\",\"InstanceID\":\"\",\"RealmName\":\"\",\"ServicePrincipalName\":null,\"ServicePrincipalProtocol\":null,\"KeyVersion\":0,\"EncryptionAlgorithm\":0,\"MasterKey\":null,\"MaximumClockTolerance\":0,\"KrbEnabled\":false,\"Passphrase\":\"\",\"Salt\":\"\",\"IterationCount\":0,\"SupportedEncryptionAlgorithms\":null,\"ConfiguredEncryptionAlgorithms\":null},\"EnumerateResponse\":{\"EnumerationContext\":\"\"},\"PullResponse\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"KerberosSettingDataItems\":null},\"GetCredentialCacheStateOutput\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"Enabled\":false,\"ReturnValue\":0},\"SetCredentialCacheStateOutput\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"ReturnValue\":0}}" result := response.JSON() assert.Equal(t, expectedResult, result) } @@ -34,15 +33,15 @@ func TestYaml(t *testing.T) { GetResponse: KerberosSettingDataResponse{}, }, } - expectedResult := "xmlname:\n space: \"\"\n local: \"\"\ngetresponse:\n xmlname:\n space: \"\"\n local: \"\"\n elementname: \"\"\n instanceid: \"\"\n realmname: \"\"\n serviceprincipalname: []\n serviceprincipalprotocol: []\n keyversion: 0\n encryptionalgorithm: 0\n masterkey: []\n maximumclocktolerance: 0\n krbenabled: false\n passphrase: \"\"\n salt: \"\"\n iterationcount: 0\n supportedencryptionalgorithms: []\n configuredencryptionalgorithms: []\nenumerateresponse:\n enumerationcontext: \"\"\npullresponse:\n xmlname:\n space: \"\"\n local: \"\"\n kerberossettingdataitems: []\ngetcredentialcachestate_output:\n xmlname:\n space: \"\"\n local: \"\"\n enabled: false\n returnvalue: 0\nsetcredentialcachestate_output:\n xmlname:\n space: \"\"\n local: \"\"\n returnvalue: 0\n" + expectedResult := "xmlname:\n space: \"\"\n local: \"\"\ngetresponse:\n xmlname:\n space: \"\"\n local: \"\"\n elementname: \"\"\n instanceid: \"\"\n realmname: \"\"\n serviceprincipalname: []\n serviceprincipalprotocol: []\n keyversion: 0\n encryptionalgorithm: 0\n masterkey: []\n maximumclocktolerance: 0\n krbenabled: false\n passphrase: \"\"\n salt: \"\"\n iterationcount: 0\n supportedencryptionalgorithms: []\n configuredencryptionalgorithms: []\nenumerateresponse:\n enumerationcontext: \"\"\npullresponse:\n xmlname:\n space: \"\"\n local: \"\"\n kerberossettingdataitems: []\ngetcredentialcachestateoutput:\n xmlname:\n space: \"\"\n local: \"\"\n enabled: false\n returnvalue: 0\nsetcredentialcachestateoutput:\n xmlname:\n space: \"\"\n local: \"\"\n returnvalue: 0\n" result := response.YAML() assert.Equal(t, expectedResult, result) } func TestPositiveAMT_KerberosSettingData(t *testing.T) { messageID := 0 - resourceUriBase := "http://intel.com/wbem/wscim/1/amt-schema/1/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.AMTResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "amt/kerberos", } @@ -57,20 +56,21 @@ func TestPositiveAMT_KerberosSettingData(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //GETS + // GETS { "should create a valid AMT_KerberosSettingData Get wsman message", - AMT_KerberosSettingData, - wsmantesting.GET, + AMTKerberosSettingData, + wsmantesting.Get, "", func() (Response, error) { - client.CurrentMessage = "Get" + client.CurrentMessage = wsmantesting.CurrentMessageGet + return elementUnderTest.Get() }, Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, GetResponse: KerberosSettingDataResponse{ - XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMT_KerberosSettingData), Local: AMT_KerberosSettingData}, + XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMTKerberosSettingData), Local: AMTKerberosSettingData}, ElementName: "Intel(r) AMT: Kerberos Settings", InstanceID: "Intel (r) AMT: Kerberos Settings", KrbEnabled: false, @@ -78,14 +78,15 @@ func TestPositiveAMT_KerberosSettingData(t *testing.T) { }, }, }, - //ENUMERATES + // ENUMERATES { "should create a valid AMT_KerberosSettingData Enumerate wsman message", - AMT_KerberosSettingData, - wsmantesting.ENUMERATE, - wsmantesting.ENUMERATE_BODY, + AMTKerberosSettingData, + wsmantesting.Enumerate, + wsmantesting.EnumerateBody, func() (Response, error) { - client.CurrentMessage = "Enumerate" + client.CurrentMessage = wsmantesting.CurrentMessageEnumerate + return elementUnderTest.Enumerate() }, Body{ @@ -95,14 +96,15 @@ func TestPositiveAMT_KerberosSettingData(t *testing.T) { }, }, }, - //PULLS + // PULLS { "should create a valid AMT_KerberosSettingData Pull wsman message", - AMT_KerberosSettingData, - wsmantesting.PULL, - wsmantesting.PULL_BODY, + AMTKerberosSettingData, + wsmantesting.Pull, + wsmantesting.PullBody, func() (Response, error) { - client.CurrentMessage = "Pull" + client.CurrentMessage = wsmantesting.CurrentMessagePull + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -111,7 +113,7 @@ func TestPositiveAMT_KerberosSettingData(t *testing.T) { XMLName: xml.Name{Space: message.XMLPullResponseSpace, Local: "PullResponse"}, KerberosSettingDataItems: []KerberosSettingDataResponse{ { - XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMT_KerberosSettingData), Local: AMT_KerberosSettingData}, + XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMTKerberosSettingData), Local: AMTKerberosSettingData}, ElementName: "Intel(r) AMT: Kerberos Settings", InstanceID: "Intel (r) AMT: Kerberos Settings", KrbEnabled: false, @@ -124,17 +126,18 @@ func TestPositiveAMT_KerberosSettingData(t *testing.T) { // GET CREDENTIAL CACHE STATE { "should return a valid amt_KerberosSettingData GetCredentialCacheState wsman message", - AMT_KerberosSettingData, - fmt.Sprintf("%s%s/%s", message.AMTSchema, AMT_KerberosSettingData, "GetCredentialCacheState"), + AMTKerberosSettingData, + fmt.Sprintf("%s%s/%s", message.AMTSchema, AMTKerberosSettingData, "GetCredentialCacheState"), ``, func() (Response, error) { client.CurrentMessage = "GetCredentialCacheState" + return elementUnderTest.GetCredentialCacheState() }, Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, GetCredentialCacheState_OUTPUT: GetCredentialCacheState_OUTPUT{ - XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMT_KerberosSettingData), Local: "GetCredentialCacheState_OUTPUT"}, + XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMTKerberosSettingData), Local: "GetCredentialCacheState_OUTPUT"}, Enabled: false, ReturnValue: 0, }, @@ -157,21 +160,21 @@ func TestPositiveAMT_KerberosSettingData(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, "", test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, "", test.body) messageID++ response, err := test.responseFunc() assert.NoError(t, err) assert.Equal(t, expectedXMLInput, response.XMLInput) assert.Equal(t, test.expectedResponse, response.Body) - }) } }) } + func TestNegativeAMT_KerberosSettingData(t *testing.T) { messageID := 0 - resourceUriBase := "http://intel.com/wbem/wscim/1/amt-schema/1/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.AMTResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "amt/kerberos", } @@ -186,20 +189,21 @@ func TestNegativeAMT_KerberosSettingData(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //GETS + // GETS { "should create a valid AMT_KerberosSettingData Get wsman message", - AMT_KerberosSettingData, - wsmantesting.GET, + AMTKerberosSettingData, + wsmantesting.Get, "", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Get() }, Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, GetResponse: KerberosSettingDataResponse{ - XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMT_KerberosSettingData), Local: AMT_KerberosSettingData}, + XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMTKerberosSettingData), Local: AMTKerberosSettingData}, ElementName: "Intel(r) AMT: Kerberos Settings", InstanceID: "Intel (r) AMT: Kerberos Settings", KrbEnabled: false, @@ -207,14 +211,15 @@ func TestNegativeAMT_KerberosSettingData(t *testing.T) { }, }, }, - //ENUMERATES + // ENUMERATES { "should create a valid AMT_KerberosSettingData Enumerate wsman message", - AMT_KerberosSettingData, - wsmantesting.ENUMERATE, - wsmantesting.ENUMERATE_BODY, + AMTKerberosSettingData, + wsmantesting.Enumerate, + wsmantesting.EnumerateBody, func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Enumerate() }, Body{ @@ -224,14 +229,15 @@ func TestNegativeAMT_KerberosSettingData(t *testing.T) { }, }, }, - //PULLS + // PULLS { "should create a valid AMT_KerberosSettingData Pull wsman message", - AMT_KerberosSettingData, - wsmantesting.PULL, - wsmantesting.PULL_BODY, + AMTKerberosSettingData, + wsmantesting.Pull, + wsmantesting.PullBody, func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -240,7 +246,7 @@ func TestNegativeAMT_KerberosSettingData(t *testing.T) { XMLName: xml.Name{Space: message.XMLPullResponseSpace, Local: "PullResponse"}, KerberosSettingDataItems: []KerberosSettingDataResponse{ { - XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMT_KerberosSettingData), Local: AMT_KerberosSettingData}, + XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMTKerberosSettingData), Local: AMTKerberosSettingData}, ElementName: "Intel(r) AMT: Kerberos Settings", InstanceID: "Intel (r) AMT: Kerberos Settings", KrbEnabled: false, @@ -253,17 +259,18 @@ func TestNegativeAMT_KerberosSettingData(t *testing.T) { // GET CREDENTIAL CACHE STATE { "should return a valid amt_KerberosSettingData GetCredentialCacheState wsman message", - AMT_KerberosSettingData, - fmt.Sprintf("%s%s/%s", message.AMTSchema, AMT_KerberosSettingData, "GetCredentialCacheState"), + AMTKerberosSettingData, + fmt.Sprintf("%s%s/%s", message.AMTSchema, AMTKerberosSettingData, "GetCredentialCacheState"), ``, func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.GetCredentialCacheState() }, Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, GetCredentialCacheState_OUTPUT: GetCredentialCacheState_OUTPUT{ - XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMT_KerberosSettingData), Local: "GetCredentialCacheState_OUTPUT"}, + XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMTKerberosSettingData), Local: "GetCredentialCacheState_OUTPUT"}, Enabled: false, ReturnValue: 0, }, @@ -286,13 +293,12 @@ func TestNegativeAMT_KerberosSettingData(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, "", test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, "", test.body) messageID++ response, err := test.responseFunc() assert.Error(t, err) assert.Equal(t, expectedXMLInput, response.XMLInput) assert.NotEqual(t, test.expectedResponse, response.Body) - }) } }) diff --git a/pkg/wsman/amt/kerberos/types.go b/pkg/wsman/amt/kerberos/types.go index a869ffd5..29de7c91 100644 --- a/pkg/wsman/amt/kerberos/types.go +++ b/pkg/wsman/amt/kerberos/types.go @@ -18,7 +18,7 @@ type SettingData struct { } // OUTPUTS -// Response Types +// Response Types. type ( Response struct { *client.Message @@ -71,9 +71,9 @@ type ( ) // INPUTS -// Request Types +// Request Types. type ( - SetCredentialCacheState_INPUT struct { + SetCredentialCacheStateInput struct { XMLName xml.Name `xml:"h:SetCredentialCacheState_INPUT"` H string `xml:"xmlns:h,attr"` Enabled bool `xml:"h:Enabled"` @@ -84,28 +84,28 @@ type ( // // ValueMap={0, 1, 2, 3} // -// Values={HTTP Protocol definition, HTTPS Protocol definition, SOL&IDER protocol definition, SOL&IDER protocol definition (using SSL)} +// Values={HTTP Protocol definition, HTTPS Protocol definition, SOL&IDER protocol definition, SOL&IDER protocol definition (using SSL)}. type ServicePrincipalProtocol int // A 16-bit enumeration values that identifier the supported encryption algorithms used in Kerberos authentication. Note: While RC4-HMAC is supported, Intel recommends using AES256-CTS-HMAC-SHA1-96. // // ValueMap={0, 1, 2, ..} // -// Values={RC4-HMAC, AES128-CTS-HMAC-SHA1-96, AES256-CTS-HMAC-SHA1-96, Reserved} +// Values={RC4-HMAC, AES128-CTS-HMAC-SHA1-96, AES256-CTS-HMAC-SHA1-96, Reserved}. type SupportedEncryptionAlgorithms int // A 16-bit enumeration values that identifier the configured encryption algorithms used in Kerberos authentication. Note: While RC4-HMAC is supported, Intel recommends using AES256-CTS-HMAC-SHA1-96. Note: Intel AMT does not choose the encryption algorithm to configure based on the values specified by the user. Intel AMT attempts to enable RC4. If a Passphrase and Salt are provided, the AES suites are also configured. // // ValueMap={0, 1, 2, ..} // -// Values={RC4-HMAC, AES128-CTS-HMAC-SHA1-96, AES256-CTS-HMAC-SHA1-96, Reserved} +// Values={RC4-HMAC, AES128-CTS-HMAC-SHA1-96, AES256-CTS-HMAC-SHA1-96, Reserved}. type ConfiguredEncryptionAlgorithms int // A 16-bit enumeration value that identifiers the encryption algorithm used in Kerberos authentication. // // ValueMap={0} // -// Values={RC4 encryption and HMAC authentication} +// Values={RC4 encryption and HMAC authentication}. type EncryptionAlgorithm int // ReturnValue is a 16-bit enumeration value that indicates the success or failure of an operation. diff --git a/pkg/wsman/amt/managementpresence/decoder.go b/pkg/wsman/amt/managementpresence/decoder.go index 003475e2..3de1edc2 100644 --- a/pkg/wsman/amt/managementpresence/decoder.go +++ b/pkg/wsman/amt/managementpresence/decoder.go @@ -6,7 +6,7 @@ package managementpresence const ( - AMT_ManagementPresenceRemoteSAP string = "AMT_ManagementPresenceRemoteSAP" + AMTManagementPresenceRemoteSAP string = "AMT_ManagementPresenceRemoteSAP" ) const ( @@ -37,7 +37,7 @@ const ( InfoFormatParameterizedURL InfoFormat = 206 ) -// infoFormatString is a map of InfoFormat to their string representation +// infoFormatString is a map of InfoFormat to their string representation. var infoFormatString = map[InfoFormat]string{ InfoFormatOther: "Other", InfoFormatHostName: "HostName", @@ -71,5 +71,6 @@ func (i InfoFormat) String() string { if value, exists := infoFormatString[i]; exists { return value } + return "Value not found in map" } diff --git a/pkg/wsman/amt/managementpresence/marshal.go b/pkg/wsman/amt/managementpresence/marshal.go index edb5196a..6d279bc3 100644 --- a/pkg/wsman/amt/managementpresence/marshal.go +++ b/pkg/wsman/amt/managementpresence/marshal.go @@ -11,20 +11,22 @@ import ( "gopkg.in/yaml.v3" ) -// JSON marshals the type into JSON format +// JSON marshals the type into JSON format. func (r *Response) JSON() string { jsonOutput, err := json.Marshal(r.Body) if err != nil { return "" } + return string(jsonOutput) } -// YAML marshals the type into YAML format +// YAML marshals the type into YAML format. func (r *Response) YAML() string { yamlOutput, err := yaml.Marshal(r.Body) if err != nil { return "" } + return string(yamlOutput) } diff --git a/pkg/wsman/amt/managementpresence/remotesap.go b/pkg/wsman/amt/managementpresence/remotesap.go index fe4cecaa..59b768d0 100644 --- a/pkg/wsman/amt/managementpresence/remotesap.go +++ b/pkg/wsman/amt/managementpresence/remotesap.go @@ -13,14 +13,14 @@ import ( "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/client" ) -// NewManagementPresenceRemoteSAPWithClient instantiates a new RemoteSAP +// NewManagementPresenceRemoteSAPWithClient instantiates a new RemoteSAP. func NewManagementPresenceRemoteSAPWithClient(wsmanMessageCreator *message.WSManMessageCreator, client client.WSMan) RemoteSAP { return RemoteSAP{ - base: message.NewBaseWithClient(wsmanMessageCreator, AMT_ManagementPresenceRemoteSAP, client), + base: message.NewBaseWithClient(wsmanMessageCreator, AMTManagementPresenceRemoteSAP, client), } } -// Get retrieves the representation of the instance +// Get retrieves the representation of the instance. func (remoteSAP RemoteSAP) Get() (response Response, err error) { response = Response{ Message: &client.Message{ @@ -37,10 +37,11 @@ func (remoteSAP RemoteSAP) Get() (response Response, err error) { if err != nil { return } + return } -// Enumerate returns an enumeration context which is used in a subsequent Pull call +// Enumerate returns an enumeration context which is used in a subsequent Pull call. func (remoteSAP RemoteSAP) Enumerate() (response Response, err error) { response = Response{ Message: &client.Message{ @@ -57,6 +58,7 @@ func (remoteSAP RemoteSAP) Enumerate() (response Response, err error) { if err != nil { return } + return } @@ -77,10 +79,11 @@ func (remoteSAP RemoteSAP) Pull(enumerationContext string) (response Response, e if err != nil { return } + return } -// Delete removes a the specified instance +// Delete removes a the specified instance. func (remoteSAP RemoteSAP) Delete(handle string) (response Response, err error) { selector := message.Selector{Name: "Name", Value: handle} response = Response{ @@ -98,5 +101,6 @@ func (remoteSAP RemoteSAP) Delete(handle string) (response Response, err error) if err != nil { return } + return } diff --git a/pkg/wsman/amt/managementpresence/remotesap_test.go b/pkg/wsman/amt/managementpresence/remotesap_test.go index 2e3f2330..24d018af 100644 --- a/pkg/wsman/amt/managementpresence/remotesap_test.go +++ b/pkg/wsman/amt/managementpresence/remotesap_test.go @@ -39,12 +39,13 @@ func TestYaml(t *testing.T) { func TestPositiveAMT_ManagementPresenceRemoteSAP(t *testing.T) { messageID := 0 - resourceUriBase := "http://intel.com/wbem/wscim/1/amt-schema/1/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.AMTResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "amt/managementpresence", } elementUnderTest := NewManagementPresenceRemoteSAPWithClient(wsmanMessageCreator, &client) + t.Run("amt_ManagementPresenceRemoteSAP Tests", func(t *testing.T) { tests := []struct { name string @@ -55,15 +56,16 @@ func TestPositiveAMT_ManagementPresenceRemoteSAP(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //GETS + // GETS { "should create a valid AMT_ManagementPresenceRemoteSAP Get wsman message", - AMT_ManagementPresenceRemoteSAP, - wsmantesting.GET, + AMTManagementPresenceRemoteSAP, + wsmantesting.Get, "", "", func() (Response, error) { - client.CurrentMessage = "Get" + client.CurrentMessage = wsmantesting.CurrentMessageGet + return elementUnderTest.Get() }, Body{ @@ -82,15 +84,16 @@ func TestPositiveAMT_ManagementPresenceRemoteSAP(t *testing.T) { }, }, }, - //ENUMERATES + // ENUMERATES { "should create a valid AMT_ManagementPresenceRemoteSAP Enumerate wsman message", - AMT_ManagementPresenceRemoteSAP, - wsmantesting.ENUMERATE, - wsmantesting.ENUMERATE_BODY, + AMTManagementPresenceRemoteSAP, + wsmantesting.Enumerate, + wsmantesting.EnumerateBody, "", func() (Response, error) { - client.CurrentMessage = "Enumerate" + client.CurrentMessage = wsmantesting.CurrentMessageEnumerate + return elementUnderTest.Enumerate() }, Body{ @@ -100,15 +103,16 @@ func TestPositiveAMT_ManagementPresenceRemoteSAP(t *testing.T) { }, }, }, - //PULLS + // PULLS { "should create a valid AMT_ManagementPresenceRemoteSAP Pull wsman message", - AMT_ManagementPresenceRemoteSAP, - wsmantesting.PULL, - wsmantesting.PULL_BODY, + AMTManagementPresenceRemoteSAP, + wsmantesting.Pull, + wsmantesting.PullBody, "", func() (Response, error) { - client.CurrentMessage = "Pull" + client.CurrentMessage = wsmantesting.CurrentMessagePull + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -132,15 +136,16 @@ func TestPositiveAMT_ManagementPresenceRemoteSAP(t *testing.T) { }, }, }, - //DELETE + // DELETE { "should create a valid AMT_ManagementPresenceRemoteSAP Delete wsman message", - AMT_ManagementPresenceRemoteSAP, - wsmantesting.DELETE, + AMTManagementPresenceRemoteSAP, + wsmantesting.Delete, "", "instanceID123", func() (Response, error) { - client.CurrentMessage = "Delete" + client.CurrentMessage = wsmantesting.CurrentMessageDelete + return elementUnderTest.Delete("instanceID123") }, Body{ @@ -151,7 +156,7 @@ func TestPositiveAMT_ManagementPresenceRemoteSAP(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, test.extraHeader, test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, test.extraHeader, test.body) messageID++ response, err := test.responseFunc() assert.NoError(t, err) @@ -161,14 +166,16 @@ func TestPositiveAMT_ManagementPresenceRemoteSAP(t *testing.T) { } }) } + func TestNegativeAMT_ManagementPresenceRemoteSAP(t *testing.T) { messageID := 0 - resourceUriBase := "http://intel.com/wbem/wscim/1/amt-schema/1/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.AMTResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "amt/managementpresence", } elementUnderTest := NewManagementPresenceRemoteSAPWithClient(wsmanMessageCreator, &client) + t.Run("amt_ManagementPresenceRemoteSAP Tests", func(t *testing.T) { tests := []struct { name string @@ -179,15 +186,16 @@ func TestNegativeAMT_ManagementPresenceRemoteSAP(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //GETS + // GETS { "should create a valid AMT_ManagementPresenceRemoteSAP Get wsman message", - AMT_ManagementPresenceRemoteSAP, - wsmantesting.GET, + AMTManagementPresenceRemoteSAP, + wsmantesting.Get, "", "", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Get() }, Body{ @@ -206,15 +214,16 @@ func TestNegativeAMT_ManagementPresenceRemoteSAP(t *testing.T) { }, }, }, - //ENUMERATES + // ENUMERATES { "should create a valid AMT_ManagementPresenceRemoteSAP Enumerate wsman message", - AMT_ManagementPresenceRemoteSAP, - wsmantesting.ENUMERATE, - wsmantesting.ENUMERATE_BODY, + AMTManagementPresenceRemoteSAP, + wsmantesting.Enumerate, + wsmantesting.EnumerateBody, "", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Enumerate() }, Body{ @@ -224,15 +233,16 @@ func TestNegativeAMT_ManagementPresenceRemoteSAP(t *testing.T) { }, }, }, - //PULLS + // PULLS { "should create a valid AMT_ManagementPresenceRemoteSAP Pull wsman message", - AMT_ManagementPresenceRemoteSAP, - wsmantesting.PULL, - wsmantesting.PULL_BODY, + AMTManagementPresenceRemoteSAP, + wsmantesting.Pull, + wsmantesting.PullBody, "", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -256,15 +266,16 @@ func TestNegativeAMT_ManagementPresenceRemoteSAP(t *testing.T) { }, }, }, - //DELETE + // DELETE { "should create a valid AMT_ManagementPresenceRemoteSAP Delete wsman message", - AMT_ManagementPresenceRemoteSAP, - wsmantesting.DELETE, + AMTManagementPresenceRemoteSAP, + wsmantesting.Delete, "", "instanceID123", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Delete("instanceID123") }, Body{ @@ -275,7 +286,7 @@ func TestNegativeAMT_ManagementPresenceRemoteSAP(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, test.extraHeader, test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, test.extraHeader, test.body) messageID++ response, err := test.responseFunc() assert.Error(t, err) diff --git a/pkg/wsman/amt/managementpresence/types.go b/pkg/wsman/amt/managementpresence/types.go index a17caa8b..e5afa95a 100644 --- a/pkg/wsman/amt/managementpresence/types.go +++ b/pkg/wsman/amt/managementpresence/types.go @@ -18,7 +18,7 @@ type RemoteSAP struct { } // OUTPUTS -// Response Types +// Response Types. type ( Response struct { *client.Message diff --git a/pkg/wsman/amt/messagelog/decoder.go b/pkg/wsman/amt/messagelog/decoder.go index d5a724de..7b79491b 100644 --- a/pkg/wsman/amt/messagelog/decoder.go +++ b/pkg/wsman/amt/messagelog/decoder.go @@ -6,9 +6,10 @@ package messagelog const ( - AMT_MessageLog string = "AMT_MessageLog" + AMTMessageLog string = "AMT_MessageLog" GetRecords string = "GetRecords" PositionToFirstRecord string = "PositionToFirstRecord" + ValueNotFound string = "Value not found in map" ) const ( @@ -25,7 +26,7 @@ const ( CapabilitiesCanFlagRecordsForOverwrite ) -// capabilitiesString is a map of the capabilities to their string representation +// capabilitiesString is a map of the capabilities to their string representation. var capabilitiesString = map[Capabilities]string{ CapabilitiesUnknown: "Unknown", CapabilitiesOther: "Other", @@ -40,12 +41,13 @@ var capabilitiesString = map[Capabilities]string{ CapabilitiesCanFlagRecordsForOverwrite: "CanFlagRecordsForOverwrite", } -// String returns the string representation of the capabilities +// String returns the string representation of the capabilities. func (c Capabilities) String() string { if value, exists := capabilitiesString[c]; exists { return value } - return "Value not found in map" + + return ValueNotFound } const ( @@ -63,7 +65,7 @@ const ( CharacterSetDefinedByIndividualRecords ) -// characterSetString is a map of the character set to their string representation +// characterSetString is a map of the character set to their string representation. var characterSetString = map[CharacterSet]string{ CharacterSetUnknown: "Unknown", CharacterSetOther: "Other", @@ -79,12 +81,13 @@ var characterSetString = map[CharacterSet]string{ CharacterSetDefinedByIndividualRecords: "DefinedByIndividualRecords", } -// ConvertCharacterSetToString returns the string representation of the character set +// ConvertCharacterSetToString returns the string representation of the character set. func (c CharacterSet) String() string { if value, exists := characterSetString[c]; exists { return value } - return "Value not found in map" + + return ValueNotFound } const ( @@ -96,7 +99,7 @@ const ( EnabledDefaultQuiesce EnabledDefault = 9 ) -// enabledDefaultString is a map of the enabled default to their string representation +// enabledDefaultString is a map of the enabled default to their string representation. var enabledDefaultString = map[EnabledDefault]string{ EnabledDefaultEnabled: "Enabled", EnabledDefaultDisabled: "Disabled", @@ -106,12 +109,13 @@ var enabledDefaultString = map[EnabledDefault]string{ EnabledDefaultQuiesce: "Quiesce", } -// String returns the string representation of the enabled default +// String returns the string representation of the enabled default. func (e EnabledDefault) String() string { if value, exists := enabledDefaultString[e]; exists { return value } - return "Value not found in map" + + return ValueNotFound } const ( @@ -128,7 +132,7 @@ const ( EnabledStateStarting ) -// enabledStateString is a map of the enabled state to their string representation +// enabledStateString is a map of the enabled state to their string representation. var enabledStateString = map[EnabledState]string{ EnabledStateUnknown: "Unknown", EnabledStateOther: "Other", @@ -143,12 +147,13 @@ var enabledStateString = map[EnabledState]string{ EnabledStateStarting: "Starting", } -// String returns the string representation of the enabled state +// String returns the string representation of the enabled state. func (e EnabledState) String() string { if value, exists := enabledStateString[e]; exists { return value } - return "Value not found in map" + + return ValueNotFound } const ( @@ -161,7 +166,7 @@ const ( HealthStateNonRecoverableError HealthState = 35 ) -// healthStateString is a map of the health state to their string representation +// healthStateString is a map of the health state to their string representation. var healthStateString = map[HealthState]string{ HealthStateUnknown: "Unknown", HealthStateOK: "OK", @@ -172,12 +177,13 @@ var healthStateString = map[HealthState]string{ HealthStateNonRecoverableError: "NonRecoverableError", } -// String returns the string representation of the health state +// String returns the string representation of the health state. func (h HealthState) String() string { if value, exists := healthStateString[h]; exists { return value } - return "Value not found in map" + + return ValueNotFound } const ( @@ -188,7 +194,7 @@ const ( LastChangeLogCleared ) -// lastChangeString is a map of the last change to their string representation +// lastChangeString is a map of the last change to their string representation. var lastChangeString = map[LastChange]string{ LastChangeUnknown: "Unknown", LastChangeAdd: "Add", @@ -197,12 +203,13 @@ var lastChangeString = map[LastChange]string{ LastChangeLogCleared: "LogCleared", } -// String returns the string representation of the last change +// String returns the string representation of the last change. func (l LastChange) String() string { if value, exists := lastChangeString[l]; exists { return value } - return "Value not found in map" + + return ValueNotFound } const ( @@ -212,7 +219,7 @@ const ( LogStateNotApplicable LogState = 5 ) -// logStateString is a map of the log state to their string representation +// logStateString is a map of the log state to their string representation. var logStateString = map[LogState]string{ LogStateUnknown: "Unknown", LogStateNormal: "Normal", @@ -220,12 +227,13 @@ var logStateString = map[LogState]string{ LogStateNotApplicable: "NotApplicable", } -// String returns the string representation of the log state +// String returns the string representation of the log state. func (l LogState) String() string { if value, exists := logStateString[l]; exists { return value } - return "Value not found in map" + + return ValueNotFound } const ( @@ -251,7 +259,7 @@ const ( OperationalStatusRelocating ) -// operationalStatusString is a map of the operational status to their string representation +// operationalStatusString is a map of the operational status to their string representation. var operationalStatusString = map[OperationalStatus]string{ OperationalStatusUnknown: "Unknown", OperationalStatusOther: "Other", @@ -275,12 +283,13 @@ var operationalStatusString = map[OperationalStatus]string{ OperationalStatusRelocating: "Relocating", } -// String returns the string representation of the operational status +// String returns the string representation of the operational status. func (o OperationalStatus) String() string { if value, exists := operationalStatusString[o]; exists { return value } - return "Value not found in map" + + return ValueNotFound } const ( @@ -294,7 +303,7 @@ const ( OverwritePolicyNeverOverwrite ) -// overwritePolicyString is a map of the overwrite policy to their string representation +// overwritePolicyString is a map of the overwrite policy to their string representation. var overwritePolicyString = map[OverwritePolicy]string{ OverwritePolicyUnknown: "Unknown", OverwritePolicyOther: "Other", @@ -306,12 +315,13 @@ var overwritePolicyString = map[OverwritePolicy]string{ OverwritePolicyNeverOverwrite: "NeverOverwrite", } -// String returns the string representation of the overwrite policy +// String returns the string representation of the overwrite policy. func (o OverwritePolicy) String() string { if value, exists := overwritePolicyString[o]; exists { return value } - return "Value not found in map" + + return ValueNotFound } const ( @@ -329,7 +339,7 @@ const ( RequestedStateNotApplicable RequestedState = 12 ) -// requestedStateString is a map of the requested state to their string representation +// requestedStateString is a map of the requested state to their string representation. var requestedStateString = map[RequestedState]string{ RequestedStateUnknown: "Unknown", RequestedStateEnabled: "Enabled", @@ -345,12 +355,13 @@ var requestedStateString = map[RequestedState]string{ RequestedStateNotApplicable: "NotApplicable", } -// String returns the string representation of the requested state +// String returns the string representation of the requested state. func (r RequestedState) String() string { if value, exists := requestedStateString[r]; exists { return value } - return "Value not found in map" + + return ValueNotFound } const ( @@ -360,7 +371,7 @@ const ( GetRecordsReturnValueNoRecordExistsInLog GetRecordsReturnValue = 3 ) -// getRecordsReturnValueString is a map of the GetRecordsReturnValue to their string representation +// getRecordsReturnValueString is a map of the GetRecordsReturnValue to their string representation. var getRecordsReturnValueString = map[GetRecordsReturnValue]string{ GetRecordsReturnValueCompletedWithNoError: "CompletedWithNoError", GetRecordsReturnValueNotSupported: "NotSupported", @@ -368,12 +379,13 @@ var getRecordsReturnValueString = map[GetRecordsReturnValue]string{ GetRecordsReturnValueNoRecordExistsInLog: "NoRecordExistsInLog", } -// String returns the string representation of the GetRecordsReturnValue value +// String returns the string representation of the GetRecordsReturnValue value. func (g GetRecordsReturnValue) String() string { if value, exists := getRecordsReturnValueString[g]; exists { return value } - return "Value not found in map" + + return ValueNotFound } const ( @@ -382,17 +394,18 @@ const ( PositionToFirstRecordReturnValueNoRecordExists PositionToFirstRecordReturnValue = 2 ) -// positionToFirstRecordReturnValueString is a map of the PositionToFirstRecordReturnValue to their string representation +// positionToFirstRecordReturnValueString is a map of the PositionToFirstRecordReturnValue to their string representation. var positionToFirstRecordReturnValueString = map[PositionToFirstRecordReturnValue]string{ PositionToFirstRecordReturnValueCompletedWithNoError: "CompletedWithNoError", PositionToFirstRecordReturnValueNotSupported: "NotSupported", PositionToFirstRecordReturnValueNoRecordExists: "NoRecordExists", } -// String returns the string representation of the PositionToFirstRecordReturnValue value +// String returns the string representation of the PositionToFirstRecordReturnValue value. func (p PositionToFirstRecordReturnValue) String() string { if value, exists := positionToFirstRecordReturnValueString[p]; exists { return value } - return "Value not found in map" + + return ValueNotFound } diff --git a/pkg/wsman/amt/messagelog/log.go b/pkg/wsman/amt/messagelog/log.go index 324148e3..8221db00 100644 --- a/pkg/wsman/amt/messagelog/log.go +++ b/pkg/wsman/amt/messagelog/log.go @@ -32,15 +32,15 @@ import ( "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/client" ) -// NewMessageLogWithClient instantiates a new MessageLog -func NewMessageLogWithClient(wsmanMessageCreator *message.WSManMessageCreator, client client.WSMan) MessageLog { - return MessageLog{ - base: message.NewBaseWithClient(wsmanMessageCreator, AMT_MessageLog, client), +// NewMessageLogWithClient instantiates a new MessageLog. +func NewMessageLogWithClient(wsmanMessageCreator *message.WSManMessageCreator, client client.WSMan) Service { + return Service{ + base: message.NewBaseWithClient(wsmanMessageCreator, AMTMessageLog, client), } } -// Get retrieves the representation of the instance -func (messageLog MessageLog) Get() (response Response, err error) { +// Get retrieves the representation of the instance. +func (messageLog Service) Get() (response Response, err error) { response = Response{ Message: &client.Message{ XMLInput: messageLog.base.Get(nil), @@ -56,11 +56,12 @@ func (messageLog MessageLog) Get() (response Response, err error) { if err != nil { return } + return } -// Enumerate returns an enumeration context which is used in a subsequent Pull call -func (messageLog MessageLog) Enumerate() (response Response, err error) { +// Enumerate returns an enumeration context which is used in a subsequent Pull call. +func (messageLog Service) Enumerate() (response Response, err error) { response = Response{ Message: &client.Message{ XMLInput: messageLog.base.Enumerate(), @@ -76,11 +77,12 @@ func (messageLog MessageLog) Enumerate() (response Response, err error) { if err != nil { return } + return } // Pull returns the instances of this class. An enumeration context provided by the Enumerate call is used as input. -func (messageLog MessageLog) Pull(enumerationContext string) (response Response, err error) { +func (messageLog Service) Pull(enumerationContext string) (response Response, err error) { response = Response{ Message: &client.Message{ XMLInput: messageLog.base.Pull(enumerationContext), @@ -96,19 +98,20 @@ func (messageLog MessageLog) Pull(enumerationContext string) (response Response, if err != nil { return } + return } // GetRecords retrieves multiple records from event log. // The IterationIdentifier input parameter is a numeric value (starting at 1) which is the position of the first record in the log that should be extracted. -// MaxReadRecords is set to 390. If NoMoreRecords returns false, call this again setting the identifier to the start of the next IterationIdentifier -func (messageLog MessageLog) GetRecords(identifier int) (response Response, err error) { +// MaxReadRecords is set to 390. If NoMoreRecords returns false, call this again setting the identifier to the start of the next IterationIdentifier. +func (messageLog Service) GetRecords(identifier int) (response Response, err error) { if identifier < 1 { identifier = 1 } - header := messageLog.base.WSManMessageCreator.CreateHeader(methods.GenerateAction(AMT_MessageLog, GetRecords), AMT_MessageLog, nil, "", "") - body := messageLog.base.WSManMessageCreator.CreateBody(methods.GenerateInputMethod(GetRecords), AMT_MessageLog, &GetRecords_INPUT{ + header := messageLog.base.WSManMessageCreator.CreateHeader(methods.GenerateAction(AMTMessageLog, GetRecords), AMTMessageLog, nil, "", "") + body := messageLog.base.WSManMessageCreator.CreateBody(methods.GenerateInputMethod(GetRecords), AMTMessageLog, &GetRecords_INPUT{ IterationIdentifier: identifier, MaxReadRecords: 390, }) @@ -128,15 +131,16 @@ func (messageLog MessageLog) GetRecords(identifier int) (response Response, err if err != nil { return } + return } // Requests that an iteration of the MessageLog be established and that the iterator be set to the first entry in the Log. An identifier for the iterator is returned as an output parameter of the method. Regarding iteration, you have 2 choices: 1) Embed iteration data in the method call, and allow implementations to track/ store this data manually; or, 2) Iterate using a separate object (for example, class ActiveIterator) as an iteration agent. The first approach is used here for interoperability. The second requires an instance of the Iterator object for EACH iteration in progress. 2's functionality could be implemented underneath 1. // // Product Specific Usage: In current implementation this method doesn't have any affect. In order to get the events from the log user should just call GetRecord or GetRecords. -func (messageLog MessageLog) PositionToFirstRecord() (response Response, err error) { - header := messageLog.base.WSManMessageCreator.CreateHeader(methods.GenerateAction(AMT_MessageLog, PositionToFirstRecord), AMT_MessageLog, nil, "", "") - body := messageLog.base.WSManMessageCreator.CreateBody(methods.GenerateInputMethod(PositionToFirstRecord), AMT_MessageLog, nil) +func (messageLog Service) PositionToFirstRecord() (response Response, err error) { + header := messageLog.base.WSManMessageCreator.CreateHeader(methods.GenerateAction(AMTMessageLog, PositionToFirstRecord), AMTMessageLog, nil, "", "") + body := messageLog.base.WSManMessageCreator.CreateBody(methods.GenerateInputMethod(PositionToFirstRecord), AMTMessageLog, nil) response = Response{ Message: &client.Message{ XMLInput: messageLog.base.WSManMessageCreator.CreateXML(header, body), @@ -152,5 +156,6 @@ func (messageLog MessageLog) PositionToFirstRecord() (response Response, err err if err != nil { return } + return } diff --git a/pkg/wsman/amt/messagelog/log_test.go b/pkg/wsman/amt/messagelog/log_test.go index c12b2b2f..28d7d72e 100644 --- a/pkg/wsman/amt/messagelog/log_test.go +++ b/pkg/wsman/amt/messagelog/log_test.go @@ -9,11 +9,10 @@ import ( "encoding/xml" "testing" - "github.com/stretchr/testify/assert" - "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/internal/message" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/common" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/wsmantesting" + "github.com/stretchr/testify/assert" ) func TestJson(t *testing.T) { @@ -40,8 +39,8 @@ func TestYaml(t *testing.T) { func TestPositiveAMT_MessageLog(t *testing.T) { messageID := 0 - resourceUriBase := "http://intel.com/wbem/wscim/1/amt-schema/1/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.AMTResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "amt/messagelog", } @@ -56,13 +55,14 @@ func TestPositiveAMT_MessageLog(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //GETS + // GETS { "should create a valid AMT_MessageLog Get wsman message", - AMT_MessageLog, wsmantesting.GET, + AMTMessageLog, wsmantesting.Get, "", func() (Response, error) { - client.CurrentMessage = "Get" + client.CurrentMessage = wsmantesting.CurrentMessageGet + return elementUnderTest.Get() }, Body{ @@ -94,14 +94,15 @@ func TestPositiveAMT_MessageLog(t *testing.T) { }, }, }, - //ENUMERATES + // ENUMERATES { "should create a valid AMT_MessageLog Enumerate wsman message", - AMT_MessageLog, - wsmantesting.ENUMERATE, - wsmantesting.ENUMERATE_BODY, + AMTMessageLog, + wsmantesting.Enumerate, + wsmantesting.EnumerateBody, func() (Response, error) { - client.CurrentMessage = "Enumerate" + client.CurrentMessage = wsmantesting.CurrentMessageEnumerate + return elementUnderTest.Enumerate() }, Body{ @@ -111,14 +112,15 @@ func TestPositiveAMT_MessageLog(t *testing.T) { }, }, }, - //PULLS + // PULLS { "should create a valid AMT_MessageLog Pull wsman message", - AMT_MessageLog, - wsmantesting.PULL, - wsmantesting.PULL_BODY, + AMTMessageLog, + wsmantesting.Pull, + wsmantesting.PullBody, func() (Response, error) { - client.CurrentMessage = "Pull" + client.CurrentMessage = wsmantesting.CurrentMessagePull + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -158,11 +160,12 @@ func TestPositiveAMT_MessageLog(t *testing.T) { // POSITION TO FIRST RECORD { "should return a valid amt_MessageLog PositionToFirstRecords wsman message", - AMT_MessageLog, + AMTMessageLog, `http://intel.com/wbem/wscim/1/amt-schema/1/AMT_MessageLog/PositionToFirstRecord`, ``, func() (Response, error) { client.CurrentMessage = "PositionToFirstRecord" + return elementUnderTest.PositionToFirstRecord() }, Body{ @@ -177,11 +180,12 @@ func TestPositiveAMT_MessageLog(t *testing.T) { // GET RECORDS { "should return a valid amt_MessageLog GetRecords wsman message", - AMT_MessageLog, + AMTMessageLog, `http://intel.com/wbem/wscim/1/amt-schema/1/AMT_MessageLog/GetRecords`, `1390`, func() (Response, error) { client.CurrentMessage = "GetRecords" + return elementUnderTest.GetRecords(1) }, Body{ @@ -199,7 +203,7 @@ func TestPositiveAMT_MessageLog(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, "", test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, "", test.body) messageID++ response, err := test.responseFunc() assert.NoError(t, err) @@ -209,10 +213,11 @@ func TestPositiveAMT_MessageLog(t *testing.T) { } }) } + func TestNegativeAMT_MessageLog(t *testing.T) { messageID := 0 - resourceUriBase := "http://intel.com/wbem/wscim/1/amt-schema/1/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.AMTResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "amt/messagelog", } @@ -227,13 +232,14 @@ func TestNegativeAMT_MessageLog(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //GETS + // GETS { "should create a valid AMT_MessageLog Get wsman message", - AMT_MessageLog, wsmantesting.GET, + AMTMessageLog, wsmantesting.Get, "", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Get() }, Body{ @@ -265,14 +271,15 @@ func TestNegativeAMT_MessageLog(t *testing.T) { }, }, }, - //ENUMERATES + // ENUMERATES { "should create a valid AMT_MessageLog Enumerate wsman message", - AMT_MessageLog, - wsmantesting.ENUMERATE, - wsmantesting.ENUMERATE_BODY, + AMTMessageLog, + wsmantesting.Enumerate, + wsmantesting.EnumerateBody, func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Enumerate() }, Body{ @@ -282,14 +289,15 @@ func TestNegativeAMT_MessageLog(t *testing.T) { }, }, }, - //PULLS + // PULLS { "should create a valid AMT_MessageLog Pull wsman message", - AMT_MessageLog, - wsmantesting.PULL, - wsmantesting.PULL_BODY, + AMTMessageLog, + wsmantesting.Pull, + wsmantesting.PullBody, func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -329,11 +337,12 @@ func TestNegativeAMT_MessageLog(t *testing.T) { // POSITION TO FIRST RECORD { "should return a valid amt_MessageLog PositionToFirstRecords wsman message", - AMT_MessageLog, + AMTMessageLog, `http://intel.com/wbem/wscim/1/amt-schema/1/AMT_MessageLog/PositionToFirstRecord`, ``, func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.PositionToFirstRecord() }, Body{ @@ -348,11 +357,12 @@ func TestNegativeAMT_MessageLog(t *testing.T) { // GET RECORDS { "should return a valid amt_MessageLog GetRecords wsman message", - AMT_MessageLog, + AMTMessageLog, `http://intel.com/wbem/wscim/1/amt-schema/1/AMT_MessageLog/GetRecords`, `1390`, func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.GetRecords(1) }, Body{ @@ -370,7 +380,7 @@ func TestNegativeAMT_MessageLog(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, "", test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, "", test.body) messageID++ response, err := test.responseFunc() assert.Error(t, err) diff --git a/pkg/wsman/amt/messagelog/marshal.go b/pkg/wsman/amt/messagelog/marshal.go index 587e4920..fc5be410 100644 --- a/pkg/wsman/amt/messagelog/marshal.go +++ b/pkg/wsman/amt/messagelog/marshal.go @@ -11,20 +11,22 @@ import ( "gopkg.in/yaml.v3" ) -// JSON marshals the type into JSON format +// JSON marshals the type into JSON format. func (r *Response) JSON() string { jsonOutput, err := json.Marshal(r.Body) if err != nil { return "" } + return string(jsonOutput) } -// YAML marshals the type into YAML format +// YAML marshals the type into YAML format. func (r *Response) YAML() string { yamlOutput, err := yaml.Marshal(r.Body) if err != nil { return "" } + return string(yamlOutput) } diff --git a/pkg/wsman/amt/messagelog/types.go b/pkg/wsman/amt/messagelog/types.go index 6c0c7b9e..8b9a4f47 100644 --- a/pkg/wsman/amt/messagelog/types.go +++ b/pkg/wsman/amt/messagelog/types.go @@ -13,12 +13,12 @@ import ( "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/common" ) -type MessageLog struct { +type Service struct { base message.Base } // OUTPUTS -// Response Types +// Response Types. type ( Response struct { *client.Message @@ -118,7 +118,7 @@ type ( PositionToFirstRecordReturnValue int ) -// INPUTS +// INPUTS. type GetRecords_INPUT struct { XMLName xml.Name `xml:"h:GetRecords_INPUT"` H string `xml:"xmlns:h,attr"` diff --git a/pkg/wsman/amt/messages.go b/pkg/wsman/amt/messages.go index c92c0750..d47a6ba4 100644 --- a/pkg/wsman/amt/messages.go +++ b/pkg/wsman/amt/messages.go @@ -3,7 +3,7 @@ * SPDX-License-Identifier: Apache-2.0 **********************************************************************/ -// Package amt implements AMT classes to support communicating with Intel® AMT Devices +// Package amt implements AMT classes to support communicating with Intel® AMT Devices. package amt import ( @@ -32,12 +32,12 @@ import ( "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/client" ) -// Messages contains the supported AMT classes +// Messages contains the supported AMT classes. type Messages struct { wsmanMessageCreator *message.WSManMessageCreator AlarmClockService alarmclock.Service AuditLog auditlog.Service - AuthorizationService authorization.AuthorizationService + AuthorizationService authorization.Service BootCapabilities boot.Capabilities BootSettingData boot.SettingData EnvironmentDetectionSettingData environmentdetection.SettingData @@ -47,7 +47,7 @@ type Messages struct { IEEE8021xProfile ieee8021x.Profile KerberosSettingData kerberos.SettingData ManagementPresenceRemoteSAP managementpresence.RemoteSAP - MessageLog messagelog.MessageLog + MessageLog messagelog.Service MPSUsernamePassword mps.UsernamePassword PublicKeyCertificate publickey.Certificate PublicKeyManagementService publickey.ManagementService @@ -65,7 +65,7 @@ type Messages struct { WiFiPortConfigurationService wifiportconfiguration.Service } -// NewMessages instantiates a new instance of amt Messages +// NewMessages instantiates a new instance of amt Messages. func NewMessages(client client.WSMan) Messages { resourceUriBase := "http://intel.com/wbem/wscim/1/amt-schema/1/" wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) @@ -100,5 +100,6 @@ func NewMessages(client client.WSMan) Messages { m.TLSSettingData = tls.NewTLSSettingDataWithClient(wsmanMessageCreator, client) m.UserInitiatedConnectionService = userinitiatedconnection.NewUserInitiatedConnectionServiceWithClient(wsmanMessageCreator, client) m.WiFiPortConfigurationService = wifiportconfiguration.NewWiFiPortConfigurationServiceWithClient(wsmanMessageCreator, client) + return m } diff --git a/pkg/wsman/amt/messages_test.go b/pkg/wsman/amt/messages_test.go index 826d1e0d..65a1fb1a 100644 --- a/pkg/wsman/amt/messages_test.go +++ b/pkg/wsman/amt/messages_test.go @@ -40,87 +40,115 @@ func TestNewMessages(t *testing.T) { if m.wsmanMessageCreator == nil { t.Error("wsmanMessageCreator is not initialized") } + if reflect.DeepEqual(m.AlarmClockService, alarmclock.Service{}) { t.Error("AlarmClockService is not initialized") } + if reflect.DeepEqual(m.AuditLog, auditlog.Service{}) { t.Error("AuditLog is not initialized") } - if reflect.DeepEqual(m.AuthorizationService, authorization.AuthorizationService{}) { + + if reflect.DeepEqual(m.AuthorizationService, authorization.Service{}) { t.Error("AuthorizationService is not initialized") } + if reflect.DeepEqual(m.BootCapabilities, boot.Capabilities{}) { t.Error("BootCapabilities is not initialized") } + if reflect.DeepEqual(m.BootSettingData, boot.SettingData{}) { t.Error("BootSettingData is not initialized") } + if reflect.DeepEqual(m.EnvironmentDetectionSettingData, environmentdetection.SettingData{}) { t.Error("EnvironmentDetectionSettingData is not initialized") } + if reflect.DeepEqual(m.EthernetPortSettings, ethernetport.Settings{}) { t.Error("EthernetPortSettings is not initialized") } + if reflect.DeepEqual(m.GeneralSettings, general.Settings{}) { t.Error("GeneralSettings is not initialized") } + if reflect.DeepEqual(m.IEEE8021xCredentialContext, ieee8021x.CredentialContext{}) { t.Error("IEEE8021xCredentialContext is not initialized") } + if reflect.DeepEqual(m.IEEE8021xProfile, ieee8021x.Profile{}) { t.Error("IEEE8021xProfile is not initialized") } + if reflect.DeepEqual(m.KerberosSettingData, kerberos.SettingData{}) { t.Error("KerberosSettingData is not initialized") } + if reflect.DeepEqual(m.ManagementPresenceRemoteSAP, managementpresence.RemoteSAP{}) { t.Error("ManagementPresenceRemoteSAP is not initialized") } - if reflect.DeepEqual(m.MessageLog, messagelog.MessageLog{}) { + + if reflect.DeepEqual(m.MessageLog, messagelog.Service{}) { t.Error("MessageLog is not initialized") } + if reflect.DeepEqual(m.MPSUsernamePassword, mps.UsernamePassword{}) { t.Error("MPSUsernamePassword is not initialized") } + if reflect.DeepEqual(m.PublicKeyCertificate, publickey.Certificate{}) { t.Error("PublicKeyCertificate is not initialized") } + if reflect.DeepEqual(m.PublicKeyManagementService, publickey.ManagementService{}) { t.Error("PublicKeyManagementService is not initialized") } + if reflect.DeepEqual(m.PublicPrivateKeyPair, publicprivate.KeyPair{}) { t.Error("PublicPrivateKeyPair is not initialized") } + if reflect.DeepEqual(m.RedirectionService, redirection.Service{}) { t.Error("RedirectionService is not initialized") } + if reflect.DeepEqual(m.RemoteAccessPolicyAppliesToMPS, remoteaccess.PolicyAppliesToMPS{}) { t.Error("RemoteAccessPolicyAppliesToMPS is not initialized") } + if reflect.DeepEqual(m.RemoteAccessPolicyRule, remoteaccess.PolicyRule{}) { t.Error("RemoteAccessPolicyRule is not initialized") } + if reflect.DeepEqual(m.RemoteAccessService, remoteaccess.Service{}) { t.Error("RemoteAccessService is not initialized") } + if reflect.DeepEqual(m.SetupAndConfigurationService, setupandconfiguration.Service{}) { t.Error("SetupAndConfigurationService is not initialized") } + if reflect.DeepEqual(m.TimeSynchronizationService, timesynchronization.Service{}) { t.Error("TimeSynchronizationService is not initialized") } + if reflect.DeepEqual(m.TLSCredentialContext, tls.CredentialContext{}) { t.Error("TLSCredentialContext is not initialized") } + if reflect.DeepEqual(m.TLSProtocolEndpointCollection, tls.ProtocolEndpointCollection{}) { t.Error("TLSProtocolEndpointCollection is not initialized") } + if reflect.DeepEqual(m.TLSSettingData, tls.SettingData{}) { t.Error("TLSSettingData is not initialized") } + if reflect.DeepEqual(m.UserInitiatedConnectionService, userinitiatedconnection.Service{}) { t.Error("UserInitiatedConnectionService is not initialized") } + if reflect.DeepEqual(m.WiFiPortConfigurationService, wifiportconfiguration.Service{}) { t.Error("WiFiPortConfigurationService is not initialized") } diff --git a/pkg/wsman/amt/methods/methods.go b/pkg/wsman/amt/methods/methods.go index 4a9641df..f15d1c73 100644 --- a/pkg/wsman/amt/methods/methods.go +++ b/pkg/wsman/amt/methods/methods.go @@ -8,17 +8,17 @@ package methods import "fmt" -// RequestStateChange creates an amt specific request state change action +// RequestStateChange creates an amt specific request state change action. func RequestStateChange(className string) string { return fmt.Sprintf("http://intel.com/wbem/wscim/1/amt-schema/1/%s/RequestStateChange", className) } -// GenerateAction creates an amt specific action for custom methods -func GenerateAction(className string, methodName string) string { +// GenerateAction creates an amt specific action for custom methods. +func GenerateAction(className, methodName string) string { return fmt.Sprintf("http://intel.com/wbem/wscim/1/amt-schema/1/%s/%s", className, methodName) } -// GenerateInputMethod creates the string used to populate the XML tag for INPUT calls +// GenerateInputMethod creates the string used to populate the XML tag for INPUT calls. func GenerateInputMethod(methodName string) string { return fmt.Sprintf("%s_INPUT", methodName) } diff --git a/pkg/wsman/amt/methods/methods_test.go b/pkg/wsman/amt/methods/methods_test.go index f2f4d009..f5760c27 100644 --- a/pkg/wsman/amt/methods/methods_test.go +++ b/pkg/wsman/amt/methods/methods_test.go @@ -11,23 +11,28 @@ import ( "github.com/stretchr/testify/assert" ) +const ( + TestMethod string = "TestMethod" + AMTTest string = "AMT_Test" +) + func TestMethods(t *testing.T) { t.Run("GenerateAction Test", func(t *testing.T) { expectedResult := "http://intel.com/wbem/wscim/1/amt-schema/1/AMT_Test/TestMethod" - className := "AMT_Test" - methodName := "TestMethod" + className := AMTTest + methodName := TestMethod result := GenerateAction(className, methodName) assert.Equal(t, expectedResult, result) }) t.Run("GenerateMethod Test", func(t *testing.T) { expectedResult := "TestMethod_INPUT" - methodName := "TestMethod" + methodName := TestMethod result := GenerateInputMethod(methodName) assert.Equal(t, expectedResult, result) }) t.Run("RequestStateChange Test", func(t *testing.T) { expectedResult := "http://intel.com/wbem/wscim/1/amt-schema/1/AMT_Test/RequestStateChange" - className := "AMT_Test" + className := AMTTest result := RequestStateChange(className) assert.Equal(t, expectedResult, result) }) diff --git a/pkg/wsman/amt/mps/constants.go b/pkg/wsman/amt/mps/constants.go index f06c750c..29af062e 100644 --- a/pkg/wsman/amt/mps/constants.go +++ b/pkg/wsman/amt/mps/constants.go @@ -6,5 +6,5 @@ package mps const ( - AMT_MPSUsernamePassword string = "AMT_MPSUsernamePassword" + AMTMPSUsernamePassword string = "AMT_MPSUsernamePassword" ) diff --git a/pkg/wsman/amt/mps/marshal.go b/pkg/wsman/amt/mps/marshal.go index 7b2a2624..953bdb59 100644 --- a/pkg/wsman/amt/mps/marshal.go +++ b/pkg/wsman/amt/mps/marshal.go @@ -11,20 +11,22 @@ import ( "gopkg.in/yaml.v3" ) -// JSON marshals the type into JSON format +// JSON marshals the type into JSON format. func (r *Response) JSON() string { jsonOutput, err := json.Marshal(r.Body) if err != nil { return "" } + return string(jsonOutput) } -// YAML marshals the type into YAML format +// YAML marshals the type into YAML format. func (r *Response) YAML() string { yamlOutput, err := yaml.Marshal(r.Body) if err != nil { return "" } + return string(yamlOutput) } diff --git a/pkg/wsman/amt/mps/types.go b/pkg/wsman/amt/mps/types.go index 70758081..d1870e89 100644 --- a/pkg/wsman/amt/mps/types.go +++ b/pkg/wsman/amt/mps/types.go @@ -18,7 +18,7 @@ type UsernamePassword struct { } // OUTPUTS -// Response Types +// Response Types. type ( Response struct { *client.Message @@ -50,7 +50,7 @@ type ( ) // INPUTS -// Request Types +// Request Types. type ( MPSUsernamePasswordRequest struct { XMLName xml.Name `xml:"h:AMT_MPSUsernamePassword"` diff --git a/pkg/wsman/amt/mps/usernamepassword.go b/pkg/wsman/amt/mps/usernamepassword.go index 563665a1..d755b721 100644 --- a/pkg/wsman/amt/mps/usernamepassword.go +++ b/pkg/wsman/amt/mps/usernamepassword.go @@ -14,14 +14,14 @@ import ( "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/client" ) -// NewMPSUsernamePasswordWithClient instantiates a new UsernamePassword +// NewMPSUsernamePasswordWithClient instantiates a new UsernamePassword. func NewMPSUsernamePasswordWithClient(wsmanMessageCreator *message.WSManMessageCreator, client client.WSMan) UsernamePassword { return UsernamePassword{ - base: message.NewBaseWithClient(wsmanMessageCreator, AMT_MPSUsernamePassword, client), + base: message.NewBaseWithClient(wsmanMessageCreator, AMTMPSUsernamePassword, client), } } -// Get retrieves the representation of the instance +// Get retrieves the representation of the instance. func (usernamePassword UsernamePassword) Get() (response Response, err error) { response = Response{ Message: &client.Message{ @@ -38,10 +38,11 @@ func (usernamePassword UsernamePassword) Get() (response Response, err error) { if err != nil { return } + return } -// Enumerate returns an enumeration context which is used in a subsequent Pull call +// Enumerate returns an enumeration context which is used in a subsequent Pull call. func (usernamePassword UsernamePassword) Enumerate() (response Response, err error) { response = Response{ Message: &client.Message{ @@ -58,6 +59,7 @@ func (usernamePassword UsernamePassword) Enumerate() (response Response, err err if err != nil { return } + return } @@ -78,12 +80,13 @@ func (usernamePassword UsernamePassword) Pull(enumerationContext string) (respon if err != nil { return } + return } -// Put will change properties of the selected instance +// Put will change properties of the selected instance. func (usernamePassword UsernamePassword) Put(mpsUsernamePassword MPSUsernamePasswordRequest) (response Response, err error) { - mpsUsernamePassword.H = fmt.Sprintf("%s%s", message.AMTSchema, AMT_MPSUsernamePassword) + mpsUsernamePassword.H = fmt.Sprintf("%s%s", message.AMTSchema, AMTMPSUsernamePassword) response = Response{ Message: &client.Message{ XMLInput: usernamePassword.base.Put(mpsUsernamePassword, false, nil), @@ -99,5 +102,6 @@ func (usernamePassword UsernamePassword) Put(mpsUsernamePassword MPSUsernamePass if err != nil { return } + return } diff --git a/pkg/wsman/amt/mps/usernamepassword_test.go b/pkg/wsman/amt/mps/usernamepassword_test.go index 437531d2..300d94b4 100644 --- a/pkg/wsman/amt/mps/usernamepassword_test.go +++ b/pkg/wsman/amt/mps/usernamepassword_test.go @@ -9,11 +9,10 @@ import ( "encoding/xml" "testing" - "github.com/stretchr/testify/assert" - "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/internal/message" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/common" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/wsmantesting" + "github.com/stretchr/testify/assert" ) func TestJson(t *testing.T) { @@ -40,8 +39,8 @@ func TestYaml(t *testing.T) { func TestPositiveAMT_MPSUsernamePassword(t *testing.T) { messageID := 0 - resourceUriBase := "http://intel.com/wbem/wscim/1/amt-schema/1/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.AMTResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "amt/mps", } @@ -56,14 +55,15 @@ func TestPositiveAMT_MPSUsernamePassword(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //GETS + // GETS { "should create a valid AMT_MPSUsernamePassword Get wsman message", - AMT_MPSUsernamePassword, - wsmantesting.GET, + AMTMPSUsernamePassword, + wsmantesting.Get, "", func() (Response, error) { - client.CurrentMessage = "Get" + client.CurrentMessage = wsmantesting.CurrentMessageGet + return elementUnderTest.Get() }, Body{ @@ -75,14 +75,15 @@ func TestPositiveAMT_MPSUsernamePassword(t *testing.T) { }, }, }, - //ENUMERATES + // ENUMERATES { "should create a valid AMT_MPSUsernamePassword Enumerate wsman message", - AMT_MPSUsernamePassword, - wsmantesting.ENUMERATE, - wsmantesting.ENUMERATE_BODY, + AMTMPSUsernamePassword, + wsmantesting.Enumerate, + wsmantesting.EnumerateBody, func() (Response, error) { - client.CurrentMessage = "Enumerate" + client.CurrentMessage = wsmantesting.CurrentMessageEnumerate + return elementUnderTest.Enumerate() }, Body{ @@ -92,14 +93,15 @@ func TestPositiveAMT_MPSUsernamePassword(t *testing.T) { }, }, }, - //PULLS + // PULLS { "should create a valid AMT_MPSUsernamePassword Pull wsman message", - AMT_MPSUsernamePassword, - wsmantesting.PULL, - wsmantesting.PULL_BODY, + AMTMPSUsernamePassword, + wsmantesting.Pull, + wsmantesting.PullBody, func() (Response, error) { - client.CurrentMessage = "Pull" + client.CurrentMessage = wsmantesting.CurrentMessagePull + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -118,17 +120,18 @@ func TestPositiveAMT_MPSUsernamePassword(t *testing.T) { }, { "should create a valid AMT_MPSUsernamePassword Put wsman message", - AMT_MPSUsernamePassword, - wsmantesting.PUT, + AMTMPSUsernamePassword, + wsmantesting.Put, "Intel(r) AMT:MPS Username Password 0testP@ssw0rd", func() (Response, error) { - client.CurrentMessage = "Put" + client.CurrentMessage = wsmantesting.CurrentMessagePut mpsUsernamePassword := MPSUsernamePasswordRequest{ H: "http://intel.com/wbem/wscim/1/amt-schema/1/AMT_MPSUsernamePassword", InstanceID: "Intel(r) AMT:MPS Username Password 0", Secret: "P@ssw0rd", RemoteID: "test", } + return elementUnderTest.Put(mpsUsernamePassword) }, Body{ @@ -139,7 +142,7 @@ func TestPositiveAMT_MPSUsernamePassword(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, "", test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, "", test.body) messageID++ response, err := test.responseFunc() assert.NoError(t, err) @@ -149,10 +152,11 @@ func TestPositiveAMT_MPSUsernamePassword(t *testing.T) { } }) } + func TestNegativeAMT_MPSUsernamePassword(t *testing.T) { messageID := 0 - resourceUriBase := "http://intel.com/wbem/wscim/1/amt-schema/1/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.AMTResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "amt/mps", } @@ -167,14 +171,15 @@ func TestNegativeAMT_MPSUsernamePassword(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //GETS + // GETS { "should create a valid AMT_MPSUsernamePassword Get wsman message", - AMT_MPSUsernamePassword, - wsmantesting.GET, + AMTMPSUsernamePassword, + wsmantesting.Get, "", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Get() }, Body{ @@ -186,14 +191,15 @@ func TestNegativeAMT_MPSUsernamePassword(t *testing.T) { }, }, }, - //ENUMERATES + // ENUMERATES { "should create a valid AMT_MPSUsernamePassword Enumerate wsman message", - AMT_MPSUsernamePassword, - wsmantesting.ENUMERATE, - wsmantesting.ENUMERATE_BODY, + AMTMPSUsernamePassword, + wsmantesting.Enumerate, + wsmantesting.EnumerateBody, func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Enumerate() }, Body{ @@ -203,14 +209,15 @@ func TestNegativeAMT_MPSUsernamePassword(t *testing.T) { }, }, }, - //PULLS + // PULLS { "should create a valid AMT_MPSUsernamePassword Pull wsman message", - AMT_MPSUsernamePassword, - wsmantesting.PULL, - wsmantesting.PULL_BODY, + AMTMPSUsernamePassword, + wsmantesting.Pull, + wsmantesting.PullBody, func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -229,17 +236,18 @@ func TestNegativeAMT_MPSUsernamePassword(t *testing.T) { }, { "should create a valid AMT_MPSUsernamePassword Put wsman message", - AMT_MPSUsernamePassword, - wsmantesting.PUT, + AMTMPSUsernamePassword, + wsmantesting.Put, "Intel(r) AMT:MPS Username Password 0testP@ssw0rd", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError mpsUsernamePassword := MPSUsernamePasswordRequest{ H: "http://intel.com/wbem/wscim/1/amt-schema/1/AMT_MPSUsernamePassword", InstanceID: "Intel(r) AMT:MPS Username Password 0", Secret: "P@ssw0rd", RemoteID: "test", } + return elementUnderTest.Put(mpsUsernamePassword) }, Body{ @@ -250,7 +258,7 @@ func TestNegativeAMT_MPSUsernamePassword(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, "", test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, "", test.body) messageID++ response, err := test.responseFunc() assert.Error(t, err) diff --git a/pkg/wsman/amt/publickey/certificate.go b/pkg/wsman/amt/publickey/certificate.go index e469136b..b0fe20fb 100644 --- a/pkg/wsman/amt/publickey/certificate.go +++ b/pkg/wsman/amt/publickey/certificate.go @@ -20,14 +20,14 @@ import ( "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/client" ) -// NewPublicKeyCertificateWithClient instantiates a new Certificate +// NewPublicKeyCertificateWithClient instantiates a new Certificate. func NewPublicKeyCertificateWithClient(wsmanMessageCreator *message.WSManMessageCreator, client client.WSMan) Certificate { return Certificate{ - base: message.NewBaseWithClient(wsmanMessageCreator, AMT_PublicKeyCertificate, client), + base: message.NewBaseWithClient(wsmanMessageCreator, AMTPublicKeyCertificate, client), } } -// Get retrieves the representation of the instance +// Get retrieves the representation of the instance. func (certificate Certificate) Get(instanceID string) (response Response, err error) { selector := message.Selector{ Name: "InstanceID", @@ -48,10 +48,11 @@ func (certificate Certificate) Get(instanceID string) (response Response, err er if err != nil { return } + return } -// Enumerate returns an enumeration context which is used in a subsequent Pull call +// Enumerate returns an enumeration context which is used in a subsequent Pull call. func (certificate Certificate) Enumerate() (response Response, err error) { response = Response{ Message: &client.Message{ @@ -68,6 +69,7 @@ func (certificate Certificate) Enumerate() (response Response, err error) { if err != nil { return } + return } @@ -88,18 +90,19 @@ func (certificate Certificate) Pull(enumerationContext string) (response Respons if err != nil { return } + return } -// Put will change properties of the selected instance -func (certificate Certificate) Put(instanceId string, cert string) (response Response, err error) { +// Put will change properties of the selected instance. +func (certificate Certificate) Put(instanceID, cert string) (response Response, err error) { selector := message.Selector{ Name: "InstanceID", - Value: instanceId, + Value: instanceID, } publicKeyCertificate := PublicKeyCertificateRequest{} publicKeyCertificate.X509Certificate = cert - publicKeyCertificate.H = fmt.Sprintf("%s%s", message.AMTSchema, AMT_PublicKeyCertificate) + publicKeyCertificate.H = fmt.Sprintf("%s%s", message.AMTSchema, AMTPublicKeyCertificate) response = Response{ Message: &client.Message{ XMLInput: certificate.base.Put(publicKeyCertificate, true, &selector), @@ -115,10 +118,11 @@ func (certificate Certificate) Put(instanceId string, cert string) (response Res if err != nil { return } + return } -// Delete removes a the specified instance +// Delete removes a the specified instance. func (certificate Certificate) Delete(instanceID string) (response Response, err error) { selector := message.Selector{Name: "InstanceID", Value: instanceID} response = Response{ @@ -136,5 +140,6 @@ func (certificate Certificate) Delete(instanceID string) (response Response, err if err != nil { return } + return } diff --git a/pkg/wsman/amt/publickey/certificate_test.go b/pkg/wsman/amt/publickey/certificate_test.go index 8317479f..0ea1a410 100644 --- a/pkg/wsman/amt/publickey/certificate_test.go +++ b/pkg/wsman/amt/publickey/certificate_test.go @@ -10,20 +10,22 @@ import ( "fmt" "testing" - "github.com/stretchr/testify/assert" - "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/internal/message" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/common" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/wsmantesting" + "github.com/sirupsen/logrus" + "github.com/stretchr/testify/assert" ) +const X509TestCertificate = "MIIEOzCCAqOgAwIBAgIDAZMjMA0GCSqGSIb3DQEBDAUAMD0xFzAVBgNVBAMTDk1QU1Jvb3QtMGFmMWQ1MRAwDgYDVQQKEwd1bmtub3duMRAwDgYDVQQGEwd1bmtub3duMCAXDTIyMDkyNDEwNDUwOFoYDzIwNTMwOTI0MTA0NTA4WjA9MRcwFQYDVQQDEw5NUFNSb290LTBhZjFkNTEQMA4GA1UEChMHdW5rbm93bjEQMA4GA1UEBhMHdW5rbm93bjCCAaIwDQYJKoZIhvcNAQEBBQADggGPADCCAYoCggGBALz/oJNyWXlClSlteAieC8Uyd4A+tbn8b45k6LKiImhDmdz/xFo9xe0C9GNf7b42KVpg5WoH/sPhoClR9Tv5i1LnilT1SUir42fcm2NEV9dRcLsPd/RAQfz8u0D4zb3blnxE8isqzriNpG7kac35UidSr5ym8TZ3IwXx6JJuncGgfB0DFZADC/+dA74n3coykvWBYqLr6RI5pkAxvulkRlCsatJTJrvMUYJ51GI28jV56mIAc89sLrHqiSKCZBH9AcUrnZ/cB6ST/IikXpxy5wXBIvWT3VKVq75T/uIoCBEp5TLEn1EOYGqBBOCSQgmtmX7eVaB0s1+ppPW9w9a2zS45cHAtQ7tYvkkPv2dRhSzZdlk6HRXDP5wsF0aiflZCgbrjkq0SFC4e3Lo7XQX3FTNb0SOTZVTydupoMKkgJQTNlcosdu1ZzaIBl3eSkKkJZz2rUTssZC5tn9vcDd5vy3BzcGh5pvkgfAgN1sydqG7Ke1qCkNEzm11B/BsevatjjwIDAQABo0IwQDAMBgNVHRMEBTADAQH/MBEGCWCGSAGG+EIBAQQEAwIABzAdBgNVHQ4EFgQUCvHVQqerCid99eLApuLky9x6H5owDQYJKoZIhvcNAQEMBQADggGBAIzOyGV0hzsmH2biJlzwTZaHMxqS7boTFMkHw+KvzsI201tHqVmCoiQ8EHErBGLSoDOTDRgOUGOCA5XU5ie9OWupAGqKBSwIyAhmJMOzrzC4Gwpu8K1msoFJH30kx/V9purpbS3BRj0xfYXLa6IczbTg3E5IfTnZRJ9YuUtKQfI0P9c5U9CoKtddKn4+lRvOjFDoYfQGCJ7go3xjNCcGCVCjfkUhAVdbQ21DCRr6/YCZDWmjzZpL0p7UKF8roTiNuL/Z7gIXxch5HOmEWHY9uQ6K2MntuxAu0aK/mSD2kwmt/ECongdEGfUvhULLoPRQlQ2LnzcUQEgMECGQR5Yfy9jT0E8zdWDpc2tgVioNu6rEYKgp/GhG+sv7jv58pW82FRAV9xXtftW9+XDugC8tBJ6JHn0Q2v0QAflD2CEQVhWAY8bAqrbfTGUsaLfGL6kxV/qqssoMgLR8WhQ96T5le/4XGhQpbCHWIlctD6MwbrsunIAeQKp1Sc3DosY7DLq1MQ==" + func TestJson(t *testing.T) { response := Response{ Body: Body{ AddCertificate_OUTPUT: AddCertificate_OUTPUT{}, }, } - expectedResult := "{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"AddTrustedRootCertificate_OUTPUT\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"CreatedCertificate\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"Address\":\"\",\"ReferenceParameters\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"ResourceURI\":\"\",\"SelectorSet\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"Selectors\":null}}},\"ReturnValue\":0},\"AddCertificate_OUTPUT\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"CreatedCertificate\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"Address\":\"\",\"ReferenceParameters\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"ResourceURI\":\"\",\"SelectorSet\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"Selectors\":null}}},\"ReturnValue\":0},\"AddKey_OUTPUT\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"CreatedKey\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"Address\":\"\",\"ReferenceParameters\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"ResourceURI\":\"\",\"SelectorSet\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"Selectors\":null}}},\"ReturnValue\":0},\"GenerateKeyPair_OUTPUT\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"KeyPair\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"Address\":\"\",\"ReferenceParameters\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"ResourceURI\":\"\",\"SelectorSet\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"Selectors\":null}}},\"ReturnValue\":0},\"GeneratePKCS10RequestEx_OUTPUT\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"SignedCertificateRequest\":\"\",\"ReturnValue\":0},\"KeyManagementGetResponse\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"CreationClassName\":\"\",\"ElementName\":\"\",\"EnabledDefault\":0,\"EnabledState\":0,\"Name\":\"\",\"OperationalStatus\":null,\"RequestedState\":0,\"SystemCreationClassName\":\"\",\"SystemName\":\"\"},\"PublicKeyCertificateGetAndPutResponse\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"ElementName\":\"\",\"InstanceID\":\"\",\"X509Certificate\":\"\",\"TrustedRootCertificate\":false,\"Issuer\":\"\",\"Subject\":\"\",\"ReadOnlyCertificate\":false},\"EnumerateResponse\":{\"EnumerationContext\":\"\"},\"PullResponse\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"KeyManagementItems\":null,\"PublicKeyCertificateItems\":null}}" + expectedResult := "{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"AddTrustedRootCertificateOutput\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"CreatedCertificate\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"Address\":\"\",\"ReferenceParameters\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"ResourceURI\":\"\",\"SelectorSet\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"Selectors\":null}}},\"ReturnValue\":0},\"AddCertificateOutput\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"CreatedCertificate\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"Address\":\"\",\"ReferenceParameters\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"ResourceURI\":\"\",\"SelectorSet\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"Selectors\":null}}},\"ReturnValue\":0},\"AddKeyOutput\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"CreatedKey\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"Address\":\"\",\"ReferenceParameters\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"ResourceURI\":\"\",\"SelectorSet\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"Selectors\":null}}},\"ReturnValue\":0},\"GenerateKeyPairOutput\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"KeyPair\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"Address\":\"\",\"ReferenceParameters\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"ResourceURI\":\"\",\"SelectorSet\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"Selectors\":null}}},\"ReturnValue\":0},\"GeneratePKCS10RequestExOutput\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"SignedCertificateRequest\":\"\",\"ReturnValue\":0},\"KeyManagementGetResponse\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"CreationClassName\":\"\",\"ElementName\":\"\",\"EnabledDefault\":0,\"EnabledState\":0,\"Name\":\"\",\"OperationalStatus\":null,\"RequestedState\":0,\"SystemCreationClassName\":\"\",\"SystemName\":\"\"},\"PublicKeyCertificateGetAndPutResponse\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"ElementName\":\"\",\"InstanceID\":\"\",\"X509Certificate\":\"\",\"TrustedRootCertificate\":false,\"Issuer\":\"\",\"Subject\":\"\",\"ReadOnlyCertificate\":false},\"EnumerateResponse\":{\"EnumerationContext\":\"\"},\"PullResponse\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"KeyManagementItems\":null,\"PublicKeyCertificateItems\":null}}" result := response.JSON() assert.Equal(t, expectedResult, result) } @@ -34,19 +36,20 @@ func TestYaml(t *testing.T) { AddCertificate_OUTPUT: AddCertificate_OUTPUT{}, }, } - expectedResult := "xmlname:\n space: \"\"\n local: \"\"\naddtrustedrootcertificate_output:\n xmlname:\n space: \"\"\n local: \"\"\n createdcertificate:\n xmlname:\n space: \"\"\n local: \"\"\n address: \"\"\n referenceparameters:\n xmlname:\n space: \"\"\n local: \"\"\n resourceuri: \"\"\n selectorset:\n xmlname:\n space: \"\"\n local: \"\"\n selectors: []\n returnvalue: 0\naddcertificate_output:\n xmlname:\n space: \"\"\n local: \"\"\n createdcertificate:\n xmlname:\n space: \"\"\n local: \"\"\n address: \"\"\n referenceparameters:\n xmlname:\n space: \"\"\n local: \"\"\n resourceuri: \"\"\n selectorset:\n xmlname:\n space: \"\"\n local: \"\"\n selectors: []\n returnvalue: 0\naddkey_output:\n xmlname:\n space: \"\"\n local: \"\"\n createdkey:\n xmlname:\n space: \"\"\n local: \"\"\n address: \"\"\n referenceparameters:\n xmlname:\n space: \"\"\n local: \"\"\n resourceuri: \"\"\n selectorset:\n xmlname:\n space: \"\"\n local: \"\"\n selectors: []\n returnvalue: 0\ngeneratekeypair_output:\n xmlname:\n space: \"\"\n local: \"\"\n keypair:\n xmlname:\n space: \"\"\n local: \"\"\n address: \"\"\n referenceparameters:\n xmlname:\n space: \"\"\n local: \"\"\n resourceuri: \"\"\n selectorset:\n xmlname:\n space: \"\"\n local: \"\"\n selectors: []\n returnvalue: 0\ngeneratepkcs10requestex_output:\n xmlname:\n space: \"\"\n local: \"\"\n signedcertificaterequest: \"\"\n returnvalue: 0\nkeymanagementgetresponse:\n xmlname:\n space: \"\"\n local: \"\"\n creationclassname: \"\"\n elementname: \"\"\n enableddefault: 0\n enabledstate: 0\n name: \"\"\n operationalstatus: []\n requestedstate: 0\n systemcreationclassname: \"\"\n systemname: \"\"\npublickeycertificategetandputresponse:\n xmlname:\n space: \"\"\n local: \"\"\n elementname: \"\"\n instanceid: \"\"\n x509certificate: \"\"\n trustedrootcertificate: false\n issuer: \"\"\n subject: \"\"\n readonlycertificate: false\nenumerateresponse:\n enumerationcontext: \"\"\npullresponse:\n xmlname:\n space: \"\"\n local: \"\"\n keymanagementitems: []\n publickeycertificateitems: []\n" + expectedResult := "xmlname:\n space: \"\"\n local: \"\"\naddtrustedrootcertificateoutput:\n xmlname:\n space: \"\"\n local: \"\"\n createdcertificate:\n xmlname:\n space: \"\"\n local: \"\"\n address: \"\"\n referenceparameters:\n xmlname:\n space: \"\"\n local: \"\"\n resourceuri: \"\"\n selectorset:\n xmlname:\n space: \"\"\n local: \"\"\n selectors: []\n returnvalue: 0\naddcertificateoutput:\n xmlname:\n space: \"\"\n local: \"\"\n createdcertificate:\n xmlname:\n space: \"\"\n local: \"\"\n address: \"\"\n referenceparameters:\n xmlname:\n space: \"\"\n local: \"\"\n resourceuri: \"\"\n selectorset:\n xmlname:\n space: \"\"\n local: \"\"\n selectors: []\n returnvalue: 0\naddkeyoutput:\n xmlname:\n space: \"\"\n local: \"\"\n createdkey:\n xmlname:\n space: \"\"\n local: \"\"\n address: \"\"\n referenceparameters:\n xmlname:\n space: \"\"\n local: \"\"\n resourceuri: \"\"\n selectorset:\n xmlname:\n space: \"\"\n local: \"\"\n selectors: []\n returnvalue: 0\ngeneratekeypairoutput:\n xmlname:\n space: \"\"\n local: \"\"\n keypair:\n xmlname:\n space: \"\"\n local: \"\"\n address: \"\"\n referenceparameters:\n xmlname:\n space: \"\"\n local: \"\"\n resourceuri: \"\"\n selectorset:\n xmlname:\n space: \"\"\n local: \"\"\n selectors: []\n returnvalue: 0\ngeneratepkcs10requestexoutput:\n xmlname:\n space: \"\"\n local: \"\"\n signedcertificaterequest: \"\"\n returnvalue: 0\nkeymanagementgetresponse:\n xmlname:\n space: \"\"\n local: \"\"\n creationclassname: \"\"\n elementname: \"\"\n enableddefault: 0\n enabledstate: 0\n name: \"\"\n operationalstatus: []\n requestedstate: 0\n systemcreationclassname: \"\"\n systemname: \"\"\npublickeycertificategetandputresponse:\n xmlname:\n space: \"\"\n local: \"\"\n elementname: \"\"\n instanceid: \"\"\n x509certificate: \"\"\n trustedrootcertificate: false\n issuer: \"\"\n subject: \"\"\n readonlycertificate: false\nenumerateresponse:\n enumerationcontext: \"\"\npullresponse:\n xmlname:\n space: \"\"\n local: \"\"\n keymanagementitems: []\n publickeycertificateitems: []\n" result := response.YAML() assert.Equal(t, expectedResult, result) } func TestPositiveAMT_PublicKeyCertificate(t *testing.T) { messageID := 0 - resourceUriBase := "http://intel.com/wbem/wscim/1/amt-schema/1/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.AMTResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "amt/publickey/certificate", } elementUnderTest := NewPublicKeyCertificateWithClient(wsmanMessageCreator, &client) + t.Run("amt_PublicKeyCertificate Tests", func(t *testing.T) { tests := []struct { name string @@ -57,42 +60,44 @@ func TestPositiveAMT_PublicKeyCertificate(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //GETS + // GETS { "should create a valid AMT_PublicKeyCertificate Get wsman message", - AMT_PublicKeyCertificate, - wsmantesting.GET, + AMTPublicKeyCertificate, + wsmantesting.Get, "", "Intel(r) AMT Certificate: Handle: 0", func() (Response, error) { - client.CurrentMessage = "Get" + client.CurrentMessage = wsmantesting.CurrentMessageGet + return elementUnderTest.Get("Intel(r) AMT Certificate: Handle: 0") }, Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, PublicKeyCertificateGetAndPutResponse: PublicKeyCertificateResponse{ - XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMT_PublicKeyCertificate), Local: "AMT_PublicKeyCertificate"}, + XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMTPublicKeyCertificate), Local: "AMT_PublicKeyCertificate"}, ElementName: "Intel(r) AMT Certificate", InstanceID: "Intel(r) AMT Certificate: Handle: 0", Issuer: "C=unknown,O=unknown,CN=MPSRoot-0af1d5", Subject: "C=unknown,O=unknown,CN=MPSRoot-0af1d5", TrustedRootCertificate: true, - X509Certificate: "MIIEOzCCAqOgAwIBAgIDAZMjMA0GCSqGSIb3DQEBDAUAMD0xFzAVBgNVBAMTDk1QU1Jvb3QtMGFmMWQ1MRAwDgYDVQQKEwd1bmtub3duMRAwDgYDVQQGEwd1bmtub3duMCAXDTIyMDkyNDEwNDUwOFoYDzIwNTMwOTI0MTA0NTA4WjA9MRcwFQYDVQQDEw5NUFNSb290LTBhZjFkNTEQMA4GA1UEChMHdW5rbm93bjEQMA4GA1UEBhMHdW5rbm93bjCCAaIwDQYJKoZIhvcNAQEBBQADggGPADCCAYoCggGBALz/oJNyWXlClSlteAieC8Uyd4A+tbn8b45k6LKiImhDmdz/xFo9xe0C9GNf7b42KVpg5WoH/sPhoClR9Tv5i1LnilT1SUir42fcm2NEV9dRcLsPd/RAQfz8u0D4zb3blnxE8isqzriNpG7kac35UidSr5ym8TZ3IwXx6JJuncGgfB0DFZADC/+dA74n3coykvWBYqLr6RI5pkAxvulkRlCsatJTJrvMUYJ51GI28jV56mIAc89sLrHqiSKCZBH9AcUrnZ/cB6ST/IikXpxy5wXBIvWT3VKVq75T/uIoCBEp5TLEn1EOYGqBBOCSQgmtmX7eVaB0s1+ppPW9w9a2zS45cHAtQ7tYvkkPv2dRhSzZdlk6HRXDP5wsF0aiflZCgbrjkq0SFC4e3Lo7XQX3FTNb0SOTZVTydupoMKkgJQTNlcosdu1ZzaIBl3eSkKkJZz2rUTssZC5tn9vcDd5vy3BzcGh5pvkgfAgN1sydqG7Ke1qCkNEzm11B/BsevatjjwIDAQABo0IwQDAMBgNVHRMEBTADAQH/MBEGCWCGSAGG+EIBAQQEAwIABzAdBgNVHQ4EFgQUCvHVQqerCid99eLApuLky9x6H5owDQYJKoZIhvcNAQEMBQADggGBAIzOyGV0hzsmH2biJlzwTZaHMxqS7boTFMkHw+KvzsI201tHqVmCoiQ8EHErBGLSoDOTDRgOUGOCA5XU5ie9OWupAGqKBSwIyAhmJMOzrzC4Gwpu8K1msoFJH30kx/V9purpbS3BRj0xfYXLa6IczbTg3E5IfTnZRJ9YuUtKQfI0P9c5U9CoKtddKn4+lRvOjFDoYfQGCJ7go3xjNCcGCVCjfkUhAVdbQ21DCRr6/YCZDWmjzZpL0p7UKF8roTiNuL/Z7gIXxch5HOmEWHY9uQ6K2MntuxAu0aK/mSD2kwmt/ECongdEGfUvhULLoPRQlQ2LnzcUQEgMECGQR5Yfy9jT0E8zdWDpc2tgVioNu6rEYKgp/GhG+sv7jv58pW82FRAV9xXtftW9+XDugC8tBJ6JHn0Q2v0QAflD2CEQVhWAY8bAqrbfTGUsaLfGL6kxV/qqssoMgLR8WhQ96T5le/4XGhQpbCHWIlctD6MwbrsunIAeQKp1Sc3DosY7DLq1MQ==", + X509Certificate: X509TestCertificate, }, }, }, - //ENUMERATES + // ENUMERATES { "should create a valid AMT_PublicKeyCertificate Enumerate wsman message", - AMT_PublicKeyCertificate, - wsmantesting.ENUMERATE, - wsmantesting.ENUMERATE_BODY, + AMTPublicKeyCertificate, + wsmantesting.Enumerate, + wsmantesting.EnumerateBody, "", func() (Response, error) { - client.CurrentMessage = "Enumerate" + client.CurrentMessage = wsmantesting.CurrentMessageEnumerate if elementUnderTest.base.WSManMessageCreator == nil { - print("Error") + logrus.Print("Error") } + return elementUnderTest.Enumerate() }, Body{ @@ -102,15 +107,16 @@ func TestPositiveAMT_PublicKeyCertificate(t *testing.T) { }, }, }, - //PULLS + // PULLS { "should create a valid AMT_PublicKeyCertificate Pull wsman message", - AMT_PublicKeyCertificate, - wsmantesting.PULL, - wsmantesting.PULL_BODY, + AMTPublicKeyCertificate, + wsmantesting.Pull, + wsmantesting.PullBody, "", func() (Response, error) { - client.CurrentMessage = "Pull" + client.CurrentMessage = wsmantesting.CurrentMessagePull + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -119,16 +125,16 @@ func TestPositiveAMT_PublicKeyCertificate(t *testing.T) { XMLName: xml.Name{Space: message.XMLPullResponseSpace, Local: "PullResponse"}, PublicKeyCertificateItems: []PublicKeyCertificateResponse{ { - XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMT_PublicKeyCertificate), Local: "AMT_PublicKeyCertificate"}, + XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMTPublicKeyCertificate), Local: "AMT_PublicKeyCertificate"}, ElementName: "Intel(r) AMT Certificate", InstanceID: "Intel(r) AMT Certificate: Handle: 0", Issuer: "C=unknown,O=unknown,CN=MPSRoot-0af1d5", Subject: "C=unknown,O=unknown,CN=MPSRoot-0af1d5", TrustedRootCertificate: true, - X509Certificate: "MIIEOzCCAqOgAwIBAgIDAZMjMA0GCSqGSIb3DQEBDAUAMD0xFzAVBgNVBAMTDk1QU1Jvb3QtMGFmMWQ1MRAwDgYDVQQKEwd1bmtub3duMRAwDgYDVQQGEwd1bmtub3duMCAXDTIyMDkyNDEwNDUwOFoYDzIwNTMwOTI0MTA0NTA4WjA9MRcwFQYDVQQDEw5NUFNSb290LTBhZjFkNTEQMA4GA1UEChMHdW5rbm93bjEQMA4GA1UEBhMHdW5rbm93bjCCAaIwDQYJKoZIhvcNAQEBBQADggGPADCCAYoCggGBALz/oJNyWXlClSlteAieC8Uyd4A+tbn8b45k6LKiImhDmdz/xFo9xe0C9GNf7b42KVpg5WoH/sPhoClR9Tv5i1LnilT1SUir42fcm2NEV9dRcLsPd/RAQfz8u0D4zb3blnxE8isqzriNpG7kac35UidSr5ym8TZ3IwXx6JJuncGgfB0DFZADC/+dA74n3coykvWBYqLr6RI5pkAxvulkRlCsatJTJrvMUYJ51GI28jV56mIAc89sLrHqiSKCZBH9AcUrnZ/cB6ST/IikXpxy5wXBIvWT3VKVq75T/uIoCBEp5TLEn1EOYGqBBOCSQgmtmX7eVaB0s1+ppPW9w9a2zS45cHAtQ7tYvkkPv2dRhSzZdlk6HRXDP5wsF0aiflZCgbrjkq0SFC4e3Lo7XQX3FTNb0SOTZVTydupoMKkgJQTNlcosdu1ZzaIBl3eSkKkJZz2rUTssZC5tn9vcDd5vy3BzcGh5pvkgfAgN1sydqG7Ke1qCkNEzm11B/BsevatjjwIDAQABo0IwQDAMBgNVHRMEBTADAQH/MBEGCWCGSAGG+EIBAQQEAwIABzAdBgNVHQ4EFgQUCvHVQqerCid99eLApuLky9x6H5owDQYJKoZIhvcNAQEMBQADggGBAIzOyGV0hzsmH2biJlzwTZaHMxqS7boTFMkHw+KvzsI201tHqVmCoiQ8EHErBGLSoDOTDRgOUGOCA5XU5ie9OWupAGqKBSwIyAhmJMOzrzC4Gwpu8K1msoFJH30kx/V9purpbS3BRj0xfYXLa6IczbTg3E5IfTnZRJ9YuUtKQfI0P9c5U9CoKtddKn4+lRvOjFDoYfQGCJ7go3xjNCcGCVCjfkUhAVdbQ21DCRr6/YCZDWmjzZpL0p7UKF8roTiNuL/Z7gIXxch5HOmEWHY9uQ6K2MntuxAu0aK/mSD2kwmt/ECongdEGfUvhULLoPRQlQ2LnzcUQEgMECGQR5Yfy9jT0E8zdWDpc2tgVioNu6rEYKgp/GhG+sv7jv58pW82FRAV9xXtftW9+XDugC8tBJ6JHn0Q2v0QAflD2CEQVhWAY8bAqrbfTGUsaLfGL6kxV/qqssoMgLR8WhQ96T5le/4XGhQpbCHWIlctD6MwbrsunIAeQKp1Sc3DosY7DLq1MQ==", + X509Certificate: X509TestCertificate, }, { - XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMT_PublicKeyCertificate), Local: "AMT_PublicKeyCertificate"}, + XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMTPublicKeyCertificate), Local: "AMT_PublicKeyCertificate"}, ElementName: "Intel(r) AMT Certificate", InstanceID: "Intel(r) AMT Certificate: Handle: 1", Issuer: "C=unknown,O=unknown,CN=MPSRoot-0af1d5", @@ -137,7 +143,7 @@ func TestPositiveAMT_PublicKeyCertificate(t *testing.T) { X509Certificate: "MIIEOzCCAqOgAwIBAgIDAZMjMA0GCSqGSIb3DQEBDAUAMD0xFzAVBgNVBAMTDk1QU1Jvb3QtMGFmMWQ1MRAwDgYDVQQKEwd1bmtub3duMRAwDgYDVQQGEwd1bmtub3duMCAXDTIyMDkyNDEwNDUwOFoYDzIwNTMwOTI0MTA0NTA4WjA9MRcwFQYDVQQDEw5NUFNSb290LTBhZjFkNTEQMA4GA1UEChMHdW5rbm93bjEQMA4GA1UEBhMHdW5rbm93bjCCAaIwDQYJKoZIhvcNAQEBBQADggGPADCCAYoCggGBALz/oJNyWXlClSlteAieC8Uyd4A+tbn8b45k6LKiImhDmdz/xFo9xe0C9GNf7b42KVpg5WoH/sPhoClR9Tv5i1LnilT1SUir42fcm2NEV9dRcLsPd/RAQfz8u0D4zb3blnxE8isqzriNpG7kac35UidSr5ym8TZ3IwXx6JJuncGgfB0DFZADC/+dA74n3coykvWBYqLr6RI5pkAxvulkRlCsatJTJrvMUYJ51GI28jV56mIAc89sLrHqiSKCZBH9AcUrnZ/cB6ST/IikXpxy5wXBIvWT3VKVq75T/uIoCBEp5TLEn1EOYGqBBOCSQgmtmX7eVaB0s1+ppPW9w9a2zS45cHAtQ7tYvkkPv2dRhSzZdlk6HRXDP5wsF0aiflZCgbrjkq0SFC4e3Lo7XQX3FTNb0SOTZVTydupoMKkgJQTNlcosdu1ZzaIBl3eSkKkJZz2rUTssZC5tn9vcDd5vy3BzcGh5pvkgfAgN1sydqG7Ke1qCkNEzm11B/BsevatjjwIDAQABo0IwQDAMBgNVHRMEBTADAQH/MBEGCWCGSAGG+EIBAQQEAwIABzAdBgNVHQ4EFgQUCvHVQqerCid99eLApuLky9x6H5owDQYJKoZIhvcNAQEMBQADggGBAIzOyGV0hzsmH2biJlzwTZaHMxqS7boTFMkHw+KvzsI201tHqVmCoiQ8EHErBGLSoDOTDRgOUGOCA5XU5ie9OWupAGqKBSwIyAhmJMOzrzC4Gwpu8K1msoFJH30kx/V9purpbS3BRj0xfYXLa6IczbTg3E5IfTnZRJ9YuUtKQfI0P9c5U9CoKtddKn4+lRvOjFDoYfQGCJ7go3xjNCcGCVCjfkUhAVdbQ21DCRr6/YCZDWmjzZpL0p7UKF8roTiNuL/Z7gIXxch5HOmEWHY9uQ6K2MntuxAu0aK/mSD2kwmt/ECongdEGfUvhULLoPRQlQ2LnzcUQEgMECGQR5Yfy9jT0E8zdWDpc2tgVioNu6rEYKgp/GhG+sv7jv58pW82FRAV9xXtftW9+XDugC8tBJ6JHn0Q2v0QAflD2CEQVhWAY8bAqrbfTGUsaLfGL6kxV/qqssoMgLR8Whq96T5le/4XGhQpbCHWIlctD6MwbrsunIAeQKp1Sc3DosY7DLq1MQ==", }, { - XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMT_PublicKeyCertificate), Local: "AMT_PublicKeyCertificate"}, + XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMTPublicKeyCertificate), Local: "AMT_PublicKeyCertificate"}, ElementName: "Intel(r) AMT Certificate", InstanceID: "Intel(r) AMT Certificate: Handle: 2", Issuer: "C=unknown,O=unknown,CN=MPSRoot-0af1d5", @@ -150,16 +156,17 @@ func TestPositiveAMT_PublicKeyCertificate(t *testing.T) { }, }, - //PUTS + // PUTS { "should create a valid AMT_PublicKeyCertificate Put wsman message", - AMT_PublicKeyCertificate, - wsmantesting.PUT, + AMTPublicKeyCertificate, + wsmantesting.Put, "MIIEOzCCAqOgAwIBAgIDAZMjMA0GCSqGSIb3DQEBDAUAMD0xFzAVBgNVBAMTDk1QU1Jvb3QtMGFmMWQ1MRAwDgYDVQQKEwd1bmtub3duMRAwDgYDVQQGEwd1bmtub3duMCAXDTIyMDkyNDEwNDUwOFoYDzIwNTMwOTI0MTA0NTA4WjA9MRcwFQYDVQQDEw5NUFNSb290LTBhZjFkNTEQMA4GA1UEChMHdW5rbm93bjEQMA4GA1UEBhMHdW5rbm93bjCCAaIwDQYJKoZIhvcNAQEBBQADggGPADCCAYoCggGBALz/oJNyWXlClSlteAieC8Uyd4A+tbn8b45k6LKiImhDmdz/xFo9xe0C9GNf7b42KVpg5WoH/sPhoClR9Tv5i1LnilT1SUir42fcm2NEV9dRcLsPd/RAQfz8u0D4zb3blnxE8isqzriNpG7kac35UidSr5ym8TZ3IwXx6JJuncGgfB0DFZADC/+dA74n3coykvWBYqLr6RI5pkAxvulkRlCsatJTJrvMUYJ51GI28jV56mIAc89sLrHqiSKCZBH9AcUrnZ/cB6ST/IikXpxy5wXBIvWT3VKVq75T/uIoCBEp5TLEn1EOYGqBBOCSQgmtmX7eVaB0s1+ppPW9w9a2zS45cHAtQ7tYvkkPv2dRhSzZdlk6HRXDP5wsF0aiflZCgbrjkq0SFC4e3Lo7XQX3FTNb0SOTZVTydupoMKkgJQTNlcosdu1ZzaIBl3eSkKkJZz2rUTssZC5tn9vcDd5vy3BzcGh5pvkgfAgN1sydqG7Ke1qCkNEzm11B/BsevatjjwIDAQABo0IwQDAMBgNVHRMEBTADAQH/MBEGCWCGSAGG+EIBAQQEAwIABzAdBgNVHQ4EFgQUCvHVQqerCid99eLApuLky9x6H5owDQYJKoZIhvcNAQEMBQADggGBAIzOyGV0hzsmH2biJlzwTZaHMxqS7boTFMkHw+KvzsI201tHqVmCoiQ8EHErBGLSoDOTDRgOUGOCA5XU5ie9OWupAGqKBSwIyAhmJMOzrzC4Gwpu8K1msoFJH30kx/V9purpbS3BRj0xfYXLa6IczbTg3E5IfTnZRJ9YuUtKQfI0P9c5U9CoKtddKn4+lRvOjFDoYfQGCJ7go3xjNCcGCVCjfkUhAVdbQ21DCRr6/YCZDWmjzZpL0p7UKF8roTiNuL/Z7gIXxch5HOmEWHY9uQ6K2MntuxAu0aK/mSD2kwmt/ECongdEGfUvhULLoPRQlQ2LnzcUQEgMECGQR5Yfy9jT0E8zdWDpc2tgVioNu6rEYKgp/GhG+sv7jv58pW82FRAV9xXtftW9+XDugC8tBJ6JHn0Q2v0QAflD2CEQVhWAY8bAqrbfTGUsaLfGL6kxV/qqssoMgLR8WhQ96T5le/4XGhQpbCHWIlctD6MwbrsunIAeQKp1Sc3DosY7DLq1MQ==falsefalse", "Intel(r) AMT Certificate: Handle: 0", func() (Response, error) { - X509Certificate := "MIIEOzCCAqOgAwIBAgIDAZMjMA0GCSqGSIb3DQEBDAUAMD0xFzAVBgNVBAMTDk1QU1Jvb3QtMGFmMWQ1MRAwDgYDVQQKEwd1bmtub3duMRAwDgYDVQQGEwd1bmtub3duMCAXDTIyMDkyNDEwNDUwOFoYDzIwNTMwOTI0MTA0NTA4WjA9MRcwFQYDVQQDEw5NUFNSb290LTBhZjFkNTEQMA4GA1UEChMHdW5rbm93bjEQMA4GA1UEBhMHdW5rbm93bjCCAaIwDQYJKoZIhvcNAQEBBQADggGPADCCAYoCggGBALz/oJNyWXlClSlteAieC8Uyd4A+tbn8b45k6LKiImhDmdz/xFo9xe0C9GNf7b42KVpg5WoH/sPhoClR9Tv5i1LnilT1SUir42fcm2NEV9dRcLsPd/RAQfz8u0D4zb3blnxE8isqzriNpG7kac35UidSr5ym8TZ3IwXx6JJuncGgfB0DFZADC/+dA74n3coykvWBYqLr6RI5pkAxvulkRlCsatJTJrvMUYJ51GI28jV56mIAc89sLrHqiSKCZBH9AcUrnZ/cB6ST/IikXpxy5wXBIvWT3VKVq75T/uIoCBEp5TLEn1EOYGqBBOCSQgmtmX7eVaB0s1+ppPW9w9a2zS45cHAtQ7tYvkkPv2dRhSzZdlk6HRXDP5wsF0aiflZCgbrjkq0SFC4e3Lo7XQX3FTNb0SOTZVTydupoMKkgJQTNlcosdu1ZzaIBl3eSkKkJZz2rUTssZC5tn9vcDd5vy3BzcGh5pvkgfAgN1sydqG7Ke1qCkNEzm11B/BsevatjjwIDAQABo0IwQDAMBgNVHRMEBTADAQH/MBEGCWCGSAGG+EIBAQQEAwIABzAdBgNVHQ4EFgQUCvHVQqerCid99eLApuLky9x6H5owDQYJKoZIhvcNAQEMBQADggGBAIzOyGV0hzsmH2biJlzwTZaHMxqS7boTFMkHw+KvzsI201tHqVmCoiQ8EHErBGLSoDOTDRgOUGOCA5XU5ie9OWupAGqKBSwIyAhmJMOzrzC4Gwpu8K1msoFJH30kx/V9purpbS3BRj0xfYXLa6IczbTg3E5IfTnZRJ9YuUtKQfI0P9c5U9CoKtddKn4+lRvOjFDoYfQGCJ7go3xjNCcGCVCjfkUhAVdbQ21DCRr6/YCZDWmjzZpL0p7UKF8roTiNuL/Z7gIXxch5HOmEWHY9uQ6K2MntuxAu0aK/mSD2kwmt/ECongdEGfUvhULLoPRQlQ2LnzcUQEgMECGQR5Yfy9jT0E8zdWDpc2tgVioNu6rEYKgp/GhG+sv7jv58pW82FRAV9xXtftW9+XDugC8tBJ6JHn0Q2v0QAflD2CEQVhWAY8bAqrbfTGUsaLfGL6kxV/qqssoMgLR8WhQ96T5le/4XGhQpbCHWIlctD6MwbrsunIAeQKp1Sc3DosY7DLq1MQ==" - client.CurrentMessage = "Put" + X509Certificate := X509TestCertificate + client.CurrentMessage = wsmantesting.CurrentMessagePut + return elementUnderTest.Put("Intel(r) AMT Certificate: Handle: 0", X509Certificate) }, Body{ @@ -171,19 +178,20 @@ func TestPositiveAMT_PublicKeyCertificate(t *testing.T) { Issuer: "C=unknown,O=unknown,CN=MPSRoot-0af1d5", Subject: "C=unknown,O=unknown,CN=MPSRoot-0af1d5", TrustedRootCertificate: true, - X509Certificate: "MIIEOzCCAqOgAwIBAgIDAZMjMA0GCSqGSIb3DQEBDAUAMD0xFzAVBgNVBAMTDk1QU1Jvb3QtMGFmMWQ1MRAwDgYDVQQKEwd1bmtub3duMRAwDgYDVQQGEwd1bmtub3duMCAXDTIyMDkyNDEwNDUwOFoYDzIwNTMwOTI0MTA0NTA4WjA9MRcwFQYDVQQDEw5NUFNSb290LTBhZjFkNTEQMA4GA1UEChMHdW5rbm93bjEQMA4GA1UEBhMHdW5rbm93bjCCAaIwDQYJKoZIhvcNAQEBBQADggGPADCCAYoCggGBALz/oJNyWXlClSlteAieC8Uyd4A+tbn8b45k6LKiImhDmdz/xFo9xe0C9GNf7b42KVpg5WoH/sPhoClR9Tv5i1LnilT1SUir42fcm2NEV9dRcLsPd/RAQfz8u0D4zb3blnxE8isqzriNpG7kac35UidSr5ym8TZ3IwXx6JJuncGgfB0DFZADC/+dA74n3coykvWBYqLr6RI5pkAxvulkRlCsatJTJrvMUYJ51GI28jV56mIAc89sLrHqiSKCZBH9AcUrnZ/cB6ST/IikXpxy5wXBIvWT3VKVq75T/uIoCBEp5TLEn1EOYGqBBOCSQgmtmX7eVaB0s1+ppPW9w9a2zS45cHAtQ7tYvkkPv2dRhSzZdlk6HRXDP5wsF0aiflZCgbrjkq0SFC4e3Lo7XQX3FTNb0SOTZVTydupoMKkgJQTNlcosdu1ZzaIBl3eSkKkJZz2rUTssZC5tn9vcDd5vy3BzcGh5pvkgfAgN1sydqG7Ke1qCkNEzm11B/BsevatjjwIDAQABo0IwQDAMBgNVHRMEBTADAQH/MBEGCWCGSAGG+EIBAQQEAwIABzAdBgNVHQ4EFgQUCvHVQqerCid99eLApuLky9x6H5owDQYJKoZIhvcNAQEMBQADggGBAIzOyGV0hzsmH2biJlzwTZaHMxqS7boTFMkHw+KvzsI201tHqVmCoiQ8EHErBGLSoDOTDRgOUGOCA5XU5ie9OWupAGqKBSwIyAhmJMOzrzC4Gwpu8K1msoFJH30kx/V9purpbS3BRj0xfYXLa6IczbTg3E5IfTnZRJ9YuUtKQfI0P9c5U9CoKtddKn4+lRvOjFDoYfQGCJ7go3xjNCcGCVCjfkUhAVdbQ21DCRr6/YCZDWmjzZpL0p7UKF8roTiNuL/Z7gIXxch5HOmEWHY9uQ6K2MntuxAu0aK/mSD2kwmt/ECongdEGfUvhULLoPRQlQ2LnzcUQEgMECGQR5Yfy9jT0E8zdWDpc2tgVioNu6rEYKgp/GhG+sv7jv58pW82FRAV9xXtftW9+XDugC8tBJ6JHn0Q2v0QAflD2CEQVhWAY8bAqrbfTGUsaLfGL6kxV/qqssoMgLR8WhQ96T5le/4XGhQpbCHWIlctD6MwbrsunIAeQKp1Sc3DosY7DLq1MQ==", + X509Certificate: X509TestCertificate, }, }, }, - //DELETE + // DELETE { "should create a valid AMT_PublicKeyCertificate Delete wsman message", - AMT_PublicKeyCertificate, - wsmantesting.DELETE, + AMTPublicKeyCertificate, + wsmantesting.Delete, "", "instanceID123", func() (Response, error) { - client.CurrentMessage = "Delete" + client.CurrentMessage = wsmantesting.CurrentMessageDelete + return elementUnderTest.Delete("instanceID123") }, Body{XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}}, @@ -192,7 +200,7 @@ func TestPositiveAMT_PublicKeyCertificate(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, test.extraHeader, test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, test.extraHeader, test.body) messageID++ response, err := test.responseFunc() assert.NoError(t, err) @@ -202,14 +210,16 @@ func TestPositiveAMT_PublicKeyCertificate(t *testing.T) { } }) } + func TestNegativeAMT_PublicKeyCertificate(t *testing.T) { messageID := 0 - resourceUriBase := "http://intel.com/wbem/wscim/1/amt-schema/1/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.AMTResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "amt/publickey/certificate", } elementUnderTest := NewPublicKeyCertificateWithClient(wsmanMessageCreator, &client) + t.Run("amt_PublicKeyCertificate Tests", func(t *testing.T) { tests := []struct { name string @@ -220,42 +230,44 @@ func TestNegativeAMT_PublicKeyCertificate(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //GETS + // GETS { "should create a valid AMT_PublicKeyCertificate Get wsman message", - AMT_PublicKeyCertificate, - wsmantesting.GET, + AMTPublicKeyCertificate, + wsmantesting.Get, "", "Intel(r) AMT Certificate: Handle: 0", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Get("Intel(r) AMT Certificate: Handle: 0") }, Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, PublicKeyCertificateGetAndPutResponse: PublicKeyCertificateResponse{ - XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMT_PublicKeyCertificate), Local: "AMT_PublicKeyCertificate"}, + XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMTPublicKeyCertificate), Local: "AMT_PublicKeyCertificate"}, ElementName: "Intel(r) AMT Certificate", InstanceID: "Intel(r) AMT Certificate: Handle: 0", Issuer: "C=unknown,O=unknown,CN=MPSRoot-0af1d5", Subject: "C=unknown,O=unknown,CN=MPSRoot-0af1d5", TrustedRootCertificate: true, - X509Certificate: "MIIEOzCCAqOgAwIBAgIDAZMjMA0GCSqGSIb3DQEBDAUAMD0xFzAVBgNVBAMTDk1QU1Jvb3QtMGFmMWQ1MRAwDgYDVQQKEwd1bmtub3duMRAwDgYDVQQGEwd1bmtub3duMCAXDTIyMDkyNDEwNDUwOFoYDzIwNTMwOTI0MTA0NTA4WjA9MRcwFQYDVQQDEw5NUFNSb290LTBhZjFkNTEQMA4GA1UEChMHdW5rbm93bjEQMA4GA1UEBhMHdW5rbm93bjCCAaIwDQYJKoZIhvcNAQEBBQADggGPADCCAYoCggGBALz/oJNyWXlClSlteAieC8Uyd4A+tbn8b45k6LKiImhDmdz/xFo9xe0C9GNf7b42KVpg5WoH/sPhoClR9Tv5i1LnilT1SUir42fcm2NEV9dRcLsPd/RAQfz8u0D4zb3blnxE8isqzriNpG7kac35UidSr5ym8TZ3IwXx6JJuncGgfB0DFZADC/+dA74n3coykvWBYqLr6RI5pkAxvulkRlCsatJTJrvMUYJ51GI28jV56mIAc89sLrHqiSKCZBH9AcUrnZ/cB6ST/IikXpxy5wXBIvWT3VKVq75T/uIoCBEp5TLEn1EOYGqBBOCSQgmtmX7eVaB0s1+ppPW9w9a2zS45cHAtQ7tYvkkPv2dRhSzZdlk6HRXDP5wsF0aiflZCgbrjkq0SFC4e3Lo7XQX3FTNb0SOTZVTydupoMKkgJQTNlcosdu1ZzaIBl3eSkKkJZz2rUTssZC5tn9vcDd5vy3BzcGh5pvkgfAgN1sydqG7Ke1qCkNEzm11B/BsevatjjwIDAQABo0IwQDAMBgNVHRMEBTADAQH/MBEGCWCGSAGG+EIBAQQEAwIABzAdBgNVHQ4EFgQUCvHVQqerCid99eLApuLky9x6H5owDQYJKoZIhvcNAQEMBQADggGBAIzOyGV0hzsmH2biJlzwTZaHMxqS7boTFMkHw+KvzsI201tHqVmCoiQ8EHErBGLSoDOTDRgOUGOCA5XU5ie9OWupAGqKBSwIyAhmJMOzrzC4Gwpu8K1msoFJH30kx/V9purpbS3BRj0xfYXLa6IczbTg3E5IfTnZRJ9YuUtKQfI0P9c5U9CoKtddKn4+lRvOjFDoYfQGCJ7go3xjNCcGCVCjfkUhAVdbQ21DCRr6/YCZDWmjzZpL0p7UKF8roTiNuL/Z7gIXxch5HOmEWHY9uQ6K2MntuxAu0aK/mSD2kwmt/ECongdEGfUvhULLoPRQlQ2LnzcUQEgMECGQR5Yfy9jT0E8zdWDpc2tgVioNu6rEYKgp/GhG+sv7jv58pW82FRAV9xXtftW9+XDugC8tBJ6JHn0Q2v0QAflD2CEQVhWAY8bAqrbfTGUsaLfGL6kxV/qqssoMgLR8Whq96T5le/4XGhQpbCHWIlctD6MwbrsunIAeQKp1Sc3DosY7DLq1MQ==", + X509Certificate: X509TestCertificate, }, }, }, - //ENUMERATES + // ENUMERATES { "should create a valid AMT_PublicKeyCertificate Enumerate wsman message", - AMT_PublicKeyCertificate, - wsmantesting.ENUMERATE, - wsmantesting.ENUMERATE_BODY, + AMTPublicKeyCertificate, + wsmantesting.Enumerate, + wsmantesting.EnumerateBody, "", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError if elementUnderTest.base.WSManMessageCreator == nil { - print("Error") + logrus.Print("Error") } + return elementUnderTest.Enumerate() }, Body{ @@ -265,15 +277,16 @@ func TestNegativeAMT_PublicKeyCertificate(t *testing.T) { }, }, }, - //PULLS + // PULLS { "should create a valid AMT_PublicKeyCertificate Pull wsman message", - AMT_PublicKeyCertificate, - wsmantesting.PULL, - wsmantesting.PULL_BODY, + AMTPublicKeyCertificate, + wsmantesting.Pull, + wsmantesting.PullBody, "", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -282,47 +295,48 @@ func TestNegativeAMT_PublicKeyCertificate(t *testing.T) { XMLName: xml.Name{Space: message.XMLPullResponseSpace, Local: "PullResponse"}, PublicKeyCertificateItems: []PublicKeyCertificateResponse{ { - XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMT_PublicKeyCertificate), Local: "AMT_PublicKeyCertificate"}, + XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMTPublicKeyCertificate), Local: "AMT_PublicKeyCertificate"}, ElementName: "Intel(r) AMT Certificate", InstanceID: "Intel(r) AMT Certificate: Handle: 0", Issuer: "C=unknown,O=unknown,CN=MPSRoot-0af1d5", Subject: "C=unknown,O=unknown,CN=MPSRoot-0af1d5", TrustedRootCertificate: true, - X509Certificate: "MIIEOzCCAqOgAwIBAgIDAZMjMA0GCSqGSIb3DQEBDAUAMD0xFzAVBgNVBAMTDk1QU1Jvb3QtMGFmMWQ1MRAwDgYDVQQKEwd1bmtub3duMRAwDgYDVQQGEwd1bmtub3duMCAXDTIyMDkyNDEwNDUwOFoYDzIwNTMwOTI0MTA0NTA4WjA9MRcwFQYDVQQDEw5NUFNSb290LTBhZjFkNTEQMA4GA1UEChMHdW5rbm93bjEQMA4GA1UEBhMHdW5rbm93bjCCAaIwDQYJKoZIhvcNAQEBBQADggGPADCCAYoCggGBALz/oJNyWXlClSlteAieC8Uyd4A+tbn8b45k6LKiImhDmdz/xFo9xe0C9GNf7b42KVpg5WoH/sPhoClR9Tv5i1LnilT1SUir42fcm2NEV9dRcLsPd/RAQfz8u0D4zb3blnxE8isqzriNpG7kac35UidSr5ym8TZ3IwXx6JJuncGgfB0DFZADC/+dA74n3coykvWBYqLr6RI5pkAxvulkRlCsatJTJrvMUYJ51GI28jV56mIAc89sLrHqiSKCZBH9AcUrnZ/cB6ST/IikXpxy5wXBIvWT3VKVq75T/uIoCBEp5TLEn1EOYGqBBOCSQgmtmX7eVaB0s1+ppPW9w9a2zS45cHAtQ7tYvkkPv2dRhSzZdlk6HRXDP5wsF0aiflZCgbrjkq0SFC4e3Lo7XQX3FTNb0SOTZVTydupoMKkgJQTNlcosdu1ZzaIBl3eSkKkJZz2rUTssZC5tn9vcDd5vy3BzcGh5pvkgfAgN1sydqG7Ke1qCkNEzm11B/BsevatjjwIDAQABo0IwQDAMBgNVHRMEBTADAQH/MBEGCWCGSAGG+EIBAQQEAwIABzAdBgNVHQ4EFgQUCvHVQqerCid99eLApuLky9x6H5owDQYJKoZIhvcNAQEMBQADggGBAIzOyGV0hzsmH2biJlzwTZaHMxqS7boTFMkHw+KvzsI201tHqVmCoiQ8EHErBGLSoDOTDRgOUGOCA5XU5ie9OWupAGqKBSwIyAhmJMOzrzC4Gwpu8K1msoFJH30kx/V9purpbS3BRj0xfYXLa6IczbTg3E5IfTnZRJ9YuUtKQfI0P9c5U9CoKtddKn4+lRvOjFDoYfQGCJ7go3xjNCcGCVCjfkUhAVdbQ21DCRr6/YCZDWmjzZpL0p7UKF8roTiNuL/Z7gIXxch5HOmEWHY9uQ6K2MntuxAu0aK/mSD2kwmt/ECongdEGfUvhULLoPRQlQ2LnzcUQEgMECGQR5Yfy9jT0E8zdWDpc2tgVioNu6rEYKgp/GhG+sv7jv58pW82FRAV9xXtftW9+XDugC8tBJ6JHn0Q2v0QAflD2CEQVhWAY8bAqrbfTGUsaLfGL6kxV/qqssoMgLR8WhQ96T5le/4XGhQpbCHWIlctD6MwbrsunIAeQKp1Sc3DosY7DLq1MQ==", + X509Certificate: X509TestCertificate, }, { - XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMT_PublicKeyCertificate), Local: "AMT_PublicKeyCertificate"}, + XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMTPublicKeyCertificate), Local: "AMT_PublicKeyCertificate"}, ElementName: "Intel(r) AMT Certificate", InstanceID: "Intel(r) AMT Certificate: Handle: 1", Issuer: "C=unknown,O=unknown,CN=MPSRoot-0af1d5", Subject: "C=unknown,O=unknown,CN=MPSRoot-0af1d5", TrustedRootCertificate: false, - X509Certificate: "MIIEOzCCAqOgAwIBAgIDAZMjMA0GCSqGSIb3DQEBDAUAMD0xFzAVBgNVBAMTDk1QU1Jvb3QtMGFmMWQ1MRAwDgYDVQQKEwd1bmtub3duMRAwDgYDVQQGEwd1bmtub3duMCAXDTIyMDkyNDEwNDUwOFoYDzIwNTMwOTI0MTA0NTA4WjA9MRcwFQYDVQQDEw5NUFNSb290LTBhZjFkNTEQMA4GA1UEChMHdW5rbm93bjEQMA4GA1UEBhMHdW5rbm93bjCCAaIwDQYJKoZIhvcNAQEBBQADggGPADCCAYoCggGBALz/oJNyWXlClSlteAieC8Uyd4A+tbn8b45k6LKiImhDmdz/xFo9xe0C9GNf7b42KVpg5WoH/sPhoClR9Tv5i1LnilT1SUir42fcm2NEV9dRcLsPd/RAQfz8u0D4zb3blnxE8isqzriNpG7kac35UidSr5ym8TZ3IwXx6JJuncGgfB0DFZADC/+dA74n3coykvWBYqLr6RI5pkAxvulkRlCsatJTJrvMUYJ51GI28jV56mIAc89sLrHqiSKCZBH9AcUrnZ/cB6ST/IikXpxy5wXBIvWT3VKVq75T/uIoCBEp5TLEn1EOYGqBBOCSQgmtmX7eVaB0s1+ppPW9w9a2zS45cHAtQ7tYvkkPv2dRhSzZdlk6HRXDP5wsF0aiflZCgbrjkq0SFC4e3Lo7XQX3FTNb0SOTZVTydupoMKkgJQTNlcosdu1ZzaIBl3eSkKkJZz2rUTssZC5tn9vcDd5vy3BzcGh5pvkgfAgN1sydqG7Ke1qCkNEzm11B/BsevatjjwIDAQABo0IwQDAMBgNVHRMEBTADAQH/MBEGCWCGSAGG+EIBAQQEAwIABzAdBgNVHQ4EFgQUCvHVQqerCid99eLApuLky9x6H5owDQYJKoZIhvcNAQEMBQADggGBAIzOyGV0hzsmH2biJlzwTZaHMxqS7boTFMkHw+KvzsI201tHqVmCoiQ8EHErBGLSoDOTDRgOUGOCA5XU5ie9OWupAGqKBSwIyAhmJMOzrzC4Gwpu8K1msoFJH30kx/V9purpbS3BRj0xfYXLa6IczbTg3E5IfTnZRJ9YuUtKQfI0P9c5U9CoKtddKn4+lRvOjFDoYfQGCJ7go3xjNCcGCVCjfkUhAVdbQ21DCRr6/YCZDWmjzZpL0p7UKF8roTiNuL/Z7gIXxch5HOmEWHY9uQ6K2MntuxAu0aK/mSD2kwmt/ECongdEGfUvhULLoPRQlQ2LnzcUQEgMECGQR5Yfy9jT0E8zdWDpc2tgVioNu6rEYKgp/GhG+sv7jv58pW82FRAV9xXtftW9+XDugC8tBJ6JHn0Q2v0QAflD2CEQVhWAY8bAqrbfTGUsaLfGL6kxV/qqssoMgLR8Whq96T5le/4XGhQpbCHWIlctD6MwbrsunIAeQKp1Sc3DosY7DLq1MQ==", + X509Certificate: X509TestCertificate, }, { - XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMT_PublicKeyCertificate), Local: "AMT_PublicKeyCertificate"}, + XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMTPublicKeyCertificate), Local: "AMT_PublicKeyCertificate"}, ElementName: "Intel(r) AMT Certificate", InstanceID: "Intel(r) AMT Certificate: Handle: 2", Issuer: "C=unknown,O=unknown,CN=MPSRoot-0af1d5", Subject: "C=unknown,O=unknown,CN=MPSRoot-0af1d5", TrustedRootCertificate: true, - X509Certificate: "MIIEOzCCAqOgAwIBAgIDAZMjMA0GCSqGSIb3DQEBDAUAMD0xFzAVBgNVBAMTDk1QU1Jvb3QtMGFmMWQ1MRAwDgYDVQQKEwd1bmtub3duMRAwDgYDVQQGEwd1bmtub3duMCAXDTIyMDkyNDEwNDUwOFoYDzIwNTMwOTI0MTA0NTA4WjA9MRcwFQYDVQQDEw5NUFNSb290LTBhZjFkNTEQMA4GA1UEChMHdW5rbm93bjEQMA4GA1UEBhMHdW5rbm93bjCCAaIwDQYJKoZIhvcNAQEBBQADggGPADCCAYoCggGBALz/oJNyWXlClSlteAieC8Uyd4A+tbn8b45k6LKiImhDmdz/xFo9xe0C9GNf7b42KVpg5WoH/sPhoClR9Tv5i1LnilT1SUir42fcm2NEV9dRcLsPd/RAQfz8u0D4zb3blnxE8isqzriNpG7kac35UidSr5ym8TZ3IwXx6JJuncGgfB0DFBADC/+dA74n3coykvWBYqLr6RI5pkAxvulkRlCsatJTJrvMUYJ51GI28jV56mIAc89sLrHqiSKCZBH9AcUrnZ/cB6ST/IikXpxy5wXBIvWT3VKVq75T/uIoCBEp5TLEn1EOYGqBBOCSQgmtmX7eVaB0s1+ppPW9w9a2zS45cHAtQ7tYvkkPv2dRhSzZdlk6HRXDP5wsF0aiflZCgbrjkq0SFC4e3Lo7XQX3FTNb0SOTZVTydupoMKkgJQTNlcosdu1ZzaIBl3eSkKkJZz2rUTssZC5tn9vcDd5vy3BzcGh5pvkgfAgN1sydqG7Ke1qCkNEzm11B/BsevatjjwIDAQABo0IwQDAMBgNVHRMEBTADAQH/MBEGCWCGSAGG+EIBAQQEAwIABzAdBgNVHQ4EFgQUCvHVQqerCid99eLApuLky9x6H5owDQYJKoZIhvcNAQEMBQADggGBAIzOyGV0hzsmH2biJlzwTZaHMxqS7boTFMkHw+KvzsI201tHqVmCoiQ8EHErBGLSoDOTDRgOUGOCA5XU5ie9OWupAGqKBSwIyAhmJMOzrzC4Gwpu8K1msoFJH30kx/V9purpbS3BRj0xfYXLa6IczbTg3E5IfTnZRJ9YuUtKQfI0P9c5U9CoKtddKn4+lRvOjFDoYfQGCJ7go3xjNCcGCVCjfkUhAVdbQ21DCRr6/YCZDWmjzZpL0p7UKF8roTiNuL/Z7gIXxch5HOmEWHY9uQ6K2MntuxAu0aK/mSD2kwmt/ECongdEGfUvhULLoPRQlQ2LnzcUQEgMECGQR5Yfy9jT0E8zdWDpc2tgVioNu6rEYKgp/GhG+sv7jv58pW82FRAV9xXtftW9+XDugC8tBJ6JHn0Q2v0QAflD2CEQVhWAY8bAqrbfTGUsaLfGL6kxV/qqssoMgLR8Whq96T5le/4XGhQpbCHWIlctD6MwbrsunIAeQKp1Sc3DosY7DLq1MQ==", + X509Certificate: X509TestCertificate, }, }, }, }, }, - //PUTS + // PUTS { "should create a valid AMT_PublicKeyCertificate Put wsman message", - AMT_PublicKeyCertificate, - wsmantesting.PUT, + AMTPublicKeyCertificate, + wsmantesting.Put, "MIIEOzCCAqOgAwIBAgIDAZMjMA0GCSqGSIb3DQEBDAUAMD0xFzAVBgNVBAMTDk1QU1Jvb3QtMGFmMWQ1MRAwDgYDVQQKEwd1bmtub3duMRAwDgYDVQQGEwd1bmtub3duMCAXDTIyMDkyNDEwNDUwOFoYDzIwNTMwOTI0MTA0NTA4WjA9MRcwFQYDVQQDEw5NUFNSb290LTBhZjFkNTEQMA4GA1UEChMHdW5rbm93bjEQMA4GA1UEBhMHdW5rbm93bjCCAaIwDQYJKoZIhvcNAQEBBQADggGPADCCAYoCggGBALz/oJNyWXlClSlteAieC8Uyd4A+tbn8b45k6LKiImhDmdz/xFo9xe0C9GNf7b42KVpg5WoH/sPhoClR9Tv5i1LnilT1SUir42fcm2NEV9dRcLsPd/RAQfz8u0D4zb3blnxE8isqzriNpG7kac35UidSr5ym8TZ3IwXx6JJuncGgfB0DFZADC/+dA74n3coykvWBYqLr6RI5pkAxvulkRlCsatJTJrvMUYJ51GI28jV56mIAc89sLrHqiSKCZBH9AcUrnZ/cB6ST/IikXpxy5wXBIvWT3VKVq75T/uIoCBEp5TLEn1EOYGqBBOCSQgmtmX7eVaB0s1+ppPW9w9a2zS45cHAtQ7tYvkkPv2dRhSzZdlk6HRXDP5wsF0aiflZCgbrjkq0SFC4e3Lo7XQX3FTNb0SOTZVTydupoMKkgJQTNlcosdu1ZzaIBl3eSkKkJZz2rUTssZC5tn9vcDd5vy3BzcGh5pvkgfAgN1sydqG7Ke1qCkNEzm11B/BsevatjjwIDAQABo0IwQDAMBgNVHRMEBTADAQH/MBEGCWCGSAGG+EIBAQQEAwIABzAdBgNVHQ4EFgQUCvHVQqerCid99eLApuLky9x6H5owDQYJKoZIhvcNAQEMBQADggGBAIzOyGV0hzsmH2biJlzwTZaHMxqS7boTFMkHw+KvzsI201tHqVmCoiQ8EHErBGLSoDOTDRgOUGOCA5XU5ie9OWupAGqKBSwIyAhmJMOzrzC4Gwpu8K1msoFJH30kx/V9purpbS3BRj0xfYXLa6IczbTg3E5IfTnZRJ9YuUtKQfI0P9c5U9CoKtddKn4+lRvOjFDoYfQGCJ7go3xjNCcGCVCjfkUhAVdbQ21DCRr6/YCZDWmjzZpL0p7UKF8roTiNuL/Z7gIXxch5HOmEWHY9uQ6K2MntuxAu0aK/mSD2kwmt/ECongdEGfUvhULLoPRQlQ2LnzcUQEgMECGQR5Yfy9jT0E8zdWDpc2tgVioNu6rEYKgp/GhG+sv7jv58pW82FRAV9xXtftW9+XDugC8tBJ6JHn0Q2v0QAflD2CEQVhWAY8bAqrbfTGUsaLfGL6kxV/qqssoMgLR8WhQ96T5le/4XGhQpbCHWIlctD6MwbrsunIAeQKp1Sc3DosY7DLq1MQ==falsefalse", "Intel(r) AMT Certificate: Handle: 0", func() (Response, error) { - X509Certificate := "MIIEOzCCAqOgAwIBAgIDAZMjMA0GCSqGSIb3DQEBDAUAMD0xFzAVBgNVBAMTDk1QU1Jvb3QtMGFmMWQ1MRAwDgYDVQQKEwd1bmtub3duMRAwDgYDVQQGEwd1bmtub3duMCAXDTIyMDkyNDEwNDUwOFoYDzIwNTMwOTI0MTA0NTA4WjA9MRcwFQYDVQQDEw5NUFNSb290LTBhZjFkNTEQMA4GA1UEChMHdW5rbm93bjEQMA4GA1UEBhMHdW5rbm93bjCCAaIwDQYJKoZIhvcNAQEBBQADggGPADCCAYoCggGBALz/oJNyWXlClSlteAieC8Uyd4A+tbn8b45k6LKiImhDmdz/xFo9xe0C9GNf7b42KVpg5WoH/sPhoClR9Tv5i1LnilT1SUir42fcm2NEV9dRcLsPd/RAQfz8u0D4zb3blnxE8isqzriNpG7kac35UidSr5ym8TZ3IwXx6JJuncGgfB0DFZADC/+dA74n3coykvWBYqLr6RI5pkAxvulkRlCsatJTJrvMUYJ51GI28jV56mIAc89sLrHqiSKCZBH9AcUrnZ/cB6ST/IikXpxy5wXBIvWT3VKVq75T/uIoCBEp5TLEn1EOYGqBBOCSQgmtmX7eVaB0s1+ppPW9w9a2zS45cHAtQ7tYvkkPv2dRhSzZdlk6HRXDP5wsF0aiflZCgbrjkq0SFC4e3Lo7XQX3FTNb0SOTZVTydupoMKkgJQTNlcosdu1ZzaIBl3eSkKkJZz2rUTssZC5tn9vcDd5vy3BzcGh5pvkgfAgN1sydqG7Ke1qCkNEzm11B/BsevatjjwIDAQABo0IwQDAMBgNVHRMEBTADAQH/MBEGCWCGSAGG+EIBAQQEAwIABzAdBgNVHQ4EFgQUCvHVQqerCid99eLApuLky9x6H5owDQYJKoZIhvcNAQEMBQADggGBAIzOyGV0hzsmH2biJlzwTZaHMxqS7boTFMkHw+KvzsI201tHqVmCoiQ8EHErBGLSoDOTDRgOUGOCA5XU5ie9OWupAGqKBSwIyAhmJMOzrzC4Gwpu8K1msoFJH30kx/V9purpbS3BRj0xfYXLa6IczbTg3E5IfTnZRJ9YuUtKQfI0P9c5U9CoKtddKn4+lRvOjFDoYfQGCJ7go3xjNCcGCVCjfkUhAVdbQ21DCRr6/YCZDWmjzZpL0p7UKF8roTiNuL/Z7gIXxch5HOmEWHY9uQ6K2MntuxAu0aK/mSD2kwmt/ECongdEGfUvhULLoPRQlQ2LnzcUQEgMECGQR5Yfy9jT0E8zdWDpc2tgVioNu6rEYKgp/GhG+sv7jv58pW82FRAV9xXtftW9+XDugC8tBJ6JHn0Q2v0QAflD2CEQVhWAY8bAqrbfTGUsaLfGL6kxV/qqssoMgLR8WhQ96T5le/4XGhQpbCHWIlctD6MwbrsunIAeQKp1Sc3DosY7DLq1MQ==" - client.CurrentMessage = "Error" + X509Certificate := X509TestCertificate + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Put("Intel(r) AMT Certificate: Handle: 0", X509Certificate) }, Body{ @@ -334,19 +348,20 @@ func TestNegativeAMT_PublicKeyCertificate(t *testing.T) { Issuer: "C=unknown,O=unknown,CN=MPSRoot-0af1d5", Subject: "C=unknown,O=unknown,CN=MPSRoot-0af1d5", TrustedRootCertificate: true, - X509Certificate: "MIIEOzCCAqOgAwIBAgIDAZMjMA0GCSqGSIb3DQEBDAUAMD0xFzAVBgNVBAMTDk1QU1Jvb3QtMGFmMWQ1MRAwDgYDVQQKEwd1bmtub3duMRAwDgYDVQQGEwd1bmtub3duMCAXDTIyMDkyNDEwNDUwOFoYDzIwNTMwOTI0MTA0NTA4WjA9MRcwFQYDVQQDEw5NUFNSb290LTBhZjFkNTEQMA4GA1UEChMHdW5rbm93bjEQMA4GA1UEBhMHdW5rbm93bjCCAaIwDQYJKoZIhvcNAQEBBQADggGPADCCAYoCggGBALz/oJNyWXlClSlteAieC8Uyd4A+tbn8b45k6LKiImhDmdz/xFo9xe0C9GNf7b42KVpg5WoH/sPhoClR9Tv5i1LnilT1SUir42fcm2NEV9dRcLsPd/RAQfz8u0D4zb3blnxE8isqzriNpG7kac35UidSr5ym8TZ3IwXx6JJuncGgfB0DFZADC/+dA74n3coykvWBYqLr6RI5pkAxvulkRlCsatJTJrvMUYJ51GI28jV56mIAc89sLrHqiSKCZBH9AcUrnZ/cB6ST/IikXpxy5wXBIvWT3VKVq75T/uIoCBEp5TLEn1EOYGqBBOCSQgmtmX7eVaB0s1+ppPW9w9a2zS45cHAtQ7tYvkkPv2dRhSzZdlk6HRXDP5wsF0aiflZCgbrjkq0SFC4e3Lo7XQX3FTNb0SOTZVTydupoMKkgJQTNlcosdu1ZzaIBl3eSkKkJZz2rUTssZC5tn9vcDd5vy3BzcGh5pvkgfAgN1sydqG7Ke1qCkNEzm11B/BsevatjjwIDAQABo0IwQDAMBgNVHRMEBTADAQH/MBEGCWCGSAGG+EIBAQQEAwIABzAdBgNVHQ4EFgQUCvHVQqerCid99eLApuLky9x6H5owDQYJKoZIhvcNAQEMBQADggGBAIzOyGV0hzsmH2biJlzwTZaHMxqS7boTFMkHw+KvzsI201tHqVmCoiQ8EHErBGLSoDOTDRgOUGOCA5XU5ie9OWupAGqKBSwIyAhmJMOzrzC4Gwpu8K1msoFJH30kx/V9purpbS3BRj0xfYXLa6IczbTg3E5IfTnZRJ9YuUtKQfI0P9c5U9CoKtddKn4+lRvOjFDoYfQGCJ7go3xjNCcGCVCjfkUhAVdbQ21DCRr6/YCZDWmjzZpL0p7UKF8roTiNuL/Z7gIXxch5HOmEWHY9uQ6K2MntuxAu0aK/mSD2kwmt/ECongdEGfUvhULLoPRQlQ2LnzcUQEgMECGQR5Yfy9jT0E8zdWDpc2tgVioNu6rEYKgp/GhG+sv7jv58pW82FRAV9xXtftW9+XDugC8tBJ6JHn0Q2v0QAflD2CEQVhWAY8bAqrbfTGUsaLfGL6kxV/qqssoMgLR8WhQ96T5le/4XGhQpbCHWIlctD6MwbrsunIAeQKp1Sc3DosY7DLq1MQ==", + X509Certificate: X509TestCertificate, }, }, }, - //DELETE + // DELETE { "should create a valid AMT_PublicKeyCertificate Delete wsman message", - AMT_PublicKeyCertificate, - wsmantesting.DELETE, + AMTPublicKeyCertificate, + wsmantesting.Delete, "", "instanceID123", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Delete("instanceID123") }, Body{XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}}, @@ -355,7 +370,7 @@ func TestNegativeAMT_PublicKeyCertificate(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, test.extraHeader, test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, test.extraHeader, test.body) messageID++ response, err := test.responseFunc() assert.Error(t, err) diff --git a/pkg/wsman/amt/publickey/decoder.go b/pkg/wsman/amt/publickey/decoder.go index 0186a1f2..e9279b22 100644 --- a/pkg/wsman/amt/publickey/decoder.go +++ b/pkg/wsman/amt/publickey/decoder.go @@ -6,13 +6,14 @@ package publickey const ( - AMT_PublicKeyCertificate string = "AMT_PublicKeyCertificate" - AMT_PublicKeyManagementService string = "AMT_PublicKeyManagementService" - GeneratePKCS10RequestEx string = "GeneratePKCS10RequestEx" - AddTrustedRootCertificate string = "AddTrustedRootCertificate" - AddCertificate string = "AddCertificate" - GenerateKeyPair string = "GenerateKeyPair" - AddKey string = "AddKey" + AMTPublicKeyCertificate string = "AMT_PublicKeyCertificate" + AMTPublicKeyManagementService string = "AMT_PublicKeyManagementService" + GeneratePKCS10RequestEx string = "GeneratePKCS10RequestEx" + AddTrustedRootCertificate string = "AddTrustedRootCertificate" + AddCertificate string = "AddCertificate" + GenerateKeyPair string = "GenerateKeyPair" + AddKey string = "AddKey" + ValueNotFound string = "Value not found in map" ) const ( @@ -37,7 +38,7 @@ const ( EnabledDefaultQuiesce EnabledDefault = 9 ) -// enabledDefaultToString is a map of EnabledDefault values to their string representations +// enabledDefaultToString is a map of EnabledDefault values to their string representations. var enabledDefaultToString = map[EnabledDefault]string{ EnabledDefaultEnabled: "Enabled", EnabledDefaultDisabled: "Disabled", @@ -47,13 +48,13 @@ var enabledDefaultToString = map[EnabledDefault]string{ EnabledDefaultQuiesce: "Quiesce", } -// String returns the string representation of the EnabledDefault value +// String returns the string representation of the EnabledDefault value. func (e EnabledDefault) String() string { if value, exists := enabledDefaultToString[e]; exists { return value } - return "Value not found in map" + return ValueNotFound } const ( @@ -70,7 +71,7 @@ const ( EnabledStateStarting ) -// enabledStateToString is a map of EnabledState values to their string representations +// enabledStateToString is a map of EnabledState values to their string representations. var enabledStateToString = map[EnabledState]string{ EnabledStateUnknown: "Unknown", EnabledStateOther: "Other", @@ -85,13 +86,13 @@ var enabledStateToString = map[EnabledState]string{ EnabledStateStarting: "Starting", } -// String returns the string representation of the EnabledState value +// String returns the string representation of the EnabledState value. func (e EnabledState) String() string { if value, exists := enabledStateToString[e]; exists { return value } - return "Value not found in map" + return ValueNotFound } const ( @@ -117,7 +118,7 @@ const ( OperationalStatusRelocating ) -// operationalStatusToString is a map of OperationalStatus values to their string representations +// operationalStatusToString is a map of OperationalStatus values to their string representations. var operationalStatusToString = map[OperationalStatus]string{ OperationalStatusUnknown: "Unknown", OperationalStatusOther: "Other", @@ -141,13 +142,13 @@ var operationalStatusToString = map[OperationalStatus]string{ OperationalStatusRelocating: "Relocating", } -// String returns the string representation of the OperationalStatus value +// String returns the string representation of the OperationalStatus value. func (o OperationalStatus) String() string { if value, exists := operationalStatusToString[o]; exists { return value } - return "Value not found in map" + return ValueNotFound } const ( @@ -165,7 +166,7 @@ const ( RequestedStateNotApplicable RequestedState = 12 ) -// requestedStateToString is a map of RequestedState values to their string representations +// requestedStateToString is a map of RequestedState values to their string representations. var requestedStateToString = map[RequestedState]string{ RequestedStateUnknown: "Unknown", RequestedStateEnabled: "Enabled", @@ -181,13 +182,13 @@ var requestedStateToString = map[RequestedState]string{ RequestedStateNotApplicable: "NotApplicable", } -// String returns the string representation of the RequestedState value +// String returns the string representation of the RequestedState value. func (r RequestedState) String() string { if value, exists := requestedStateToString[r]; exists { return value } - return "Value not found in map" + return ValueNotFound } const ( @@ -204,7 +205,7 @@ const ( ReturnValueOperationInProgress ReturnValue = 2082 ) -// returnValueToString is a map of ReturnValue values to their string representations +// returnValueToString is a map of ReturnValue values to their string representations. var returnValueToString = map[ReturnValue]string{ ReturnValueSuccess: "Success", ReturnValueInternalError: "InternalError", @@ -219,11 +220,11 @@ var returnValueToString = map[ReturnValue]string{ ReturnValueOperationInProgress: "OperationInProgress", } -// String returns the string representation of the ReturnValue value +// String returns the string representation of the ReturnValue value. func (p ReturnValue) String() string { if value, exists := returnValueToString[p]; exists { return value } - return "Value not found in map" + return ValueNotFound } diff --git a/pkg/wsman/amt/publickey/managementservice.go b/pkg/wsman/amt/publickey/managementservice.go index e3799c4c..d4ab87b6 100644 --- a/pkg/wsman/amt/publickey/managementservice.go +++ b/pkg/wsman/amt/publickey/managementservice.go @@ -16,51 +16,57 @@ import ( "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/client" ) -// NewPublicKeyManagementServiceWithClient instantiates a new ManagementService +// NewPublicKeyManagementServiceWithClient instantiates a new ManagementService. func NewPublicKeyManagementServiceWithClient(wsmanMessageCreator *message.WSManMessageCreator, client client.WSMan) ManagementService { return ManagementService{ - base: message.NewBaseWithClient(wsmanMessageCreator, AMT_PublicKeyManagementService, client), + base: message.NewBaseWithClient(wsmanMessageCreator, AMTPublicKeyManagementService, client), } } -// Get retrieves the representation of the instance +// Get retrieves the representation of the instance. func (managementService ManagementService) Get() (response Response, err error) { response = Response{ Message: &client.Message{ XMLInput: managementService.base.Get(nil), }, } + // send the message to AMT err = managementService.base.Execute(response.Message) if err != nil { - return + return response, err } + // put the xml response into the go struct err = xml.Unmarshal([]byte(response.XMLOutput), &response) if err != nil { - return + return response, err } - return + + return response, nil } -// Enumerate returns an enumeration context which is used in a subsequent Pull call +// Enumerate returns an enumeration context which is used in a subsequent Pull call. func (managementService ManagementService) Enumerate() (response Response, err error) { response = Response{ Message: &client.Message{ XMLInput: managementService.base.Enumerate(), }, } + // send the message to AMT err = managementService.base.Execute(response.Message) if err != nil { - return + return response, err } + // put the xml response into the go struct err = xml.Unmarshal([]byte(response.XMLOutput), &response) if err != nil { - return + return response, err } - return + + return response, nil } // Pull returns the instances of this class. An enumeration context provided by the Enumerate call is used as input. @@ -70,20 +76,23 @@ func (managementService ManagementService) Pull(enumerationContext string) (resp XMLInput: managementService.base.Pull(enumerationContext), }, } + // send the message to AMT err = managementService.base.Execute(response.Message) if err != nil { - return + return response, err } + // put the xml response into the go struct err = xml.Unmarshal([]byte(response.XMLOutput), &response) if err != nil { - return + return response, err } - return + + return response, nil } -// Delete removes a the specified instance +// Delete removes a the specified instance. func (managementService ManagementService) Delete(instanceID string) (response Response, err error) { selector := message.Selector{Name: "InstanceID", Value: instanceID} response = Response{ @@ -91,20 +100,23 @@ func (managementService ManagementService) Delete(instanceID string) (response R XMLInput: managementService.base.Delete(selector), }, } + // send the message to AMT err = managementService.base.Execute(response.Message) if err != nil { - return + return response, err } + // put the xml response into the go struct err = xml.Unmarshal([]byte(response.XMLOutput), &response) if err != nil { - return + return response, err } - return + + return response, nil } -//unittest +// unittest // func TestCheckReturnValue(t *testing.T) { // tests := []struct { // name string @@ -131,103 +143,117 @@ func checkReturnValue(rc int, item string) (err error) { return errors.New(item + " already exists and must be removed before continuing") } else if rc == int(ReturnValueInvalidCert) { return errors.New(item + " is invalid") - } else { - return errors.New(item + " non-zero return code: " + strconv.Itoa(rc)) } + + return errors.New(item + " non-zero return code: " + strconv.Itoa(rc)) } + return nil } // This function adds new certificate to the Intel® AMT CertStore. A certificate cannot be removed if it is referenced (for example, used by TLS, 802.1X or EAC). func (managementService ManagementService) AddCertificate(certificateBlob string) (response Response, err error) { - header := managementService.base.WSManMessageCreator.CreateHeader(methods.GenerateAction(AMT_PublicKeyManagementService, AddCertificate), AMT_PublicKeyManagementService, nil, "", "") + header := managementService.base.WSManMessageCreator.CreateHeader(methods.GenerateAction(AMTPublicKeyManagementService, AddCertificate), AMTPublicKeyManagementService, nil, "", "") certificate := AddCertificate_INPUT{ - H: fmt.Sprintf("%s%s", message.AMTSchema, AMT_PublicKeyManagementService), + H: fmt.Sprintf("%s%s", message.AMTSchema, AMTPublicKeyManagementService), CertificateBlob: certificateBlob, } - body := managementService.base.WSManMessageCreator.CreateBody(methods.GenerateInputMethod(AddCertificate), AMT_PublicKeyManagementService, &certificate) + body := managementService.base.WSManMessageCreator.CreateBody(methods.GenerateInputMethod(AddCertificate), AMTPublicKeyManagementService, &certificate) + response = Response{ Message: &client.Message{ XMLInput: managementService.base.WSManMessageCreator.CreateXML(header, body), }, } + // send the message to AMT err = managementService.base.Execute(response.Message) if err != nil { - return + return response, err } + // put the xml response into the go struct err = xml.Unmarshal([]byte(response.XMLOutput), &response) if err != nil { - return + return response, err } + err = checkReturnValue(int(response.Body.AddCertificate_OUTPUT.ReturnValue), "Client Certificate") - return + + return response, err } // This function adds new root certificate to the Intel® AMT CertStore. A certificate cannot be removed if it is referenced (for example, used by TLS, 802.1X or EAC). func (managementService ManagementService) AddTrustedRootCertificate(certificateBlob string) (response Response, err error) { - header := managementService.base.WSManMessageCreator.CreateHeader(methods.GenerateAction(AMT_PublicKeyManagementService, AddTrustedRootCertificate), AMT_PublicKeyManagementService, nil, "", "") + header := managementService.base.WSManMessageCreator.CreateHeader(methods.GenerateAction(AMTPublicKeyManagementService, AddTrustedRootCertificate), AMTPublicKeyManagementService, nil, "", "") trustedRootCert := AddTrustedRootCertificate_INPUT{ - H: fmt.Sprintf("%s%s", message.AMTSchema, AMT_PublicKeyManagementService), + H: fmt.Sprintf("%s%s", message.AMTSchema, AMTPublicKeyManagementService), CertificateBlob: certificateBlob, } - body := managementService.base.WSManMessageCreator.CreateBody(methods.GenerateInputMethod(AddTrustedRootCertificate), AMT_PublicKeyManagementService, &trustedRootCert) + body := managementService.base.WSManMessageCreator.CreateBody(methods.GenerateInputMethod(AddTrustedRootCertificate), AMTPublicKeyManagementService, &trustedRootCert) response = Response{ Message: &client.Message{ XMLInput: managementService.base.WSManMessageCreator.CreateXML(header, body), }, } + // send the message to AMT err = managementService.base.Execute(response.Message) if err != nil { - return + return response, err } + // put the xml response into the go struct err = xml.Unmarshal([]byte(response.XMLOutput), &response) if err != nil { - return + return response, err } + err = checkReturnValue(int(response.Body.AddTrustedRootCertificate_OUTPUT.ReturnValue), "Root Certificate") - return + return response, err } -// This API is used to generate a key in the FW +// This API is used to generate a key in the FW. func (managementService ManagementService) GenerateKeyPair(keyAlgorithm KeyAlgorithm, keyLength KeyLength) (response Response, err error) { - header := managementService.base.WSManMessageCreator.CreateHeader(methods.GenerateAction(AMT_PublicKeyManagementService, GenerateKeyPair), AMT_PublicKeyManagementService, nil, "", "") + header := managementService.base.WSManMessageCreator.CreateHeader(methods.GenerateAction(AMTPublicKeyManagementService, GenerateKeyPair), AMTPublicKeyManagementService, nil, "", "") generateKeyPair := GenerateKeyPair_INPUT{ - H: fmt.Sprintf("%s%s", message.AMTSchema, AMT_PublicKeyManagementService), + H: fmt.Sprintf("%s%s", message.AMTSchema, AMTPublicKeyManagementService), KeyAlgorithm: keyAlgorithm, KeyLength: keyLength, } - body := managementService.base.WSManMessageCreator.CreateBody(methods.GenerateInputMethod(GenerateKeyPair), AMT_PublicKeyManagementService, &generateKeyPair) + + body := managementService.base.WSManMessageCreator.CreateBody(methods.GenerateInputMethod(GenerateKeyPair), AMTPublicKeyManagementService, &generateKeyPair) + response = Response{ Message: &client.Message{ XMLInput: managementService.base.WSManMessageCreator.CreateXML(header, body), }, } + // send the message to AMT err = managementService.base.Execute(response.Message) if err != nil { - return + return response, err } + // put the xml response into the go struct err = xml.Unmarshal([]byte(response.XMLOutput), &response) if err != nil { - return + return response, err } + err = checkReturnValue(int(response.Body.AddKey_OUTPUT.ReturnValue), "Private Key") - return + return response, err } // This API is used to create a PKCS#10 certificate signing request based on a key from the key store. func (managementService ManagementService) GeneratePKCS10RequestEx(keyPair, nullSignedCertificateRequest string, signingAlgorithm SigningAlgorithm) (response Response, err error) { - header := managementService.base.WSManMessageCreator.CreateHeader(methods.GenerateAction(AMT_PublicKeyManagementService, GeneratePKCS10RequestEx), AMT_PublicKeyManagementService, nil, "", "") + header := managementService.base.WSManMessageCreator.CreateHeader(methods.GenerateAction(AMTPublicKeyManagementService, GeneratePKCS10RequestEx), AMTPublicKeyManagementService, nil, "", "") pkcs10Request := PKCS10Request{ - H: fmt.Sprintf("%s%s", message.AMTSchema, AMT_PublicKeyManagementService), + H: fmt.Sprintf("%s%s", message.AMTSchema, AMTPublicKeyManagementService), KeyPair: KeyPair{ Address: "http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous", ReferenceParameters: ReferenceParametersRequest{ @@ -245,23 +271,26 @@ func (managementService ManagementService) GeneratePKCS10RequestEx(keyPair, null SigningAlgorithm: signingAlgorithm, NullSignedCertificateRequest: nullSignedCertificateRequest, } - body := managementService.base.WSManMessageCreator.CreateBody(methods.GenerateInputMethod(GeneratePKCS10RequestEx), AMT_PublicKeyManagementService, &pkcs10Request) + body := managementService.base.WSManMessageCreator.CreateBody(methods.GenerateInputMethod(GeneratePKCS10RequestEx), AMTPublicKeyManagementService, &pkcs10Request) response = Response{ Message: &client.Message{ XMLInput: managementService.base.WSManMessageCreator.CreateXML(header, body), }, } + // send the message to AMT err = managementService.base.Execute(response.Message) if err != nil { - return + return response, err } + // put the xml response into the go struct err = xml.Unmarshal([]byte(response.XMLOutput), &response) if err != nil { - return + return response, err } - return + + return response, nil } // This function adds new certificate key to the Intel® AMT CertStore. A key cannot be removed if its corresponding certificate is referenced (for example, used by TLS, 802.1X or EAC). @@ -269,26 +298,29 @@ func (managementService ManagementService) GeneratePKCS10RequestEx(keyPair, null // Possible return values are: PT_STATUS_SUCCESS(0), PT_STATUS_INTERNAL_ERROR(1), PT_STATUS_MAX_LIMIT_REACHED(23), // PT_STATUS_FLASH_WRITE_LIMIT_EXCEEDED(38), PT_STATUS_DUPLICATE(2068), PT_STATUS_INVALID_KEY(2062). func (managementService ManagementService) AddKey(keyBlob string) (response Response, err error) { - header := managementService.base.WSManMessageCreator.CreateHeader(methods.GenerateAction(AMT_PublicKeyManagementService, AddKey), AMT_PublicKeyManagementService, nil, "", "") + header := managementService.base.WSManMessageCreator.CreateHeader(methods.GenerateAction(AMTPublicKeyManagementService, AddKey), AMTPublicKeyManagementService, nil, "", "") params := &AddKey_INPUT{ - H: fmt.Sprintf("%s%s", message.AMTSchema, AMT_PublicKeyManagementService), + H: fmt.Sprintf("%s%s", message.AMTSchema, AMTPublicKeyManagementService), KeyBlob: keyBlob, } - body := managementService.base.WSManMessageCreator.CreateBody(methods.GenerateInputMethod(AddKey), AMT_PublicKeyManagementService, params) + body := managementService.base.WSManMessageCreator.CreateBody(methods.GenerateInputMethod(AddKey), AMTPublicKeyManagementService, params) response = Response{ Message: &client.Message{ XMLInput: managementService.base.WSManMessageCreator.CreateXML(header, body), }, } + // send the message to AMT err = managementService.base.Execute(response.Message) if err != nil { - return + return response, err } + // put the xml response into the go struct err = xml.Unmarshal([]byte(response.XMLOutput), &response) if err != nil { - return + return response, err } - return + + return response, nil } diff --git a/pkg/wsman/amt/publickey/managementservice_test.go b/pkg/wsman/amt/publickey/managementservice_test.go index c8ac6e32..a33e4c64 100644 --- a/pkg/wsman/amt/publickey/managementservice_test.go +++ b/pkg/wsman/amt/publickey/managementservice_test.go @@ -10,26 +10,27 @@ import ( "fmt" "testing" - "github.com/stretchr/testify/assert" - "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/internal/message" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/common" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/wsmantesting" + "github.com/stretchr/testify/assert" ) const ( EnvelopeResponseService = `http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous0` GetBodyService = `AMT_PublicKeyManagementServiceIntel(r) AMT Public Key Management ServiceIntel(r) AMT Public Key Management ServiceCIM_ComputerSystemManagedSystem` + PrivateKey = "privatekey" ) func TestPositiveAMT_PublicKeyManagementService(t *testing.T) { messageID := 0 - resourceUriBase := "http://intel.com/wbem/wscim/1/amt-schema/1/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.AMTResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "amt/publickey/management", } elementUnderTest := NewPublicKeyManagementServiceWithClient(wsmanMessageCreator, &client) + t.Run("amt_PublicKeyManagementService Tests", func(t *testing.T) { tests := []struct { name string @@ -40,21 +41,22 @@ func TestPositiveAMT_PublicKeyManagementService(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //GETS + // GETS { "should create a valid AMT_PublicKeyManagementService Get wsman message", - AMT_PublicKeyManagementService, - wsmantesting.GET, + AMTPublicKeyManagementService, + wsmantesting.Get, "", "", func() (Response, error) { - client.CurrentMessage = "Get" + client.CurrentMessage = wsmantesting.CurrentMessageGet + return elementUnderTest.Get() }, Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, KeyManagementGetResponse: KeyManagementResponse{ - XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMT_PublicKeyManagementService), Local: AMT_PublicKeyManagementService}, + XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMTPublicKeyManagementService), Local: AMTPublicKeyManagementService}, CreationClassName: "AMT_PublicKeyManagementService", ElementName: "Intel(r) AMT Certificate Store Service", EnabledDefault: 5, @@ -66,15 +68,16 @@ func TestPositiveAMT_PublicKeyManagementService(t *testing.T) { }, }, }, - //ENUMERATES + // ENUMERATES { "should create a valid AMT_PublicKeyManagementService Enumerate wsman message", - AMT_PublicKeyManagementService, - wsmantesting.ENUMERATE, - wsmantesting.ENUMERATE_BODY, + AMTPublicKeyManagementService, + wsmantesting.Enumerate, + wsmantesting.EnumerateBody, "", func() (Response, error) { - client.CurrentMessage = "Enumerate" + client.CurrentMessage = wsmantesting.CurrentMessageEnumerate + return elementUnderTest.Enumerate() }, Body{ @@ -84,15 +87,16 @@ func TestPositiveAMT_PublicKeyManagementService(t *testing.T) { }, }, }, - //PULLS + // PULLS { "should create a valid AMT_PublicKeyManagementService Pull wsman message", - AMT_PublicKeyManagementService, - wsmantesting.PULL, - wsmantesting.PULL_BODY, + AMTPublicKeyManagementService, + wsmantesting.Pull, + wsmantesting.PullBody, "", func() (Response, error) { - client.CurrentMessage = "Pull" + client.CurrentMessage = wsmantesting.CurrentMessagePull + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -101,7 +105,7 @@ func TestPositiveAMT_PublicKeyManagementService(t *testing.T) { XMLName: xml.Name{Space: message.XMLPullResponseSpace, Local: "PullResponse"}, KeyManagementItems: []KeyManagementResponse{ { - XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMT_PublicKeyManagementService), Local: AMT_PublicKeyManagementService}, + XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMTPublicKeyManagementService), Local: AMTPublicKeyManagementService}, CreationClassName: "AMT_PublicKeyManagementService", ElementName: "Intel(r) AMT Certificate Store Service", EnabledDefault: 5, @@ -119,18 +123,19 @@ func TestPositiveAMT_PublicKeyManagementService(t *testing.T) { // AddTrustedRootCertificate { "should return a valid amt_PublicKeyManagementService AddTrustedRootCertificate wsman message", - AMT_PublicKeyManagementService, + AMTPublicKeyManagementService, `http://intel.com/wbem/wscim/1/amt-schema/1/AMT_PublicKeyManagementService/AddTrustedRootCertificate`, fmt.Sprintf(`%s`, wsmantesting.TrustedRootCert), "", func() (Response, error) { client.CurrentMessage = "AddTrustedRootCertificate" + return elementUnderTest.AddTrustedRootCertificate(wsmantesting.TrustedRootCert) }, Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, AddTrustedRootCertificate_OUTPUT: AddTrustedRootCertificate_OUTPUT{ - XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMT_PublicKeyManagementService), Local: "AddTrustedRootCertificate_OUTPUT"}, + XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMTPublicKeyManagementService), Local: "AddTrustedRootCertificate_OUTPUT"}, CreatedCertificate: CreatedCertificateResponse{ XMLName: xml.Name{Space: "http://intel.com/wbem/wscim/1/amt-schema/1/AMT_PublicKeyManagementService", Local: "CreatedCertificate"}, Address: "http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous", @@ -157,18 +162,19 @@ func TestPositiveAMT_PublicKeyManagementService(t *testing.T) { // GenerateKeyPair { "should return a valid amt_PublicKeyManagementService GenerateKeyPair wsman message", - AMT_PublicKeyManagementService, + AMTPublicKeyManagementService, `http://intel.com/wbem/wscim/1/amt-schema/1/AMT_PublicKeyManagementService/GenerateKeyPair`, `02048`, "", func() (Response, error) { client.CurrentMessage = "GenerateKeyPair" + return elementUnderTest.GenerateKeyPair(RSA, KeyLength2048) }, Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, GenerateKeyPair_OUTPUT: GenerateKeyPair_OUTPUT{ - XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMT_PublicKeyManagementService), Local: "GenerateKeyPair_OUTPUT"}, + XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMTPublicKeyManagementService), Local: "GenerateKeyPair_OUTPUT"}, KeyPair: KeyPairResponse{ XMLName: xml.Name{Space: "http://intel.com/wbem/wscim/1/amt-schema/1/AMT_PublicKeyManagementService", Local: "KeyPair"}, Address: "http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous", @@ -194,18 +200,19 @@ func TestPositiveAMT_PublicKeyManagementService(t *testing.T) { // AddCertificate { "should return a valid amt_PublicKeyManagementService AddCertificate wsman message", - AMT_PublicKeyManagementService, + AMTPublicKeyManagementService, `http://intel.com/wbem/wscim/1/amt-schema/1/AMT_PublicKeyManagementService/AddCertificate`, fmt.Sprintf(`%s`, wsmantesting.TrustedRootCert), "", func() (Response, error) { client.CurrentMessage = "AddCertificate" + return elementUnderTest.AddCertificate(wsmantesting.TrustedRootCert) }, Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, AddCertificate_OUTPUT: AddCertificate_OUTPUT{ - XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMT_PublicKeyManagementService), Local: "AddCertificate_OUTPUT"}, + XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMTPublicKeyManagementService), Local: "AddCertificate_OUTPUT"}, CreatedCertificate: CreatedCertificateResponse{ XMLName: xml.Name{Space: "http://intel.com/wbem/wscim/1/amt-schema/1/AMT_PublicKeyManagementService", Local: "CreatedCertificate"}, Address: "http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous", @@ -231,18 +238,19 @@ func TestPositiveAMT_PublicKeyManagementService(t *testing.T) { // PKCS10RequestEx { "should return a valid amt_PublicKeyManagementService GeneratePKCS10RequestEx wsman message", - AMT_PublicKeyManagementService, + AMTPublicKeyManagementService, "http://intel.com/wbem/wscim/1/amt-schema/1/AMT_PublicKeyManagementService/GeneratePKCS10RequestEx", fmt.Sprintf("http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymoushttp://intel.com/wbem/wscim/1/amt-schema/1/AMT_PublicPrivateKeyPair%s1reallylongcertificateteststring", "test"), "", func() (Response, error) { client.CurrentMessage = "GeneratePKCS10RequestEx" + return elementUnderTest.GeneratePKCS10RequestEx("test", "reallylongcertificateteststring", 1) }, Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, GeneratePKCS10RequestEx_OUTPUT: GeneratePKCS10RequestEx_OUTPUT{ - XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMT_PublicKeyManagementService), Local: "GeneratePKCS10RequestEx_OUTPUT"}, + XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMTPublicKeyManagementService), Local: "GeneratePKCS10RequestEx_OUTPUT"}, SignedCertificateRequest: "test?", ReturnValue: 0, }, @@ -251,19 +259,20 @@ func TestPositiveAMT_PublicKeyManagementService(t *testing.T) { // AddKey { "should return a valid amt_PublicKeyManagementService AddKey wsman message", - AMT_PublicKeyManagementService, + AMTPublicKeyManagementService, "http://intel.com/wbem/wscim/1/amt-schema/1/AMT_PublicKeyManagementService/AddKey", `privatekey`, "", func() (Response, error) { client.CurrentMessage = "AddKey" - cert := "privatekey" + cert := PrivateKey + return elementUnderTest.AddKey(cert) }, Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, AddKey_OUTPUT: AddKey_OUTPUT{ - XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMT_PublicKeyManagementService), Local: "AddKey_OUTPUT"}, + XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMTPublicKeyManagementService), Local: "AddKey_OUTPUT"}, CreatedKey: CreatedKeyResponse{ XMLName: xml.Name{Space: "http://intel.com/wbem/wscim/1/amt-schema/1/AMT_PublicKeyManagementService", Local: "CreatedKey"}, Address: "http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous", @@ -289,12 +298,13 @@ func TestPositiveAMT_PublicKeyManagementService(t *testing.T) { // DELETE { "should create a valid amt_PublicKeyManagementService Delete wsman message", - AMT_PublicKeyManagementService, - wsmantesting.DELETE, + AMTPublicKeyManagementService, + wsmantesting.Delete, "", "instanceID123", func() (Response, error) { - client.CurrentMessage = "Delete" + client.CurrentMessage = wsmantesting.CurrentMessageDelete + return elementUnderTest.Delete("instanceID123") }, Body{XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}}, @@ -303,7 +313,7 @@ func TestPositiveAMT_PublicKeyManagementService(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, test.extraHeader, test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, test.extraHeader, test.body) messageID++ response, err := test.responseFunc() assert.NoError(t, err) @@ -313,14 +323,16 @@ func TestPositiveAMT_PublicKeyManagementService(t *testing.T) { } }) } + func TestNegativeAMT_PublicKeyManagementService(t *testing.T) { messageID := 0 - resourceUriBase := "http://intel.com/wbem/wscim/1/amt-schema/1/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.AMTResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "amt/publickey/management", } elementUnderTest := NewPublicKeyManagementServiceWithClient(wsmanMessageCreator, &client) + t.Run("amt_PublicKeyManagementService Tests", func(t *testing.T) { tests := []struct { name string @@ -331,21 +343,22 @@ func TestNegativeAMT_PublicKeyManagementService(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //GETS + // GETS { "should create a invalid AMT_PublicKeyManagementService Get wsman message", - AMT_PublicKeyManagementService, - wsmantesting.GET, + AMTPublicKeyManagementService, + wsmantesting.Get, "", "", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Get() }, Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, KeyManagementGetResponse: KeyManagementResponse{ - XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMT_PublicKeyManagementService), Local: AMT_PublicKeyManagementService}, + XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMTPublicKeyManagementService), Local: AMTPublicKeyManagementService}, CreationClassName: "AMT_PublicKeyManagementService", ElementName: "Intel(r) AMT Certificate Store Service", EnabledDefault: 5, @@ -357,15 +370,16 @@ func TestNegativeAMT_PublicKeyManagementService(t *testing.T) { }, }, }, - //ENUMERATES + // ENUMERATES { "should create a invalid AMT_PublicKeyManagementService Enumerate wsman message", - AMT_PublicKeyManagementService, - wsmantesting.ENUMERATE, - wsmantesting.ENUMERATE_BODY, + AMTPublicKeyManagementService, + wsmantesting.Enumerate, + wsmantesting.EnumerateBody, "", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Enumerate() }, Body{ @@ -375,15 +389,16 @@ func TestNegativeAMT_PublicKeyManagementService(t *testing.T) { }, }, }, - //PULLS + // PULLS { "should create a invalid AMT_PublicKeyManagementService Pull wsman message", - AMT_PublicKeyManagementService, - wsmantesting.PULL, - wsmantesting.PULL_BODY, + AMTPublicKeyManagementService, + wsmantesting.Pull, + wsmantesting.PullBody, "", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -392,7 +407,7 @@ func TestNegativeAMT_PublicKeyManagementService(t *testing.T) { XMLName: xml.Name{Space: message.XMLPullResponseSpace, Local: "PullResponse"}, KeyManagementItems: []KeyManagementResponse{ { - XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMT_PublicKeyManagementService), Local: AMT_PublicKeyManagementService}, + XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMTPublicKeyManagementService), Local: AMTPublicKeyManagementService}, CreationClassName: "AMT_PublicKeyManagementService", ElementName: "Intel(r) AMT Certificate Store Service", EnabledDefault: 5, @@ -410,18 +425,19 @@ func TestNegativeAMT_PublicKeyManagementService(t *testing.T) { // AddTrustedRootCertificate { "should return a invalid amt_PublicKeyManagementService AddTrustedRootCertificate wsman message", - AMT_PublicKeyManagementService, + AMTPublicKeyManagementService, `http://intel.com/wbem/wscim/1/amt-schema/1/AMT_PublicKeyManagementService/AddTrustedRootCertificate`, fmt.Sprintf(`%s`, wsmantesting.TrustedRootCert), "", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.AddTrustedRootCertificate(wsmantesting.TrustedRootCert) }, Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, AddTrustedRootCertificate_OUTPUT: AddTrustedRootCertificate_OUTPUT{ - XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMT_PublicKeyManagementService), Local: "AddTrustedRootCertificate_OUTPUT"}, + XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMTPublicKeyManagementService), Local: "AddTrustedRootCertificate_OUTPUT"}, CreatedCertificate: CreatedCertificateResponse{ XMLName: xml.Name{Space: "http://intel.com/wbem/wscim/1/amt-schema/1/AMT_PublicKeyManagementService", Local: "CreatedCertificate"}, Address: "http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous", @@ -448,18 +464,19 @@ func TestNegativeAMT_PublicKeyManagementService(t *testing.T) { // GenerateKeyPair { "should return a invalid amt_PublicKeyManagementService GenerateKeyPair wsman message", - AMT_PublicKeyManagementService, + AMTPublicKeyManagementService, `http://intel.com/wbem/wscim/1/amt-schema/1/AMT_PublicKeyManagementService/GenerateKeyPair`, `02048`, "", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.GenerateKeyPair(RSA, KeyLength2048) }, Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, GenerateKeyPair_OUTPUT: GenerateKeyPair_OUTPUT{ - XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMT_PublicKeyManagementService), Local: "GenerateKeyPair_OUTPUT"}, + XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMTPublicKeyManagementService), Local: "GenerateKeyPair_OUTPUT"}, KeyPair: KeyPairResponse{ XMLName: xml.Name{Space: "http://intel.com/wbem/wscim/1/amt-schema/1/AMT_PublicKeyManagementService", Local: "KeyPair"}, Address: "http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous", @@ -485,18 +502,19 @@ func TestNegativeAMT_PublicKeyManagementService(t *testing.T) { // AddCertificate { "should return a invalid amt_PublicKeyManagementService AddCertificate wsman message", - AMT_PublicKeyManagementService, + AMTPublicKeyManagementService, `http://intel.com/wbem/wscim/1/amt-schema/1/AMT_PublicKeyManagementService/AddCertificate`, fmt.Sprintf(`%s`, wsmantesting.TrustedRootCert), "", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.AddCertificate(wsmantesting.TrustedRootCert) }, Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, AddCertificate_OUTPUT: AddCertificate_OUTPUT{ - XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMT_PublicKeyManagementService), Local: "AddCertificate_OUTPUT"}, + XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMTPublicKeyManagementService), Local: "AddCertificate_OUTPUT"}, CreatedCertificate: CreatedCertificateResponse{ XMLName: xml.Name{Space: "http://intel.com/wbem/wscim/1/amt-schema/1/AMT_PublicKeyManagementService", Local: "CreatedCertificate"}, Address: "http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous", @@ -523,18 +541,19 @@ func TestNegativeAMT_PublicKeyManagementService(t *testing.T) { // PKCS10RequestEx { "should return a invalid amt_PublicKeyManagementService GeneratePKCS10RequestEx wsman message", - AMT_PublicKeyManagementService, + AMTPublicKeyManagementService, "http://intel.com/wbem/wscim/1/amt-schema/1/AMT_PublicKeyManagementService/GeneratePKCS10RequestEx", fmt.Sprintf("http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymoushttp://intel.com/wbem/wscim/1/amt-schema/1/AMT_PublicPrivateKeyPair%s1reallylongcertificateteststring", "test"), "", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.GeneratePKCS10RequestEx("test", "reallylongcertificateteststring", 1) }, Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, GeneratePKCS10RequestEx_OUTPUT: GeneratePKCS10RequestEx_OUTPUT{ - XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMT_PublicKeyManagementService), Local: "GeneratePKCS10RequestEx_OUTPUT"}, + XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMTPublicKeyManagementService), Local: "GeneratePKCS10RequestEx_OUTPUT"}, SignedCertificateRequest: "test?", ReturnValue: 0, }, @@ -544,19 +563,20 @@ func TestNegativeAMT_PublicKeyManagementService(t *testing.T) { // AddKey { "should return a invalid amt_PublicKeyManagementService AddKey wsman message", - AMT_PublicKeyManagementService, + AMTPublicKeyManagementService, "http://intel.com/wbem/wscim/1/amt-schema/1/AMT_PublicKeyManagementService/AddKey", `privatekey`, "", func() (Response, error) { - client.CurrentMessage = "Error" - cert := "privatekey" + client.CurrentMessage = wsmantesting.CurrentMessageError + cert := PrivateKey + return elementUnderTest.AddKey(cert) }, Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, AddKey_OUTPUT: AddKey_OUTPUT{ - XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMT_PublicKeyManagementService), Local: "AddKey_OUTPUT"}, + XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMTPublicKeyManagementService), Local: "AddKey_OUTPUT"}, CreatedKey: CreatedKeyResponse{ XMLName: xml.Name{Space: "http://intel.com/wbem/wscim/1/amt-schema/1/AMT_PublicKeyManagementService", Local: "CreatedKey"}, Address: "http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous", @@ -582,12 +602,13 @@ func TestNegativeAMT_PublicKeyManagementService(t *testing.T) { // DELETE { "should create a invalid amt_PublicKeyManagementService Delete wsman message", - AMT_PublicKeyManagementService, - wsmantesting.DELETE, + AMTPublicKeyManagementService, + wsmantesting.Delete, "", "instanceID123", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Delete("instanceID123") }, Body{XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}}, @@ -596,7 +617,7 @@ func TestNegativeAMT_PublicKeyManagementService(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, test.extraHeader, test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, test.extraHeader, test.body) messageID++ response, err := test.responseFunc() assert.Error(t, err) diff --git a/pkg/wsman/amt/publickey/marshal.go b/pkg/wsman/amt/publickey/marshal.go index 4ae41de0..5bc85dd2 100644 --- a/pkg/wsman/amt/publickey/marshal.go +++ b/pkg/wsman/amt/publickey/marshal.go @@ -11,20 +11,22 @@ import ( "gopkg.in/yaml.v3" ) -// JSON marshals the type into JSON format +// JSON marshals the type into JSON format. func (r *Response) JSON() string { jsonOutput, err := json.Marshal(r.Body) if err != nil { return "" } + return string(jsonOutput) } -// YAML marshals the type into YAML format +// YAML marshals the type into YAML format. func (r *Response) YAML() string { yamlOutput, err := yaml.Marshal(r.Body) if err != nil { return "" } + return string(yamlOutput) } diff --git a/pkg/wsman/amt/publickey/types.go b/pkg/wsman/amt/publickey/types.go index 407da627..6d6c6ec7 100644 --- a/pkg/wsman/amt/publickey/types.go +++ b/pkg/wsman/amt/publickey/types.go @@ -22,7 +22,7 @@ type Certificate struct { } // OUTPUTS -// Response Types +// Response Types. type ( Response struct { *client.Message @@ -141,7 +141,7 @@ type ( ) // INPUTS -// Request Types +// Request Types. type ( PublicKeyCertificateRequest struct { XMLName xml.Name `xml:"h:AMT_PublicKeyCertificate"` @@ -218,9 +218,9 @@ type ( // // ValueMap={0, ..} // - // Values={RSA, Reserved} + // Values={RSA, Reserved}. KeyAlgorithm int - // The length of the generatd key in bits + // The length of the generatd key in bits. KeyLength int ) diff --git a/pkg/wsman/amt/publicprivate/constants.go b/pkg/wsman/amt/publicprivate/constants.go index 065e5252..4d725428 100644 --- a/pkg/wsman/amt/publicprivate/constants.go +++ b/pkg/wsman/amt/publicprivate/constants.go @@ -6,5 +6,5 @@ package publicprivate const ( - AMT_PublicPrivateKeyPair string = "AMT_PublicPrivateKeyPair" + AMTPublicPrivateKeyPair string = "AMT_PublicPrivateKeyPair" ) diff --git a/pkg/wsman/amt/publicprivate/keypair.go b/pkg/wsman/amt/publicprivate/keypair.go index b89250be..7c8408b6 100644 --- a/pkg/wsman/amt/publicprivate/keypair.go +++ b/pkg/wsman/amt/publicprivate/keypair.go @@ -15,14 +15,14 @@ import ( "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/client" ) -// NewPublicPrivateKeyPairWithClient instantiates a new KeyPair +// NewPublicPrivateKeyPairWithClient instantiates a new KeyPair. func NewPublicPrivateKeyPairWithClient(wsmanMessageCreator *message.WSManMessageCreator, client client.WSMan) KeyPair { return KeyPair{ - base: message.NewBaseWithClient(wsmanMessageCreator, AMT_PublicPrivateKeyPair, client), + base: message.NewBaseWithClient(wsmanMessageCreator, AMTPublicPrivateKeyPair, client), } } -// Get retrieves the representation of the instance +// Get retrieves the representation of the instance. func (keyPair KeyPair) Get(instanceID string) (response Response, err error) { selector := message.Selector{ Name: "InstanceID", @@ -30,7 +30,7 @@ func (keyPair KeyPair) Get(instanceID string) (response Response, err error) { } response = Response{ Message: &client.Message{ - XMLInput: keyPair.base.Get((*message.Selector)(&selector)), + XMLInput: keyPair.base.Get(&selector), }, } // send the message to AMT @@ -43,10 +43,11 @@ func (keyPair KeyPair) Get(instanceID string) (response Response, err error) { if err != nil { return } + return } -// Enumerate returns an enumeration context which is used in a subsequent Pull call +// Enumerate returns an enumeration context which is used in a subsequent Pull call. func (keyPair KeyPair) Enumerate() (response Response, err error) { response = Response{ Message: &client.Message{ @@ -63,6 +64,7 @@ func (keyPair KeyPair) Enumerate() (response Response, err error) { if err != nil { return } + return } @@ -83,10 +85,11 @@ func (keyPair KeyPair) Pull(enumerationContext string) (response Response, err e if err != nil { return } + return } -// Deletes an instance of a key pair +// Deletes an instance of a key pair. func (keyPair KeyPair) Delete(handle string) (response Response, err error) { selector := message.Selector{ Name: "InstanceID", @@ -107,5 +110,6 @@ func (keyPair KeyPair) Delete(handle string) (response Response, err error) { if err != nil { return } + return } diff --git a/pkg/wsman/amt/publicprivate/keypair_test.go b/pkg/wsman/amt/publicprivate/keypair_test.go index 51506e3e..b928ac28 100644 --- a/pkg/wsman/amt/publicprivate/keypair_test.go +++ b/pkg/wsman/amt/publicprivate/keypair_test.go @@ -10,11 +10,10 @@ import ( "fmt" "testing" - "github.com/stretchr/testify/assert" - "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/internal/message" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/common" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/wsmantesting" + "github.com/stretchr/testify/assert" ) func TestJson(t *testing.T) { @@ -39,14 +38,20 @@ func TestYaml(t *testing.T) { assert.Equal(t, expectedResult, result) } -func TestPositiveAMT_PublicPrivateKeyPair(t *testing.T) { - messageID := 0 - resourceUriBase := message.AMTSchema - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) - client := wsmantesting.MockClient{ +func testSetup() (messageID int, resourceURIBase string, client *wsmantesting.MockClient, elementUnderTest KeyPair) { + messageID = 0 + resourceURIBase = message.AMTSchema + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) + client = &wsmantesting.MockClient{ PackageUnderTest: "amt/publicprivate", } - elementUnderTest := NewPublicPrivateKeyPairWithClient(wsmanMessageCreator, &client) + elementUnderTest = NewPublicPrivateKeyPairWithClient(wsmanMessageCreator, client) + + return messageID, resourceURIBase, client, elementUnderTest +} + +func TestPositiveAMT_PublicPrivateKeyPair(t *testing.T) { + messageID, resourceURIBase, client, elementUnderTest := testSetup() t.Run("amt_PublicPrivateKeyPair Tests", func(t *testing.T) { tests := []struct { @@ -58,35 +63,37 @@ func TestPositiveAMT_PublicPrivateKeyPair(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //GETS + // GETS { "should create a valid AMT_PublicPrivateKeyPair Get wsman message", - AMT_PublicPrivateKeyPair, wsmantesting.GET, + AMTPublicPrivateKeyPair, wsmantesting.Get, "", "Intel(r) AMT Key: Handle: 0", func() (Response, error) { - client.CurrentMessage = "Get" + client.CurrentMessage = wsmantesting.CurrentMessageGet + return elementUnderTest.Get("Intel(r) AMT Key: Handle: 0") }, Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, GetResponse: PublicPrivateKeyPair{ - XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMT_PublicPrivateKeyPair), Local: AMT_PublicPrivateKeyPair}, + XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMTPublicPrivateKeyPair), Local: AMTPublicPrivateKeyPair}, ElementName: "Intel(r) AMT Key", InstanceID: "Intel(r) AMT Key: Handle: 0", DERKey: "MIIBCgKCAQEA4y00wezZ1XwsSITMvqeYf61tgfVhlGbBVwq9Au0BaEgofPFCLuWMnKaTnMhUlJEGaeB2y6F8qjId0xMwLtNY6XWhmMoCP0R+ymgClT0treqtYp2zL1QPK1R04KTgF0KZh247oQpPGnB2nIe7PKCjPaY8BfOyBC6eNLeWUVIOA5TLL0gSTuk8y3iaadKo+LoWBaH/WDrIJ21Dzn6yU3zGueA8tphPH7yXaOJuNiijOUYZjVT7J0Ia8qMxUv1CrbfL2+N0lrcCG/E4f0QF1XgoCJnwIHdYaNhWzKVhfh2TTZIxJo8bXngckNOLzdYM35hUq98CxPiMSO8+G7J8RZaobQIDAQAB", }, }, }, - //ENUMERATES + // ENUMERATES { "should create a valid AMT_PublicPrivateKeyPair Enumerate wsman message", - AMT_PublicPrivateKeyPair, - wsmantesting.ENUMERATE, - wsmantesting.ENUMERATE_BODY, + AMTPublicPrivateKeyPair, + wsmantesting.Enumerate, + wsmantesting.EnumerateBody, "", func() (Response, error) { - client.CurrentMessage = "Enumerate" + client.CurrentMessage = wsmantesting.CurrentMessageEnumerate + return elementUnderTest.Enumerate() }, Body{ @@ -96,15 +103,16 @@ func TestPositiveAMT_PublicPrivateKeyPair(t *testing.T) { }, }, }, - //PULLS + // PULLS { "should create a valid AMT_PublicPrivateKeyPair Pull wsman message", - AMT_PublicPrivateKeyPair, - wsmantesting.PULL, - wsmantesting.PULL_BODY, + AMTPublicPrivateKeyPair, + wsmantesting.Pull, + wsmantesting.PullBody, "", func() (Response, error) { - client.CurrentMessage = "Pull" + client.CurrentMessage = wsmantesting.CurrentMessagePull + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -113,13 +121,13 @@ func TestPositiveAMT_PublicPrivateKeyPair(t *testing.T) { XMLName: xml.Name{Space: message.XMLPullResponseSpace, Local: "PullResponse"}, PublicPrivateKeyPairItems: []PublicPrivateKeyPair{ { - XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMT_PublicPrivateKeyPair), Local: AMT_PublicPrivateKeyPair}, + XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMTPublicPrivateKeyPair), Local: AMTPublicPrivateKeyPair}, ElementName: "Intel(r) AMT Key", InstanceID: "Intel(r) AMT Key: Handle: 0", DERKey: "MIIBCgKCAQEA4y00wezZ1XwsSITMvqeYf61tgfVhlGbBVwq9Au0BaEgofPFCLuWMnKaTnMhUlJEGaeB2y6F8qjId0xMwLtNY6XWhmMoCP0R+ymgClT0treqtYp2zL1QPK1R04KTgF0KZh247oQpPGnB2nIe7PKCjPaY8BfOyBC6eNLeWUVIOA5TLL0gSTuk8y3iaadKo+LoWBaH/WDrIJ21Dzn6yU3zGueA8tphPH7yXaOJuNiijOUYZjVT7J0Ia8qMxUv1CrbfL2+N0lrcCG/E4f0QF1XgoCJnwIHdYaNhWzKVhfh2TTZIxJo8bXngckNOLzdYM35hUq98CxPiMSO8+G7J8RZaobQIDAQAB", }, { - XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMT_PublicPrivateKeyPair), Local: AMT_PublicPrivateKeyPair}, + XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMTPublicPrivateKeyPair), Local: AMTPublicPrivateKeyPair}, ElementName: "Intel(r) AMT Key", InstanceID: "Intel(r) AMT Key: Handle: 1", DERKey: "MIIBCgKCAQEAvMgYL2FyGuHOVvwYgjABqRlJ8j8LhMo2OCU1HU2WvDN3NoLmjAh2XmBS6ic5IjIc4VtjL7S8ImKP8+PSye9nxf+lv33AqcGsvQFcUuJ5gLTnYzrmqVk6XTcHf1qtvHEmVoykTV6bN7BQx0eTejTjhw3Ro6HZBMyStaTGIKjC9HLQySV6SnFGbrjdNZZoCYsaT8dVetn23npeses9f6dZT5K3IgpA13NcdJioS71uppjIcg8dXpcxA4QKgHLmmELPN9JLbywMvcCuU+xMDceWQlFld9ohmr8NiwgebLyVCh/Q+O+jkQT43snNolyTGLRWQFR4M6DT5fdgXivoFhzMcwIDAQAB", @@ -128,15 +136,16 @@ func TestPositiveAMT_PublicPrivateKeyPair(t *testing.T) { }, }, }, - //DELETE + // DELETE { "should create a valid AMT_PublicPrivateKeyPair Delete wsman message", - AMT_PublicPrivateKeyPair, - wsmantesting.DELETE, + AMTPublicPrivateKeyPair, + wsmantesting.Delete, "", "Intel(r) AMT Key: Handle: 0", func() (Response, error) { - client.CurrentMessage = "Delete" + client.CurrentMessage = wsmantesting.CurrentMessageDelete + return elementUnderTest.Delete("Intel(r) AMT Key: Handle: 0") }, Body{XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}}, @@ -145,7 +154,7 @@ func TestPositiveAMT_PublicPrivateKeyPair(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, test.extraHeader, test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, test.extraHeader, test.body) messageID++ response, err := test.responseFunc() assert.NoError(t, err) @@ -155,14 +164,9 @@ func TestPositiveAMT_PublicPrivateKeyPair(t *testing.T) { } }) } + func TestNegativeAMT_PublicPrivateKeyPair(t *testing.T) { - messageID := 0 - resourceUriBase := message.AMTSchema - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) - client := wsmantesting.MockClient{ - PackageUnderTest: "amt/publicprivate", - } - elementUnderTest := NewPublicPrivateKeyPairWithClient(wsmanMessageCreator, &client) + messageID, resourceURIBase, client, elementUnderTest := testSetup() t.Run("amt_PublicPrivateKeyPair Tests", func(t *testing.T) { tests := []struct { @@ -174,35 +178,37 @@ func TestNegativeAMT_PublicPrivateKeyPair(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //GETS + // GETS { "should create a valid AMT_PublicPrivateKeyPair Get wsman message", - AMT_PublicPrivateKeyPair, wsmantesting.GET, + AMTPublicPrivateKeyPair, wsmantesting.Get, "", "Intel(r) AMT Key: Handle: 0", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Get("Intel(r) AMT Key: Handle: 0") }, Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, GetResponse: PublicPrivateKeyPair{ - XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMT_PublicPrivateKeyPair), Local: AMT_PublicPrivateKeyPair}, + XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMTPublicPrivateKeyPair), Local: AMTPublicPrivateKeyPair}, ElementName: "Intel(r) AMT Key", InstanceID: "Intel(r) AMT Key: Handle: 0", DERKey: "MIIBCgKCAQEA4y00wezZ1XwsSITMvqeYf61tgfVhlGbBVwq9Au0BaEgofPFCLuWMnKaTnMhUlJEGaeB2y6F8qjId0xMwLtNY6XWhmMoCP0R+ymgClT0treqtYp2zL1QPK1R04KTgF0KZh247oQpPGnB2nIe7PKCjPaY8BfOyBC6eNLeWUVIOA5TLL0gSTuk8y3iaadKo+LoWBaH/WDrIJ21Dzn6yU3zGueA8tphPH7yXaOJuNiijOUYZjVT7J0Ia8qMxUv1CrbfL2+N0lrcCG/E4f0QF1XgoCJnwIHdYaNhWzKVhfh2TTZIxJo8bXngckNOLzdYM35hUq98CxPiMSO8+G7J8RZaobQIDAQAB", }, }, }, - //ENUMERATES + // ENUMERATES { "should create a valid AMT_PublicPrivateKeyPair Enumerate wsman message", - AMT_PublicPrivateKeyPair, - wsmantesting.ENUMERATE, - wsmantesting.ENUMERATE_BODY, + AMTPublicPrivateKeyPair, + wsmantesting.Enumerate, + wsmantesting.EnumerateBody, "", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Enumerate() }, Body{ @@ -212,15 +218,16 @@ func TestNegativeAMT_PublicPrivateKeyPair(t *testing.T) { }, }, }, - //PULLS + // PULLS { "should create a valid AMT_PublicPrivateKeyPair Pull wsman message", - AMT_PublicPrivateKeyPair, - wsmantesting.PULL, - wsmantesting.PULL_BODY, + AMTPublicPrivateKeyPair, + wsmantesting.Pull, + wsmantesting.PullBody, "", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -229,13 +236,13 @@ func TestNegativeAMT_PublicPrivateKeyPair(t *testing.T) { XMLName: xml.Name{Space: message.XMLPullResponseSpace, Local: "PullResponse"}, PublicPrivateKeyPairItems: []PublicPrivateKeyPair{ { - XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMT_PublicPrivateKeyPair), Local: AMT_PublicPrivateKeyPair}, + XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMTPublicPrivateKeyPair), Local: AMTPublicPrivateKeyPair}, ElementName: "Intel(r) AMT Key", InstanceID: "Intel(r) AMT Key: Handle: 0", DERKey: "MIIBCgKCAQEA4y00wezZ1XwsSITMvqeYf61tgfVhlGbBVwq9Au0BaEgofPFCLuWMnKaTnMhUlJEGaeB2y6F8qjId0xMwLtNY6XWhmMoCP0R+ymgClT0treqtYp2zL1QPK1R04KTgF0KZh247oQpPGnB2nIe7PKCjPaY8BfOyBC6eNLeWUVIOA5TLL0gSTuk8y3iaadKo+LoWBaH/WDrIJ21Dzn6yU3zGueA8tphPH7yXaOJuNiijOUYZjVT7J0Ia8qMxUv1CrbfL2+N0lrcCG/E4f0QF1XgoCJnwIHdYaNhWzKVhfh2TTZIxJo8bXngckNOLzdYM35hUq98CxPiMSO8+G7J8RZaobQIDAQAB", }, { - XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMT_PublicPrivateKeyPair), Local: AMT_PublicPrivateKeyPair}, + XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMTPublicPrivateKeyPair), Local: AMTPublicPrivateKeyPair}, ElementName: "Intel(r) AMT Key", InstanceID: "Intel(r) AMT Key: Handle: 1", DERKey: "MIIBCgKCAQEAvMgYL2FyGuHOVvwYgjABqRlJ8j8LhMo2OCU1HU2WvDN3NoLmjAh2XmBS6ic5IjIc4VtjL7S8ImKP8+PSye9nxf+lv33AqcGsvQFcUuJ5gLTnYzrmqVk6XTcHf1qtvHEmVoykTV6bN7BQx0eTejTjhw3Ro6HZBMyStaTGIKjC9HLQySV6SnFGbrjdNZZoCYsaT8dVetn23npeses9f6dZT5K3IgpA13NcdJioS71uppjIcg8dXpcxA4QKgHLmmELPN9JLbywMvcCuU+xMDceWQlFld9ohmr8NiwgebLyVCh/Q+O+jkQT43snNolyTGLRWQFR4M6DT5fdgXivoFhzMcwIDAQAB", @@ -244,15 +251,16 @@ func TestNegativeAMT_PublicPrivateKeyPair(t *testing.T) { }, }, }, - //DELETE + // DELETE { "should create a valid AMT_PublicPrivateKeyPair Delete wsman message", - AMT_PublicPrivateKeyPair, - wsmantesting.DELETE, + AMTPublicPrivateKeyPair, + wsmantesting.Delete, "", "Intel(r) AMT Key: Handle: 0", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Delete("Intel(r) AMT Key: Handle: 0") }, Body{XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}}, @@ -261,7 +269,7 @@ func TestNegativeAMT_PublicPrivateKeyPair(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, test.extraHeader, test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, test.extraHeader, test.body) messageID++ response, err := test.responseFunc() assert.Error(t, err) diff --git a/pkg/wsman/amt/publicprivate/marshal.go b/pkg/wsman/amt/publicprivate/marshal.go index 933703b1..37de4232 100644 --- a/pkg/wsman/amt/publicprivate/marshal.go +++ b/pkg/wsman/amt/publicprivate/marshal.go @@ -11,20 +11,22 @@ import ( "gopkg.in/yaml.v3" ) -// JSON marshals the type into JSON format +// JSON marshals the type into JSON format. func (r *Response) JSON() string { jsonOutput, err := json.Marshal(r.Body) if err != nil { return "" } + return string(jsonOutput) } -// YAML marshals the type into YAML format +// YAML marshals the type into YAML format. func (r *Response) YAML() string { yamlOutput, err := yaml.Marshal(r.Body) if err != nil { return "" } + return string(yamlOutput) } diff --git a/pkg/wsman/amt/publicprivate/types.go b/pkg/wsman/amt/publicprivate/types.go index fe56e5c9..f56c61a2 100644 --- a/pkg/wsman/amt/publicprivate/types.go +++ b/pkg/wsman/amt/publicprivate/types.go @@ -18,7 +18,7 @@ type KeyPair struct { } // OUTPUTS -// Response Types +// Response Types. type ( Response struct { *client.Message diff --git a/pkg/wsman/amt/redirection/decoder.go b/pkg/wsman/amt/redirection/decoder.go index f7355f77..a7f0f650 100644 --- a/pkg/wsman/amt/redirection/decoder.go +++ b/pkg/wsman/amt/redirection/decoder.go @@ -6,8 +6,9 @@ package redirection const ( - AMT_RedirectionService string = "AMT_RedirectionService" - RequestStateChange string = "RequestStateChange" + AMTRedirectionService string = "AMT_RedirectionService" + RequestStateChange string = "RequestStateChange" + ValueNotFound string = "Value not found in map" ) const ( @@ -59,7 +60,8 @@ func (es EnabledState) String() string { if v, ok := enabledStateToString[es]; ok { return v } - return "Value not found in map" + + return ValueNotFound } const ( @@ -76,7 +78,7 @@ const ( Busy ReturnValue = 4099 ) -// returnValueToString is a map of ReturnValue values to string +// returnValueToString is a map of ReturnValue values to string. var returnValueToString = map[ReturnValue]string{ CompletedWithNoError: "CompletedWithNoError", NotSupported: "NotSupported", @@ -91,10 +93,11 @@ var returnValueToString = map[ReturnValue]string{ Busy: "Busy", } -// String returns a string representation of ReturnValue +// String returns a string representation of ReturnValue. func (rv ReturnValue) String() string { if v, ok := returnValueToString[rv]; ok { return v } - return "Value not found in map" + + return ValueNotFound } diff --git a/pkg/wsman/amt/redirection/marshal.go b/pkg/wsman/amt/redirection/marshal.go index 494f48a5..adc4c891 100644 --- a/pkg/wsman/amt/redirection/marshal.go +++ b/pkg/wsman/amt/redirection/marshal.go @@ -11,20 +11,22 @@ import ( "gopkg.in/yaml.v3" ) -// JSON marshals the type into JSON format +// JSON marshals the type into JSON format. func (r *Response) JSON() string { jsonOutput, err := json.Marshal(r.Body) if err != nil { return "" } + return string(jsonOutput) } -// YAML marshals the type into YAML format +// YAML marshals the type into YAML format. func (r *Response) YAML() string { yamlOutput, err := yaml.Marshal(r.Body) if err != nil { return "" } + return string(yamlOutput) } diff --git a/pkg/wsman/amt/redirection/service.go b/pkg/wsman/amt/redirection/service.go index 80678429..fb693f31 100644 --- a/pkg/wsman/amt/redirection/service.go +++ b/pkg/wsman/amt/redirection/service.go @@ -16,14 +16,14 @@ import ( "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/client" ) -// NewRedirectionServiceWithClient instantiates a new Service +// NewRedirectionServiceWithClient instantiates a new Service. func NewRedirectionServiceWithClient(wsmanMessageCreator *message.WSManMessageCreator, client client.WSMan) Service { return Service{ - base: message.NewBaseWithClient(wsmanMessageCreator, AMT_RedirectionService, client), + base: message.NewBaseWithClient(wsmanMessageCreator, AMTRedirectionService, client), } } -// Get retrieves the representation of the instance +// Get retrieves the representation of the instance. func (service Service) Get() (response Response, err error) { response = Response{ Message: &client.Message{ @@ -41,10 +41,11 @@ func (service Service) Get() (response Response, err error) { if err != nil { return } + return } -// Enumerate returns an enumeration context which is used in a subsequent Pull call +// Enumerate returns an enumeration context which is used in a subsequent Pull call. func (service Service) Enumerate() (response Response, err error) { response = Response{ Message: &client.Message{ @@ -61,6 +62,7 @@ func (service Service) Enumerate() (response Response, err error) { if err != nil { return } + return } @@ -81,6 +83,7 @@ func (service Service) Pull(enumerationContext string) (response Response, err e if err != nil { return } + return } @@ -95,9 +98,9 @@ func (service Service) Pull(enumerationContext string) (response Response, err e // // - SystemCreationClassName (cannot be modified) // -// - ListenerEnabled +// - ListenerEnabled. func (service Service) Put(redirectionService RedirectionRequest) (response Response, err error) { - redirectionService.H = fmt.Sprintf("%s%s", message.AMTSchema, AMT_RedirectionService) + redirectionService.H = fmt.Sprintf("%s%s", message.AMTSchema, AMTRedirectionService) response = Response{ Message: &client.Message{ XMLInput: service.base.Put(redirectionService, false, nil), @@ -113,6 +116,7 @@ func (service Service) Put(redirectionService RedirectionRequest) (response Resp if err != nil { return } + return } @@ -125,7 +129,7 @@ func (service Service) Put(redirectionService RedirectionRequest) (response Resp func (service Service) RequestStateChange(requestedState RequestedState) (response Response, err error) { response = Response{ Message: &client.Message{ - XMLInput: service.base.RequestStateChange(methods.GenerateAction(AMT_RedirectionService, RequestStateChange), int(requestedState)), + XMLInput: service.base.RequestStateChange(methods.GenerateAction(AMTRedirectionService, RequestStateChange), int(requestedState)), }, } // send the message to AMT @@ -142,5 +146,6 @@ func (service Service) RequestStateChange(requestedState RequestedState) (respon if response.Body.RequestStateChange_OUTPUT.ReturnValue != 0 { err = errors.New("RequestStateChange failed with return code " + response.Body.RequestStateChange_OUTPUT.ReturnValue.String()) } + return } diff --git a/pkg/wsman/amt/redirection/service_test.go b/pkg/wsman/amt/redirection/service_test.go index ebccbc90..f62e8077 100644 --- a/pkg/wsman/amt/redirection/service_test.go +++ b/pkg/wsman/amt/redirection/service_test.go @@ -13,6 +13,7 @@ import ( "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/internal/message" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/common" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/wsmantesting" + "github.com/sirupsen/logrus" "github.com/stretchr/testify/assert" ) @@ -22,7 +23,7 @@ func TestJson(t *testing.T) { GetAndPutResponse: RedirectionResponse{}, }, } - expectedResult := "{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"GetAndPutResponse\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"CreationClassName\":\"\",\"ElementName\":\"\",\"EnabledState\":0,\"ListenerEnabled\":false,\"Name\":\"\",\"SystemCreationClassName\":\"\",\"SystemName\":\"\",\"AccessLog\":null},\"RequestStateChange_OUTPUT\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"ReturnValue\":0},\"EnumerateResponse\":{\"EnumerationContext\":\"\"},\"PullResponse\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"RedirectionItems\":null}}" + expectedResult := "{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"GetAndPutResponse\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"CreationClassName\":\"\",\"ElementName\":\"\",\"EnabledState\":0,\"ListenerEnabled\":false,\"Name\":\"\",\"SystemCreationClassName\":\"\",\"SystemName\":\"\",\"AccessLog\":null},\"RequestStateChangeOutput\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"ReturnValue\":0},\"EnumerateResponse\":{\"EnumerationContext\":\"\"},\"PullResponse\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"RedirectionItems\":null}}" result := response.JSON() assert.Equal(t, expectedResult, result) } @@ -33,15 +34,15 @@ func TestYaml(t *testing.T) { GetAndPutResponse: RedirectionResponse{}, }, } - expectedResult := "xmlname:\n space: \"\"\n local: \"\"\ngetandputresponse:\n xmlname:\n space: \"\"\n local: \"\"\n creationclassname: \"\"\n elementname: \"\"\n enabledstate: 0\n listenerenabled: false\n name: \"\"\n systemcreationclassname: \"\"\n systemname: \"\"\n accesslog: []\nrequeststatechange_output:\n xmlname:\n space: \"\"\n local: \"\"\n returnvalue: 0\nenumerateresponse:\n enumerationcontext: \"\"\npullresponse:\n xmlname:\n space: \"\"\n local: \"\"\n redirectionitems: []\n" + expectedResult := "xmlname:\n space: \"\"\n local: \"\"\ngetandputresponse:\n xmlname:\n space: \"\"\n local: \"\"\n creationclassname: \"\"\n elementname: \"\"\n enabledstate: 0\n listenerenabled: false\n name: \"\"\n systemcreationclassname: \"\"\n systemname: \"\"\n accesslog: []\nrequeststatechangeoutput:\n xmlname:\n space: \"\"\n local: \"\"\n returnvalue: 0\nenumerateresponse:\n enumerationcontext: \"\"\npullresponse:\n xmlname:\n space: \"\"\n local: \"\"\n redirectionitems: []\n" result := response.YAML() assert.Equal(t, expectedResult, result) } func TestPositiveAMT_RedirectionService(t *testing.T) { messageID := 0 - resourceUriBase := "http://intel.com/wbem/wscim/1/amt-schema/1/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.AMTResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "amt/redirectionservice", } @@ -56,21 +57,22 @@ func TestPositiveAMT_RedirectionService(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //GETS + // GETS { "should create a valid AMT_RedirectionService Get wsman message", - AMT_RedirectionService, - wsmantesting.GET, + AMTRedirectionService, + wsmantesting.Get, "", func() (Response, error) { - client.CurrentMessage = "Get" + client.CurrentMessage = wsmantesting.CurrentMessageGet + return elementUnderTest.Get() }, Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, GetAndPutResponse: RedirectionResponse{ - XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMT_RedirectionService), Local: AMT_RedirectionService}, - CreationClassName: AMT_RedirectionService, + XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMTRedirectionService), Local: AMTRedirectionService}, + CreationClassName: AMTRedirectionService, ElementName: "Intel(r) AMT Redirection Service", EnabledState: 32771, ListenerEnabled: true, @@ -80,17 +82,18 @@ func TestPositiveAMT_RedirectionService(t *testing.T) { }, }, }, - //ENUMERATES + // ENUMERATES { "should create a valid AMT_RedirectionService Enumerate wsman message", - AMT_RedirectionService, - wsmantesting.ENUMERATE, - wsmantesting.ENUMERATE_BODY, + AMTRedirectionService, + wsmantesting.Enumerate, + wsmantesting.EnumerateBody, func() (Response, error) { - client.CurrentMessage = "Enumerate" + client.CurrentMessage = wsmantesting.CurrentMessageEnumerate if elementUnderTest.base.WSManMessageCreator == nil { - print("Error") + logrus.Println("Error") } + return elementUnderTest.Enumerate() }, Body{ @@ -100,14 +103,15 @@ func TestPositiveAMT_RedirectionService(t *testing.T) { }, }, }, - //PULLS + // PULLS { "should create a valid AMT_RedirectionService Pull wsman message", - AMT_RedirectionService, - wsmantesting.PULL, - wsmantesting.PULL_BODY, + AMTRedirectionService, + wsmantesting.Pull, + wsmantesting.PullBody, func() (Response, error) { - client.CurrentMessage = "Pull" + client.CurrentMessage = wsmantesting.CurrentMessagePull + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -116,8 +120,8 @@ func TestPositiveAMT_RedirectionService(t *testing.T) { XMLName: xml.Name{Space: message.XMLPullResponseSpace, Local: "PullResponse"}, RedirectionItems: []RedirectionResponse{ { - XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMT_RedirectionService), Local: AMT_RedirectionService}, - CreationClassName: AMT_RedirectionService, + XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMTRedirectionService), Local: AMTRedirectionService}, + CreationClassName: AMTRedirectionService, ElementName: "Intel(r) AMT Redirection Service", EnabledState: 32771, ListenerEnabled: true, @@ -129,16 +133,16 @@ func TestPositiveAMT_RedirectionService(t *testing.T) { }, }, }, - //PUTS + // PUTS { "should create a valid AMT_RedirectionService Put wsman message", - AMT_RedirectionService, - wsmantesting.PUT, + AMTRedirectionService, + wsmantesting.Put, "AMT_RedirectionServiceIntel(r) AMT Redirection Service32771trueIntel(r) AMT Redirection ServiceCIM_ComputerSystemIntel(r) AMT", func() (Response, error) { - client.CurrentMessage = "Put" + client.CurrentMessage = wsmantesting.CurrentMessagePut redirectionRequest := RedirectionRequest{ - CreationClassName: AMT_RedirectionService, + CreationClassName: AMTRedirectionService, ElementName: "Intel(r) AMT Redirection Service", EnabledState: 32771, ListenerEnabled: true, @@ -146,13 +150,14 @@ func TestPositiveAMT_RedirectionService(t *testing.T) { SystemCreationClassName: "CIM_ComputerSystem", SystemName: "Intel(r) AMT", } + return elementUnderTest.Put(redirectionRequest) }, Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, GetAndPutResponse: RedirectionResponse{ - XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMT_RedirectionService), Local: AMT_RedirectionService}, - CreationClassName: AMT_RedirectionService, + XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMTRedirectionService), Local: AMTRedirectionService}, + CreationClassName: AMTRedirectionService, ElementName: "Intel(r) AMT Redirection Service", EnabledState: 32771, ListenerEnabled: true, @@ -162,20 +167,21 @@ func TestPositiveAMT_RedirectionService(t *testing.T) { }, }, }, - //REQUEST STATE CHANGE + // REQUEST STATE CHANGE { "should create a valid AMT_RedirectionService Request State Change wsman message", - AMT_RedirectionService, - fmt.Sprintf("%s%s/%s", message.AMTSchema, AMT_RedirectionService, "RequestStateChange"), + AMTRedirectionService, + fmt.Sprintf("%s%s/%s", message.AMTSchema, AMTRedirectionService, "RequestStateChange"), "32771", func() (Response, error) { client.CurrentMessage = "RequestStateChange" + return elementUnderTest.RequestStateChange(EnableIDERAndSOL) }, Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, RequestStateChange_OUTPUT: RequestStateChange_OUTPUT{ - XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMT_RedirectionService), Local: "RequestStateChange_OUTPUT"}, + XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMTRedirectionService), Local: "RequestStateChange_OUTPUT"}, ReturnValue: 0, }, }, @@ -183,22 +189,21 @@ func TestPositiveAMT_RedirectionService(t *testing.T) { } for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, "", test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, "", test.body) messageID++ response, err := test.responseFunc() assert.NoError(t, err) assert.Equal(t, expectedXMLInput, response.XMLInput) assert.Equal(t, test.expectedResponse, response.Body) - }) } - }) } + func TestNegativeAMT_RedirectionService(t *testing.T) { messageID := 0 - resourceUriBase := "http://intel.com/wbem/wscim/1/amt-schema/1/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.AMTResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "amt/redirectionservice", } @@ -213,21 +218,22 @@ func TestNegativeAMT_RedirectionService(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //GETS + // GETS { "should create a valid AMT_RedirectionService Get wsman message", - AMT_RedirectionService, - wsmantesting.GET, + AMTRedirectionService, + wsmantesting.Get, "", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Get() }, Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, GetAndPutResponse: RedirectionResponse{ - XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMT_RedirectionService), Local: AMT_RedirectionService}, - CreationClassName: AMT_RedirectionService, + XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMTRedirectionService), Local: AMTRedirectionService}, + CreationClassName: AMTRedirectionService, ElementName: "Intel(r) AMT Redirection Service", EnabledState: 32771, ListenerEnabled: true, @@ -237,17 +243,18 @@ func TestNegativeAMT_RedirectionService(t *testing.T) { }, }, }, - //ENUMERATES + // ENUMERATES { "should create a valid AMT_RedirectionService Enumerate wsman message", - AMT_RedirectionService, - wsmantesting.ENUMERATE, - wsmantesting.ENUMERATE_BODY, + AMTRedirectionService, + wsmantesting.Enumerate, + wsmantesting.EnumerateBody, func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError if elementUnderTest.base.WSManMessageCreator == nil { - print("Error") + logrus.Println("Error") } + return elementUnderTest.Enumerate() }, Body{ @@ -257,14 +264,15 @@ func TestNegativeAMT_RedirectionService(t *testing.T) { }, }, }, - //PULLS + // PULLS { "should create a valid AMT_RedirectionService Pull wsman message", - AMT_RedirectionService, - wsmantesting.PULL, - wsmantesting.PULL_BODY, + AMTRedirectionService, + wsmantesting.Pull, + wsmantesting.PullBody, func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -273,8 +281,8 @@ func TestNegativeAMT_RedirectionService(t *testing.T) { XMLName: xml.Name{Space: message.XMLPullResponseSpace, Local: "PullResponse"}, RedirectionItems: []RedirectionResponse{ { - XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMT_RedirectionService), Local: AMT_RedirectionService}, - CreationClassName: AMT_RedirectionService, + XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMTRedirectionService), Local: AMTRedirectionService}, + CreationClassName: AMTRedirectionService, ElementName: "Intel(r) AMT Redirection Service", EnabledState: 32771, ListenerEnabled: true, @@ -286,16 +294,16 @@ func TestNegativeAMT_RedirectionService(t *testing.T) { }, }, }, - //PUTS + // PUTS { "should create a valid AMT_RedirectionService Put wsman message", - AMT_RedirectionService, - wsmantesting.PUT, + AMTRedirectionService, + wsmantesting.Put, "AMT_RedirectionServiceIntel(r) AMT Redirection Service32771trueIntel(r) AMT Redirection ServiceCIM_ComputerSystemIntel(r) AMT", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError redirectionRequest := RedirectionRequest{ - CreationClassName: AMT_RedirectionService, + CreationClassName: AMTRedirectionService, ElementName: "Intel(r) AMT Redirection Service", EnabledState: 32771, ListenerEnabled: true, @@ -303,13 +311,14 @@ func TestNegativeAMT_RedirectionService(t *testing.T) { SystemCreationClassName: "CIM_ComputerSystem", SystemName: "Intel(r) AMT", } + return elementUnderTest.Put(redirectionRequest) }, Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, GetAndPutResponse: RedirectionResponse{ - XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMT_RedirectionService), Local: AMT_RedirectionService}, - CreationClassName: AMT_RedirectionService, + XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMTRedirectionService), Local: AMTRedirectionService}, + CreationClassName: AMTRedirectionService, ElementName: "Intel(r) AMT Redirection Service", EnabledState: 32771, ListenerEnabled: true, @@ -319,20 +328,21 @@ func TestNegativeAMT_RedirectionService(t *testing.T) { }, }, }, - //REQUEST STATE CHANGE + // REQUEST STATE CHANGE { "should create a valid AMT_RedirectionService Request State Change wsman message", - AMT_RedirectionService, - fmt.Sprintf("%s%s/%s", message.AMTSchema, AMT_RedirectionService, "RequestStateChange"), + AMTRedirectionService, + fmt.Sprintf("%s%s/%s", message.AMTSchema, AMTRedirectionService, "RequestStateChange"), "32771", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.RequestStateChange(EnableIDERAndSOL) }, Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, RequestStateChange_OUTPUT: RequestStateChange_OUTPUT{ - XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMT_RedirectionService), Local: "RequestStateChange_OUTPUT"}, + XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMTRedirectionService), Local: "RequestStateChange_OUTPUT"}, ReturnValue: 0, }, }, @@ -340,15 +350,13 @@ func TestNegativeAMT_RedirectionService(t *testing.T) { } for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, "", test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, "", test.body) messageID++ response, err := test.responseFunc() assert.Error(t, err) assert.Equal(t, expectedXMLInput, response.XMLInput) assert.NotEqual(t, test.expectedResponse, response.Body) - }) } - }) } diff --git a/pkg/wsman/amt/redirection/types.go b/pkg/wsman/amt/redirection/types.go index d336b51f..fa2a783e 100644 --- a/pkg/wsman/amt/redirection/types.go +++ b/pkg/wsman/amt/redirection/types.go @@ -18,7 +18,7 @@ type Service struct { } // OUTPUT -// Response Types +// Response Types. type ( Response struct { *client.Message @@ -61,7 +61,7 @@ type ( ) // INPUT -// Request Types +// Request Types. type ( RedirectionRequest struct { XMLName xml.Name `xml:"h:AMT_RedirectionService"` @@ -98,12 +98,12 @@ type ( // // ValueMap={0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11..32767, 32768, 32769, 32770, 32771, 32772..65535} // -// Values={Unknown, Other, Enabled, Disabled, Shutting Down, Not Applicable, Enabled but Offline, In Test, Deferred, Quiesce, Starting, DMTF Reserved, IDER and SOL are disabled, IDER is enabled and SOL is disabled, SOL is enabled and IDER is disabled, IDER and SOL are enabled, Vendor Reserved} +// Values={Unknown, Other, Enabled, Disabled, Shutting Down, Not Applicable, Enabled but Offline, In Test, Deferred, Quiesce, Starting, DMTF Reserved, IDER and SOL are disabled, IDER is enabled and SOL is disabled, SOL is enabled and IDER is disabled, IDER and SOL are enabled, Vendor Reserved}. type EnabledState int // The state requested for the element. The only valid values that should be used when requesting a state change to redirection are: 32768, 32769, 32770, and 32771. // // ValueMap={32768, 32769, 32770, 32771} // -// Values={disable IDER and SOL, enable IDER and disable SOL, enable SOL and disable IDER, enable IDER and SOL} +// Values={disable IDER and SOL, enable IDER and disable SOL, enable SOL and disable IDER, enable IDER and SOL}. type RequestedState int diff --git a/pkg/wsman/amt/remoteaccess/decoder.go b/pkg/wsman/amt/remoteaccess/decoder.go index 0874ed03..4d528608 100644 --- a/pkg/wsman/amt/remoteaccess/decoder.go +++ b/pkg/wsman/amt/remoteaccess/decoder.go @@ -8,11 +8,12 @@ package remoteaccess // INPUTS constants const ( - AMT_RemoteAccessPolicyAppliesToMPS string = "AMT_RemoteAccessPolicyAppliesToMPS" - AMT_RemoteAccessPolicyRule string = "AMT_RemoteAccessPolicyRule" - AMT_RemoteAccessService string = "AMT_RemoteAccessService" - AddMps string = "AddMpServer" - AddRemoteAccessPolicyRule string = "AddRemoteAccessPolicyRule" + AMTRemoteAccessPolicyAppliesToMPS string = "AMT_RemoteAccessPolicyAppliesToMPS" + AMTRemoteAccessPolicyRule string = "AMT_RemoteAccessPolicyRule" + AMTRemoteAccessService string = "AMT_RemoteAccessService" + AddMps string = "AddMpServer" + AddRemoteAccessPolicyRule string = "AddRemoteAccessPolicyRule" + ValueNotFound string = "Value not found in map" ) const ( @@ -45,7 +46,7 @@ const ( TriggerHomeProvisioning ) -// triggerToString is a map of trigger values to their string representation +// triggerToString is a map of trigger values to their string representation. var triggerToString = map[Trigger]string{ TriggerUserInitiated: "UserInitiated", TriggerAlert: "Alert", @@ -53,12 +54,13 @@ var triggerToString = map[Trigger]string{ TriggerHomeProvisioning: "HomeProvisioning", } -// String returns the string representation of the Trigger value +// String returns the string representation of the Trigger value. func (t Trigger) String() string { if value, exists := triggerToString[t]; exists { return value } - return "Value not found in map" + + return ValueNotFound } const ( @@ -67,19 +69,20 @@ const ( BothMPS ) -// mpsTypeToString is a map of MPSType values to their string representation +// mpsTypeToString is a map of MPSType values to their string representation. var mpsTypeToString = map[MPSType]string{ ExternalMPS: "ExternalMPS", InternalMPS: "InternalMPS", BothMPS: "BothMPS", } -// String returns the string representation of the MPSType value +// String returns the string representation of the MPSType value. func (m MPSType) String() string { if value, exists := mpsTypeToString[m]; exists { return value } - return "Value not found in map" + + return ValueNotFound } const ( @@ -92,7 +95,7 @@ const ( ReturnValueDuplicate ReturnValue = 2058 ) -// returnValueToString is a map of ReturnValue values to their string representation +// returnValueToString is a map of ReturnValue values to their string representation. var returnValueToString = map[ReturnValue]string{ ReturnValueSuccess: "Success", ReturnValueInternalError: "InternalError", @@ -103,10 +106,11 @@ var returnValueToString = map[ReturnValue]string{ ReturnValueDuplicate: "Duplicate", } -// String returns the string representation of the ReturnValue value +// String returns the string representation of the ReturnValue value. func (r ReturnValue) String() string { if value, exists := returnValueToString[r]; exists { return value } - return "Value not found in map" + + return ValueNotFound } diff --git a/pkg/wsman/amt/remoteaccess/marshal.go b/pkg/wsman/amt/remoteaccess/marshal.go index 6f7b4505..d3633253 100644 --- a/pkg/wsman/amt/remoteaccess/marshal.go +++ b/pkg/wsman/amt/remoteaccess/marshal.go @@ -11,20 +11,22 @@ import ( "gopkg.in/yaml.v3" ) -// JSON marshals the type into JSON format +// JSON marshals the type into JSON format. func (r *Response) JSON() string { jsonOutput, err := json.Marshal(r.Body) if err != nil { return "" } + return string(jsonOutput) } -// YAML marshals the type into YAML format +// YAML marshals the type into YAML format. func (r *Response) YAML() string { yamlOutput, err := yaml.Marshal(r.Body) if err != nil { return "" } + return string(yamlOutput) } diff --git a/pkg/wsman/amt/remoteaccess/policyappliestomps.go b/pkg/wsman/amt/remoteaccess/policyappliestomps.go index 5e2f79c1..6b328ad3 100644 --- a/pkg/wsman/amt/remoteaccess/policyappliestomps.go +++ b/pkg/wsman/amt/remoteaccess/policyappliestomps.go @@ -26,14 +26,14 @@ import ( "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/client" ) -// NewRemoteAccessPolicyAppliesToMPSWithClient instantiates a new PolicyAppliesToMPS +// NewRemoteAccessPolicyAppliesToMPSWithClient instantiates a new PolicyAppliesToMPS. func NewRemoteAccessPolicyAppliesToMPSWithClient(wsmanMessageCreator *message.WSManMessageCreator, client client.WSMan) PolicyAppliesToMPS { return PolicyAppliesToMPS{ - base: message.NewBaseWithClient(wsmanMessageCreator, AMT_RemoteAccessPolicyAppliesToMPS, client), + base: message.NewBaseWithClient(wsmanMessageCreator, AMTRemoteAccessPolicyAppliesToMPS, client), } } -// Get retrieves the representation of the instance +// Get retrieves the representation of the instance. func (policyAppliesToMPS PolicyAppliesToMPS) Get() (response Response, err error) { response = Response{ Message: &client.Message{ @@ -51,10 +51,11 @@ func (policyAppliesToMPS PolicyAppliesToMPS) Get() (response Response, err error if err != nil { return } + return } -// Enumerate returns an enumeration context which is used in a subsequent Pull call +// Enumerate returns an enumeration context which is used in a subsequent Pull call. func (policyAppliesToMPS PolicyAppliesToMPS) Enumerate() (response Response, err error) { response = Response{ Message: &client.Message{ @@ -98,7 +99,7 @@ func (policyAppliesToMPS PolicyAppliesToMPS) Pull(enumerationContext string) (re return } -// Put will change properties of the selected instance +// Put will change properties of the selected instance. func (policyAppliesToMPS PolicyAppliesToMPS) Put(remoteAccessPolicyAppliesToMPS *RemoteAccessPolicyAppliesToMPSRequest) (response Response, err error) { response = Response{ Message: &client.Message{ @@ -120,7 +121,7 @@ func (policyAppliesToMPS PolicyAppliesToMPS) Put(remoteAccessPolicyAppliesToMPS return } -// Delete removes a the specified instance +// Delete removes a the specified instance. func (policyAppliesToMPS PolicyAppliesToMPS) Delete(handle string) (response Response, err error) { selector := message.Selector{Name: "Name", Value: handle} response = Response{ diff --git a/pkg/wsman/amt/remoteaccess/policyappliestomps_test.go b/pkg/wsman/amt/remoteaccess/policyappliestomps_test.go index f7a531e1..ef7d4c34 100644 --- a/pkg/wsman/amt/remoteaccess/policyappliestomps_test.go +++ b/pkg/wsman/amt/remoteaccess/policyappliestomps_test.go @@ -9,11 +9,10 @@ import ( "encoding/xml" "testing" - "github.com/stretchr/testify/assert" - "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/internal/message" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/common" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/wsmantesting" + "github.com/stretchr/testify/assert" ) const ( @@ -27,7 +26,7 @@ func TestJson(t *testing.T) { RemoteAccessPolicyAppliesToMPSGetResponse: RemoteAccessPolicyAppliesToMPSResponse{}, }, } - expectedResult := "{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"RemoteAccessServiceGetResponse\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"CreationClassName\":\"\",\"ElementName\":\"\",\"Name\":\"\",\"SystemCreationClassName\":\"\",\"SystemName\":\"\",\"IsRemoteTunnelConnected\":false,\"RemoteTunnelKeepAliveTimeout\":0},\"RemoteAccessPolicyRuleGetResponse\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"CreationClassName\":\"\",\"ElementName\":\"\",\"ExtendedData\":\"\",\"PolicyRuleName\":\"\",\"SystemCreationClassName\":\"\",\"SystemName\":\"\",\"Trigger\":0,\"TunnelLifeTime\":0},\"RemoteAccessPolicyAppliesToMPSGetResponse\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"ManagedElement\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"Address\":\"\",\"ReferenceParameters\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"ResourceURI\":\"\",\"SelectorSet\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"Selectors\":null}}},\"MpsType\":0,\"OrderOfAccess\":0,\"PolicySet\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"Address\":\"\",\"ReferenceParameters\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"ResourceURI\":\"\",\"SelectorSet\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"Selectors\":null}}}},\"EnumerateResponse\":{\"EnumerationContext\":\"\"},\"PullResponse\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"RemoteAccessItems\":null,\"RemotePolicyRuleItems\":null,\"PolicyAppliesItems\":null},\"AddMpServerResponse\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"MpServer\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"Address\":\"\",\"ReferenceParameters\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"ResourceURI\":\"\",\"SelectorSet\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"Selectors\":null}}},\"ReturnValue\":0},\"AddRemotePolicyRuleResponse\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"PolicyRuleResponse\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"Address\":\"\",\"ReferenceParameters\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"ResourceURI\":\"\",\"SelectorSet\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"Selectors\":null}}},\"ReturnValue\":0}}" + expectedResult := "{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"RemoteAccessServiceGetResponse\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"CreationClassName\":\"\",\"ElementName\":\"\",\"Name\":\"\",\"SystemCreationClassName\":\"\",\"SystemName\":\"\",\"IsRemoteTunnelConnected\":false,\"RemoteTunnelKeepAliveTimeout\":0},\"RemoteAccessPolicyRuleGetResponse\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"CreationClassName\":\"\",\"ElementName\":\"\",\"ExtendedData\":\"\",\"PolicyRuleName\":\"\",\"SystemCreationClassName\":\"\",\"SystemName\":\"\",\"Trigger\":0,\"TunnelLifeTime\":0},\"RemoteAccessPolicyAppliesToMPSGetResponse\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"ManagedElement\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"Address\":\"\",\"ReferenceParameters\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"ResourceURI\":\"\",\"SelectorSet\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"Selectors\":null}}},\"MpsType\":0,\"OrderOfAccess\":0,\"PolicySet\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"Address\":\"\",\"ReferenceParameters\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"ResourceURI\":\"\",\"SelectorSet\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"Selectors\":null}}}},\"EnumerateResponse\":{\"EnumerationContext\":\"\"},\"PullResponse\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"RemoteAccessItems\":null,\"RemotePolicyRuleItems\":null,\"PolicyAppliesItems\":null},\"AddMpServerResponse\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"MpServer\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"Address\":\"\",\"ReferenceParameters\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"ResourceURI\":\"\",\"SelectorSet\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"Selectors\":null}}},\"ReturnValue\":0},\"AddRemotePolicyRuleResponse\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"PolicyRuleInstance\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"Address\":\"\",\"ReferenceParameters\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"ResourceURI\":\"\",\"SelectorSet\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"Selectors\":null}}},\"ReturnValue\":0}}" result := response.JSON() assert.Equal(t, expectedResult, result) } @@ -38,19 +37,20 @@ func TestYaml(t *testing.T) { RemoteAccessPolicyAppliesToMPSGetResponse: RemoteAccessPolicyAppliesToMPSResponse{}, }, } - expectedResult := "xmlname:\n space: \"\"\n local: \"\"\nremoteaccessservicegetresponse:\n xmlname:\n space: \"\"\n local: \"\"\n creationclassname: \"\"\n elementname: \"\"\n name: \"\"\n systemcreationclassname: \"\"\n systemname: \"\"\n isremotetunnelconnected: false\n remotetunnelkeepalivetimeout: 0\nremoteaccesspolicyrulegetresponse:\n xmlname:\n space: \"\"\n local: \"\"\n creationclassname: \"\"\n elementname: \"\"\n extendeddata: \"\"\n policyrulename: \"\"\n systemcreationclassname: \"\"\n systemname: \"\"\n trigger: 0\n tunnellifetime: 0\nremoteaccesspolicyappliestompsgetresponse:\n xmlname:\n space: \"\"\n local: \"\"\n managedelement:\n xmlname:\n space: \"\"\n local: \"\"\n address: \"\"\n referenceparameters:\n xmlname:\n space: \"\"\n local: \"\"\n resourceuri: \"\"\n selectorset:\n xmlname:\n space: \"\"\n local: \"\"\n selectors: []\n mpstype: 0\n orderofaccess: 0\n policyset:\n xmlname:\n space: \"\"\n local: \"\"\n address: \"\"\n referenceparameters:\n xmlname:\n space: \"\"\n local: \"\"\n resourceuri: \"\"\n selectorset:\n xmlname:\n space: \"\"\n local: \"\"\n selectors: []\nenumerateresponse:\n enumerationcontext: \"\"\npullresponse:\n xmlname:\n space: \"\"\n local: \"\"\n remoteaccessitems: []\n remotepolicyruleitems: []\n policyappliesitems: []\naddmpserverresponse:\n xmlname:\n space: \"\"\n local: \"\"\n mpserver:\n xmlname:\n space: \"\"\n local: \"\"\n address: \"\"\n referenceparameters:\n xmlname:\n space: \"\"\n local: \"\"\n resourceuri: \"\"\n selectorset:\n xmlname:\n space: \"\"\n local: \"\"\n selectors: []\n returnvalue: 0\naddremotepolicyruleresponse:\n xmlname:\n space: \"\"\n local: \"\"\n policyruleresponse:\n xmlname:\n space: \"\"\n local: \"\"\n address: \"\"\n referenceparameters:\n xmlname:\n space: \"\"\n local: \"\"\n resourceuri: \"\"\n selectorset:\n xmlname:\n space: \"\"\n local: \"\"\n selectors: []\n returnvalue: 0\n" + expectedResult := "xmlname:\n space: \"\"\n local: \"\"\nremoteaccessservicegetresponse:\n xmlname:\n space: \"\"\n local: \"\"\n creationclassname: \"\"\n elementname: \"\"\n name: \"\"\n systemcreationclassname: \"\"\n systemname: \"\"\n isremotetunnelconnected: false\n remotetunnelkeepalivetimeout: 0\nremoteaccesspolicyrulegetresponse:\n xmlname:\n space: \"\"\n local: \"\"\n creationclassname: \"\"\n elementname: \"\"\n extendeddata: \"\"\n policyrulename: \"\"\n systemcreationclassname: \"\"\n systemname: \"\"\n trigger: 0\n tunnellifetime: 0\nremoteaccesspolicyappliestompsgetresponse:\n xmlname:\n space: \"\"\n local: \"\"\n managedelement:\n xmlname:\n space: \"\"\n local: \"\"\n address: \"\"\n referenceparameters:\n xmlname:\n space: \"\"\n local: \"\"\n resourceuri: \"\"\n selectorset:\n xmlname:\n space: \"\"\n local: \"\"\n selectors: []\n mpstype: 0\n orderofaccess: 0\n policyset:\n xmlname:\n space: \"\"\n local: \"\"\n address: \"\"\n referenceparameters:\n xmlname:\n space: \"\"\n local: \"\"\n resourceuri: \"\"\n selectorset:\n xmlname:\n space: \"\"\n local: \"\"\n selectors: []\nenumerateresponse:\n enumerationcontext: \"\"\npullresponse:\n xmlname:\n space: \"\"\n local: \"\"\n remoteaccessitems: []\n remotepolicyruleitems: []\n policyappliesitems: []\naddmpserverresponse:\n xmlname:\n space: \"\"\n local: \"\"\n mpserver:\n xmlname:\n space: \"\"\n local: \"\"\n address: \"\"\n referenceparameters:\n xmlname:\n space: \"\"\n local: \"\"\n resourceuri: \"\"\n selectorset:\n xmlname:\n space: \"\"\n local: \"\"\n selectors: []\n returnvalue: 0\naddremotepolicyruleresponse:\n xmlname:\n space: \"\"\n local: \"\"\n policyruleinstance:\n xmlname:\n space: \"\"\n local: \"\"\n address: \"\"\n referenceparameters:\n xmlname:\n space: \"\"\n local: \"\"\n resourceuri: \"\"\n selectorset:\n xmlname:\n space: \"\"\n local: \"\"\n selectors: []\n returnvalue: 0\n" result := response.YAML() assert.Equal(t, expectedResult, result) } func TestPositiveAMT_RemoteAccessPolicyAppliesToMPS(t *testing.T) { messageID := 0 - resourceUriBase := "http://intel.com/wbem/wscim/1/amt-schema/1/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.AMTResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "amt/remoteaccess/policyappliestomps", } elementUnderTest := NewRemoteAccessPolicyAppliesToMPSWithClient(wsmanMessageCreator, &client) + t.Run("amt_RemoteAccessPolicyAppliesToMPS Tests", func(t *testing.T) { tests := []struct { name string @@ -61,15 +61,16 @@ func TestPositiveAMT_RemoteAccessPolicyAppliesToMPS(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //GETS + // GETS { "should create a valid AMT_RemoteAccessPolicyAppliesToMPS Get wsman message", - AMT_RemoteAccessPolicyAppliesToMPS, - wsmantesting.GET, + AMTRemoteAccessPolicyAppliesToMPS, + wsmantesting.Get, "", "", func() (Response, error) { - client.CurrentMessage = "Get" + client.CurrentMessage = wsmantesting.CurrentMessageGet + return elementUnderTest.Get() }, Body{ @@ -147,15 +148,16 @@ func TestPositiveAMT_RemoteAccessPolicyAppliesToMPS(t *testing.T) { }, }, }, - //ENUMERATES + // ENUMERATES { "should create a valid AMT_RemoteAccessPolicyAppliesToMPS Enumerate wsman message", - AMT_RemoteAccessPolicyAppliesToMPS, - wsmantesting.ENUMERATE, - wsmantesting.ENUMERATE_BODY, + AMTRemoteAccessPolicyAppliesToMPS, + wsmantesting.Enumerate, + wsmantesting.EnumerateBody, "", func() (Response, error) { - client.CurrentMessage = "Enumerate" + client.CurrentMessage = wsmantesting.CurrentMessageEnumerate + return elementUnderTest.Enumerate() }, Body{ @@ -165,15 +167,16 @@ func TestPositiveAMT_RemoteAccessPolicyAppliesToMPS(t *testing.T) { }, }, }, - //PULLS + // PULLS { "should create a valid AMT_RemoteAccessPolicyAppliesToMPS Pull wsman message", - AMT_RemoteAccessPolicyAppliesToMPS, - wsmantesting.PULL, - wsmantesting.PULL_BODY, + AMTRemoteAccessPolicyAppliesToMPS, + wsmantesting.Pull, + wsmantesting.PullBody, "", func() (Response, error) { - client.CurrentMessage = "Pull" + client.CurrentMessage = wsmantesting.CurrentMessagePull + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -258,12 +261,12 @@ func TestPositiveAMT_RemoteAccessPolicyAppliesToMPS(t *testing.T) { }, { "should create a valid AMT_RemoteAccessPolicyAppliesToMPS Put wsman message", - AMT_RemoteAccessPolicyAppliesToMPS, - wsmantesting.PUT, + AMTRemoteAccessPolicyAppliesToMPS, + wsmantesting.Put, `http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymoushttp://intel.com/wbem/wscim/1/amt-schema/1/AMT_ManagementPresenceRemoteSAPAMT_ManagementPresenceRemoteSAPIntel(r) AMT:Management Presence Server 0CIM_ComputerSystemIntel(r) AMT02http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymoushttp://intel.com/wbem/wscim/1/amt-schema/1/AMT_RemoteAccessPolicyRuleAMT_RemoteAccessPolicyRulePeriodicCIM_ComputerSystemIntel(r) AMT`, "", func() (Response, error) { - client.CurrentMessage = "Put" + client.CurrentMessage = wsmantesting.CurrentMessagePut rapatmps := RemoteAccessPolicyAppliesToMPSRequest{ H: "http://intel.com/wbem/wscim/1/amt-schema/1/AMT_RemoteAccessPolicyAppliesToMPS", ManagedElement: ManagedElement{ @@ -325,16 +328,17 @@ func TestPositiveAMT_RemoteAccessPolicyAppliesToMPS(t *testing.T) { }, }, } + return elementUnderTest.Put(&rapatmps) }, Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, }, }, - //{"should create a valid AMT_RemoteAccessPolicyAppliesToMPS Create wsman message", AMT_RemoteAccessPolicyAppliesToMPS, wsmantesting.PULL, wsmantesting.PULL_BODY, "", func() string { return elementUnderTest.Pull(wsmantesting.EnumerationContext) }}, + // {"should create a valid AMT_RemoteAccessPolicyAppliesToMPS Create wsman message", AMT_RemoteAccessPolicyAppliesToMPS, wsmantesting.PULL, wsmantesting.PULL_BODY, "", func() string { return elementUnderTest.Pull(wsmantesting.EnumerationContext) }}, { "should create a valid AMT_RemoteAccessPolicyAppliesToMPS Delete wsman message", - AMT_RemoteAccessPolicyAppliesToMPS, wsmantesting.DELETE, + AMTRemoteAccessPolicyAppliesToMPS, wsmantesting.Delete, "", "Instance", func() (Response, error) { @@ -348,7 +352,7 @@ func TestPositiveAMT_RemoteAccessPolicyAppliesToMPS(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, test.extraHeader, test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, test.extraHeader, test.body) messageID++ response, err := test.responseFunc() assert.NoError(t, err) @@ -358,14 +362,16 @@ func TestPositiveAMT_RemoteAccessPolicyAppliesToMPS(t *testing.T) { } }) } + func TestNegativeAMT_RemoteAccessPolicyAppliesToMPS(t *testing.T) { messageID := 0 - resourceUriBase := "http://intel.com/wbem/wscim/1/amt-schema/1/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.AMTResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "amt/remoteaccess/policyappliestomps", } elementUnderTest := NewRemoteAccessPolicyAppliesToMPSWithClient(wsmanMessageCreator, &client) + t.Run("amt_RemoteAccessPolicyAppliesToMPS Tests", func(t *testing.T) { tests := []struct { name string @@ -376,15 +382,16 @@ func TestNegativeAMT_RemoteAccessPolicyAppliesToMPS(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //GETS + // GETS { "should create a valid AMT_RemoteAccessPolicyAppliesToMPS Get wsman message", - AMT_RemoteAccessPolicyAppliesToMPS, - wsmantesting.GET, + AMTRemoteAccessPolicyAppliesToMPS, + wsmantesting.Get, "", "", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Get() }, Body{ @@ -462,15 +469,16 @@ func TestNegativeAMT_RemoteAccessPolicyAppliesToMPS(t *testing.T) { }, }, }, - //ENUMERATES + // ENUMERATES { "should create a valid AMT_RemoteAccessPolicyAppliesToMPS Enumerate wsman message", - AMT_RemoteAccessPolicyAppliesToMPS, - wsmantesting.ENUMERATE, - wsmantesting.ENUMERATE_BODY, + AMTRemoteAccessPolicyAppliesToMPS, + wsmantesting.Enumerate, + wsmantesting.EnumerateBody, "", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Enumerate() }, Body{ @@ -480,15 +488,16 @@ func TestNegativeAMT_RemoteAccessPolicyAppliesToMPS(t *testing.T) { }, }, }, - //PULLS + // PULLS { "should create a valid AMT_RemoteAccessPolicyAppliesToMPS Pull wsman message", - AMT_RemoteAccessPolicyAppliesToMPS, - wsmantesting.PULL, - wsmantesting.PULL_BODY, + AMTRemoteAccessPolicyAppliesToMPS, + wsmantesting.Pull, + wsmantesting.PullBody, "", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -573,12 +582,12 @@ func TestNegativeAMT_RemoteAccessPolicyAppliesToMPS(t *testing.T) { }, { "should create a valid AMT_RemoteAccessPolicyAppliesToMPS Put wsman message", - AMT_RemoteAccessPolicyAppliesToMPS, - wsmantesting.PUT, + AMTRemoteAccessPolicyAppliesToMPS, + wsmantesting.Put, `http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymoushttp://intel.com/wbem/wscim/1/amt-schema/1/AMT_ManagementPresenceRemoteSAPAMT_ManagementPresenceRemoteSAPIntel(r) AMT:Management Presence Server 0CIM_ComputerSystemIntel(r) AMT02http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymoushttp://intel.com/wbem/wscim/1/amt-schema/1/AMT_RemoteAccessPolicyRuleAMT_RemoteAccessPolicyRulePeriodicCIM_ComputerSystemIntel(r) AMT`, "", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError rapatmps := RemoteAccessPolicyAppliesToMPSRequest{ H: "http://intel.com/wbem/wscim/1/amt-schema/1/AMT_RemoteAccessPolicyAppliesToMPS", ManagedElement: ManagedElement{ @@ -640,20 +649,22 @@ func TestNegativeAMT_RemoteAccessPolicyAppliesToMPS(t *testing.T) { }, }, } + return elementUnderTest.Put(&rapatmps) }, Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, }, }, - //{"should create a valid AMT_RemoteAccessPolicyAppliesToMPS Create wsman message", AMT_RemoteAccessPolicyAppliesToMPS, wsmantesting.PULL, wsmantesting.PULL_BODY, "", func() string { return elementUnderTest.Pull(wsmantesting.EnumerationContext) }}, + // {"should create a valid AMT_RemoteAccessPolicyAppliesToMPS Create wsman message", AMT_RemoteAccessPolicyAppliesToMPS, wsmantesting.PULL, wsmantesting.PULL_BODY, "", func() string { return elementUnderTest.Pull(wsmantesting.EnumerationContext) }}, { "should create a valid AMT_RemoteAccessPolicyAppliesToMPS Delete wsman message", - AMT_RemoteAccessPolicyAppliesToMPS, wsmantesting.DELETE, + AMTRemoteAccessPolicyAppliesToMPS, wsmantesting.Delete, "", "Instance", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Delete("Instance") }, Body{ @@ -664,7 +675,7 @@ func TestNegativeAMT_RemoteAccessPolicyAppliesToMPS(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, test.extraHeader, test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, test.extraHeader, test.body) messageID++ response, err := test.responseFunc() assert.Error(t, err) diff --git a/pkg/wsman/amt/remoteaccess/policyrule.go b/pkg/wsman/amt/remoteaccess/policyrule.go index 1f477541..77f2863f 100644 --- a/pkg/wsman/amt/remoteaccess/policyrule.go +++ b/pkg/wsman/amt/remoteaccess/policyrule.go @@ -13,14 +13,14 @@ import ( "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/client" ) -// NewPolicyRuleWithClient instantiates a new PolicyRule +// NewPolicyRuleWithClient instantiates a new PolicyRule. func NewPolicyRuleWithClient(wsmanMessageCreator *message.WSManMessageCreator, clientPolicy client.WSMan) PolicyRule { return PolicyRule{ - base: message.NewBaseWithClient(wsmanMessageCreator, AMT_RemoteAccessPolicyRule, clientPolicy), + base: message.NewBaseWithClient(wsmanMessageCreator, AMTRemoteAccessPolicyRule, clientPolicy), } } -// Get retrieves the representation of the instance +// Get retrieves the representation of the instance. func (policyRule PolicyRule) Get() (response Response, err error) { response = Response{ Message: &client.Message{ @@ -38,10 +38,11 @@ func (policyRule PolicyRule) Get() (response Response, err error) { if err != nil { return } + return } -// Enumerate returns an enumeration context which is used in a subsequent Pull call +// Enumerate returns an enumeration context which is used in a subsequent Pull call. func (policyRule PolicyRule) Enumerate() (response Response, err error) { response = Response{ Message: &client.Message{ @@ -85,9 +86,9 @@ func (policyRule PolicyRule) Pull(enumerationContext string) (response Response, return } -// Put will change properties of the selected instance +// Put will change properties of the selected instance. func (policyRule PolicyRule) Put(remoteAccessPolicyRule RemoteAccessPolicyRuleRequest) (response Response, err error) { - remoteAccessPolicyRule.H = fmt.Sprintf("%s%s", message.AMTSchema, AMT_RemoteAccessPolicyRule) + remoteAccessPolicyRule.H = fmt.Sprintf("%s%s", message.AMTSchema, AMTRemoteAccessPolicyRule) response = Response{ Message: &client.Message{ XMLInput: policyRule.base.Put(remoteAccessPolicyRule, false, nil), @@ -103,10 +104,11 @@ func (policyRule PolicyRule) Put(remoteAccessPolicyRule RemoteAccessPolicyRuleRe if err != nil { return } + return } -// Delete removes a the specified instance +// Delete removes a the specified instance. func (policyRule PolicyRule) Delete(handle string) (response Response, err error) { selector := message.Selector{Name: "PolicyRuleName", Value: handle} response = Response{ @@ -124,5 +126,6 @@ func (policyRule PolicyRule) Delete(handle string) (response Response, err error if err != nil { return } + return } diff --git a/pkg/wsman/amt/remoteaccess/policyrule_test.go b/pkg/wsman/amt/remoteaccess/policyrule_test.go index 00f35958..72112027 100644 --- a/pkg/wsman/amt/remoteaccess/policyrule_test.go +++ b/pkg/wsman/amt/remoteaccess/policyrule_test.go @@ -9,11 +9,10 @@ import ( "encoding/xml" "testing" - "github.com/stretchr/testify/assert" - "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/internal/message" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/common" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/wsmantesting" + "github.com/stretchr/testify/assert" ) const ( @@ -23,12 +22,13 @@ const ( func TestPositiveAMT_RemoteAccessPolicyRule(t *testing.T) { messageID := 0 - resourceUriBase := "http://intel.com/wbem/wscim/1/amt-schema/1/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.AMTResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "amt/remoteaccess/policyrule", } elementUnderTest := NewPolicyRuleWithClient(wsmanMessageCreator, &client) + t.Run("amt_* Tests", func(t *testing.T) { tests := []struct { name string @@ -39,22 +39,23 @@ func TestPositiveAMT_RemoteAccessPolicyRule(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //GETS + // GETS { "should create a valid AMT_RemoteAccessPolicyRule Get wsman message", - AMT_RemoteAccessPolicyRule, - wsmantesting.GET, + AMTRemoteAccessPolicyRule, + wsmantesting.Get, "", "", func() (Response, error) { - client.CurrentMessage = "Get" + client.CurrentMessage = wsmantesting.CurrentMessageGet + return elementUnderTest.Get() }, Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, RemoteAccessPolicyRuleGetResponse: RemoteAccessPolicyRuleResponse{ XMLName: xml.Name{Space: "http://intel.com/wbem/wscim/1/amt-schema/1/AMT_RemoteAccessPolicyRule", Local: "AMT_RemoteAccessPolicyRule"}, - CreationClassName: AMT_RemoteAccessPolicyRule, + CreationClassName: AMTRemoteAccessPolicyRule, ElementName: "Inte(r) AMT:Remote Access Policy", ExtendedData: "AAAAAAAAABk=", PolicyRuleName: "Periodic", @@ -65,15 +66,16 @@ func TestPositiveAMT_RemoteAccessPolicyRule(t *testing.T) { }, }, }, - //ENUMERATES + // ENUMERATES { "should create a valid AMT_RemoteAccessPolicyRule Enumerate wsman message", - AMT_RemoteAccessPolicyRule, - wsmantesting.ENUMERATE, - wsmantesting.ENUMERATE_BODY, + AMTRemoteAccessPolicyRule, + wsmantesting.Enumerate, + wsmantesting.EnumerateBody, "", func() (Response, error) { - client.CurrentMessage = "Enumerate" + client.CurrentMessage = wsmantesting.CurrentMessageEnumerate + return elementUnderTest.Enumerate() }, Body{ @@ -83,15 +85,16 @@ func TestPositiveAMT_RemoteAccessPolicyRule(t *testing.T) { }, }, }, - //PULLS + // PULLS { "should create a valid AMT_RemoteAccessPolicyRule Pull wsman message", - AMT_RemoteAccessPolicyRule, - wsmantesting.PULL, - wsmantesting.PULL_BODY, + AMTRemoteAccessPolicyRule, + wsmantesting.Pull, + wsmantesting.PullBody, "", func() (Response, error) { - client.CurrentMessage = "Pull" + client.CurrentMessage = wsmantesting.CurrentMessagePull + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -115,15 +118,16 @@ func TestPositiveAMT_RemoteAccessPolicyRule(t *testing.T) { }, }, - //DELETE + // DELETE { "should create a valid AMT_RemoteAccessPolicyRule Delete wsman message", - AMT_RemoteAccessPolicyRule, - wsmantesting.DELETE, + AMTRemoteAccessPolicyRule, + wsmantesting.Delete, "", "Instance", func() (Response, error) { - client.CurrentMessage = "Delete" + client.CurrentMessage = wsmantesting.CurrentMessageDelete + return elementUnderTest.Delete("Instance") }, Body{ @@ -134,7 +138,7 @@ func TestPositiveAMT_RemoteAccessPolicyRule(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, test.extraHeader, test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, test.extraHeader, test.body) messageID++ response, err := test.responseFunc() assert.NoError(t, err) @@ -144,14 +148,16 @@ func TestPositiveAMT_RemoteAccessPolicyRule(t *testing.T) { } }) } + func TestNegativeAMT_RemoteAccessPolicyRule(t *testing.T) { messageID := 0 - resourceUriBase := "http://intel.com/wbem/wscim/1/amt-schema/1/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.AMTResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "amt/remoteaccess/policyrule", } elementUnderTest := NewPolicyRuleWithClient(wsmanMessageCreator, &client) + t.Run("amt_* Tests", func(t *testing.T) { tests := []struct { name string @@ -162,22 +168,23 @@ func TestNegativeAMT_RemoteAccessPolicyRule(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //GETS + // GETS { "should create a valid AMT_RemoteAccessPolicyRule Get wsman message", - AMT_RemoteAccessPolicyRule, - wsmantesting.GET, + AMTRemoteAccessPolicyRule, + wsmantesting.Get, "", "", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Get() }, Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, RemoteAccessPolicyRuleGetResponse: RemoteAccessPolicyRuleResponse{ XMLName: xml.Name{Space: "http://intel.com/wbem/wscim/1/amt-schema/1/AMT_RemoteAccessPolicyRule", Local: "AMT_RemoteAccessPolicyRule"}, - CreationClassName: AMT_RemoteAccessPolicyRule, + CreationClassName: AMTRemoteAccessPolicyRule, ElementName: "Inte(r) AMT:Remote Access Policy", ExtendedData: "AAAAAAAAABk=", PolicyRuleName: "Periodic", @@ -188,15 +195,16 @@ func TestNegativeAMT_RemoteAccessPolicyRule(t *testing.T) { }, }, }, - //ENUMERATES + // ENUMERATES { "should create a valid AMT_RemoteAccessPolicyRule Enumerate wsman message", - AMT_RemoteAccessPolicyRule, - wsmantesting.ENUMERATE, - wsmantesting.ENUMERATE_BODY, + AMTRemoteAccessPolicyRule, + wsmantesting.Enumerate, + wsmantesting.EnumerateBody, "", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Enumerate() }, Body{ @@ -206,15 +214,16 @@ func TestNegativeAMT_RemoteAccessPolicyRule(t *testing.T) { }, }, }, - //PULLS + // PULLS { "should create a valid AMT_RemoteAccessPolicyRule Pull wsman message", - AMT_RemoteAccessPolicyRule, - wsmantesting.PULL, - wsmantesting.PULL_BODY, + AMTRemoteAccessPolicyRule, + wsmantesting.Pull, + wsmantesting.PullBody, "", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -238,15 +247,16 @@ func TestNegativeAMT_RemoteAccessPolicyRule(t *testing.T) { }, }, - //DELETE + // DELETE { "should create a valid AMT_RemoteAccessPolicyRule Delete wsman message", - AMT_RemoteAccessPolicyRule, - wsmantesting.DELETE, + AMTRemoteAccessPolicyRule, + wsmantesting.Delete, "", "Instance", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Delete("Instance") }, Body{ @@ -257,7 +267,7 @@ func TestNegativeAMT_RemoteAccessPolicyRule(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, test.extraHeader, test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, test.extraHeader, test.body) messageID++ response, err := test.responseFunc() assert.Error(t, err) diff --git a/pkg/wsman/amt/remoteaccess/service.go b/pkg/wsman/amt/remoteaccess/service.go index 29785541..11171cc7 100644 --- a/pkg/wsman/amt/remoteaccess/service.go +++ b/pkg/wsman/amt/remoteaccess/service.go @@ -14,14 +14,14 @@ import ( "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/client" ) -// NewRemoteAccessServiceWithClient instantiates a new Service +// NewRemoteAccessServiceWithClient instantiates a new Service. func NewRemoteAccessServiceWithClient(wsmanMessageCreator *message.WSManMessageCreator, client client.WSMan) Service { return Service{ - base: message.NewBaseWithClient(wsmanMessageCreator, AMT_RemoteAccessService, client), + base: message.NewBaseWithClient(wsmanMessageCreator, AMTRemoteAccessService, client), } } -// Get retrieves the representation of the instance +// Get retrieves the representation of the instance. func (service Service) Get() (response Response, err error) { response = Response{ Message: &client.Message{ @@ -39,10 +39,11 @@ func (service Service) Get() (response Response, err error) { if err != nil { return } + return } -// Enumerate returns an enumeration context which is used in a subsequent Pull call +// Enumerate returns an enumeration context which is used in a subsequent Pull call. func (service Service) Enumerate() (response Response, err error) { response = Response{ Message: &client.Message{ @@ -91,25 +92,30 @@ func (service Service) Pull(enumerationContext string) (response Response, err e // This credential may be an existing AMT_PublicKeyCertificate instance (if the created MPS is configured to use mutual authentication). // If the created MpServer is configured to use username password authentication, an AMT_MPSUsernamePassword instance is created and used as the associated credential. func (service Service) AddMPS(mpServer AddMpServerRequest) (response Response, err error) { - mpServer.H = fmt.Sprintf("%s%s", message.AMTSchema, AMT_RemoteAccessService) - header := service.base.WSManMessageCreator.CreateHeader(methods.GenerateAction(AMT_RemoteAccessService, AddMps), AMT_RemoteAccessService, nil, "", "") - body := service.base.WSManMessageCreator.CreateBody(methods.GenerateInputMethod(AddMps), AMT_RemoteAccessService, mpServer) - // body := fmt.Sprintf(`%s%d%d%d%s%s%s`, service.base.WSManMessageCreator.ResourceURIBase, AMT_RemoteAccessService, mpServer.AccessInfo, mpServer.InfoFormat, mpServer.Port, mpServer.AuthMethod, mpServer.Username, mpServer.Password, mpServer.CommonName) + mpServer.H = fmt.Sprintf("%s%s", message.AMTSchema, AMTRemoteAccessService) + + header := service.base.WSManMessageCreator.CreateHeader(methods.GenerateAction(AMTRemoteAccessService, AddMps), AMTRemoteAccessService, nil, "", "") + + body := service.base.WSManMessageCreator.CreateBody(methods.GenerateInputMethod(AddMps), AMTRemoteAccessService, mpServer) + response = Response{ Message: &client.Message{ XMLInput: service.base.WSManMessageCreator.CreateXML(header, body), }, } - // send the message to AMT + + // send the message to AMT. err = service.base.Execute(response.Message) if err != nil { return } - // put the xml response into the go struct + + // put the xml response into the go struct. err = xml.Unmarshal([]byte(response.XMLOutput), &response) if err != nil { return } + return } @@ -122,29 +128,35 @@ func (service Service) AddRemoteAccessPolicyRule(remoteAccessPolicyRule RemoteAc Name: "Name", Value: name, } - header := service.base.WSManMessageCreator.CreateHeader(methods.GenerateAction(AMT_RemoteAccessService, AddRemoteAccessPolicyRule), AMT_RemoteAccessService, nil, "", "") - body := fmt.Sprintf(`%d%d%s
http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous
%s%s%s
`, - service.base.WSManMessageCreator.ResourceURIBase, - AMT_RemoteAccessService, + addRemotePolicyRuleNamespace := service.base.WSManMessageCreator.ResourceURIBase + AMTRemoteAccessService + + header := service.base.WSManMessageCreator.CreateHeader(methods.GenerateAction(AMTRemoteAccessService, AddRemoteAccessPolicyRule), AMTRemoteAccessService, nil, "", "") + + body := fmt.Sprintf(`%d%d%s
http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous
%s%s%s
`, + addRemotePolicyRuleNamespace, remoteAccessPolicyRule.Trigger, remoteAccessPolicyRule.TunnelLifeTime, remoteAccessPolicyRule.ExtendedData, service.base.WSManMessageCreator.ResourceURIBase, "AMT_ManagementPresenceRemoteSAP", selector.Name, selector.Value) + response = Response{ Message: &client.Message{ XMLInput: service.base.WSManMessageCreator.CreateXML(header, body), }, } + // send the message to AMT err = service.base.Execute(response.Message) if err != nil { - return + return response, err } + // put the xml response into the go struct err = xml.Unmarshal([]byte(response.XMLOutput), &response) if err != nil { - return + return response, err } - return + + return response, nil } diff --git a/pkg/wsman/amt/remoteaccess/service_test.go b/pkg/wsman/amt/remoteaccess/service_test.go index 82f37848..8e665152 100644 --- a/pkg/wsman/amt/remoteaccess/service_test.go +++ b/pkg/wsman/amt/remoteaccess/service_test.go @@ -10,12 +10,12 @@ import ( "fmt" "testing" - "github.com/stretchr/testify/assert" - "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/internal/message" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/amt/methods" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/common" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/wsmantesting" + "github.com/sirupsen/logrus" + "github.com/stretchr/testify/assert" ) const ( @@ -25,12 +25,13 @@ const ( func TestPositiveAMT_RemoteAccessService(t *testing.T) { messageID := 0 - resourceUriBase := "http://intel.com/wbem/wscim/1/amt-schema/1/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.AMTResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "amt/remoteaccess/service", } elementUnderTest := NewRemoteAccessServiceWithClient(wsmanMessageCreator, &client) + t.Run("amt_RemoteAccessService Tests", func(t *testing.T) { tests := []struct { name string @@ -40,14 +41,15 @@ func TestPositiveAMT_RemoteAccessService(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //GETS + // GETS { "should create a valid AMT_RemoteAccessService Get wsman message", - AMT_RemoteAccessService, - wsmantesting.GET, + AMTRemoteAccessService, + wsmantesting.Get, "", func() (Response, error) { - client.CurrentMessage = "Get" + client.CurrentMessage = wsmantesting.CurrentMessageGet + return elementUnderTest.Get() }, Body{ @@ -62,17 +64,18 @@ func TestPositiveAMT_RemoteAccessService(t *testing.T) { }, }, }, - //ENUMERATES + // ENUMERATES { "should create a valid AMT_RemoteAccessService Enumerate wsman message", - AMT_RemoteAccessService, - wsmantesting.ENUMERATE, - wsmantesting.ENUMERATE_BODY, + AMTRemoteAccessService, + wsmantesting.Enumerate, + wsmantesting.EnumerateBody, func() (Response, error) { - client.CurrentMessage = "Enumerate" + client.CurrentMessage = wsmantesting.CurrentMessageEnumerate if elementUnderTest.base.WSManMessageCreator == nil { - print("Error") + logrus.Print("Error") } + return elementUnderTest.Enumerate() }, Body{ @@ -82,14 +85,15 @@ func TestPositiveAMT_RemoteAccessService(t *testing.T) { }, }, }, - //PULLS + // PULLS { "should create a valid AMT_RemoteAccessService Pull wsman message", - AMT_RemoteAccessService, - wsmantesting.PULL, - wsmantesting.PULL_BODY, + AMTRemoteAccessService, + wsmantesting.Pull, + wsmantesting.PullBody, func() (Response, error) { - client.CurrentMessage = "Pull" + client.CurrentMessage = wsmantesting.CurrentMessagePull + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -109,12 +113,12 @@ func TestPositiveAMT_RemoteAccessService(t *testing.T) { }, }, }, - //AddMPS + // AddMPS { "should create a valid AMT_RemoteAccessService AddMPS wsman message", - AMT_RemoteAccessService, - methods.GenerateAction(AMT_RemoteAccessService, AddMps), - fmt.Sprintf(`%s%d%d%d%s%s%s`, resourceUriBase, AMT_RemoteAccessService, "AccessInfo", 1, 2, 3, "Username", "Password", "CommonName"), + AMTRemoteAccessService, + methods.GenerateAction(AMTRemoteAccessService, AddMps), + fmt.Sprintf(`%s%d%d%d%s%s%s`, resourceURIBase, AMTRemoteAccessService, "AccessInfo", 1, 2, 3, "Username", "Password", "CommonName"), func() (Response, error) { client.CurrentMessage = "AddMPSServer" mpsServer := AddMpServerRequest{ @@ -127,6 +131,7 @@ func TestPositiveAMT_RemoteAccessService(t *testing.T) { Password: "Password", CommonName: "CommonName", } + return elementUnderTest.AddMPS(mpsServer) }, Body{ @@ -169,12 +174,12 @@ func TestPositiveAMT_RemoteAccessService(t *testing.T) { }, }, }, - //AddRemoteAccessPolicyRule + // AddRemoteAccessPolicyRule { "should create a valid AMT_RemoteAccessPolicyRule wsman message", - AMT_RemoteAccessService, - methods.GenerateAction(AMT_RemoteAccessService, AddRemoteAccessPolicyRule), - fmt.Sprintf(`%d%d%s
http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous
%s%strue
`, resourceUriBase, AMT_RemoteAccessService, 2, 0, "0300", "http://intel.com/wbem/wscim/1/amt-schema/1/", "AMT_ManagementPresenceRemoteSAP"), + AMTRemoteAccessService, + methods.GenerateAction(AMTRemoteAccessService, AddRemoteAccessPolicyRule), + fmt.Sprintf(`%d%d%s
http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous
%s%strue
`, resourceURIBase, AMTRemoteAccessService, 2, 0, "0300", "http://intel.com/wbem/wscim/1/amt-schema/1/", "AMT_ManagementPresenceRemoteSAP"), func() (Response, error) { client.CurrentMessage = "AddRemoteAccessService" remoteAccessPolicyRule := RemoteAccessPolicyRuleRequest{ @@ -183,6 +188,7 @@ func TestPositiveAMT_RemoteAccessService(t *testing.T) { TunnelLifeTime: 0, ExtendedData: "0300", } + return elementUnderTest.AddRemoteAccessPolicyRule(remoteAccessPolicyRule, "true") }, Body{ @@ -229,10 +235,10 @@ func TestPositiveAMT_RemoteAccessService(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, "", test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, "", test.body) messageID++ response, err := test.responseFunc() - println(response.XMLOutput) + logrus.Print(response.XMLOutput) assert.NoError(t, err) assert.Equal(t, expectedXMLInput, response.XMLInput) assert.Equal(t, test.expectedResponse, response.Body) @@ -240,14 +246,16 @@ func TestPositiveAMT_RemoteAccessService(t *testing.T) { } }) } + func TestNegativeAMT_RemoteAccessService(t *testing.T) { messageID := 0 - resourceUriBase := "http://intel.com/wbem/wscim/1/amt-schema/1/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.AMTResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "amt/remoteaccess/service", } elementUnderTest := NewRemoteAccessServiceWithClient(wsmanMessageCreator, &client) + t.Run("amt_RemoteAccessService Tests", func(t *testing.T) { tests := []struct { name string @@ -257,14 +265,15 @@ func TestNegativeAMT_RemoteAccessService(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //GETS + // GETS { "should create a valid AMT_RemoteAccessService Get wsman message", - AMT_RemoteAccessService, - wsmantesting.GET, + AMTRemoteAccessService, + wsmantesting.Get, "", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Get() }, Body{ @@ -279,17 +288,18 @@ func TestNegativeAMT_RemoteAccessService(t *testing.T) { }, }, }, - //ENUMERATES + // ENUMERATES { "should create a valid AMT_RemoteAccessService Enumerate wsman message", - AMT_RemoteAccessService, - wsmantesting.ENUMERATE, - wsmantesting.ENUMERATE_BODY, + AMTRemoteAccessService, + wsmantesting.Enumerate, + wsmantesting.EnumerateBody, func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError if elementUnderTest.base.WSManMessageCreator == nil { - print("Error") + logrus.Print("Error") } + return elementUnderTest.Enumerate() }, Body{ @@ -299,14 +309,15 @@ func TestNegativeAMT_RemoteAccessService(t *testing.T) { }, }, }, - //PULLS + // PULLS { "should create a valid AMT_RemoteAccessService Pull wsman message", - AMT_RemoteAccessService, - wsmantesting.PULL, - wsmantesting.PULL_BODY, + AMTRemoteAccessService, + wsmantesting.Pull, + wsmantesting.PullBody, func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -326,14 +337,14 @@ func TestNegativeAMT_RemoteAccessService(t *testing.T) { }, }, }, - //AddMPS + // AddMPS { "should create a valid AMT_RemoteAccessService AddMPS wsman message", - AMT_RemoteAccessService, - methods.GenerateAction(AMT_RemoteAccessService, AddMps), - fmt.Sprintf(`%s%d%d%d%s%s%s`, resourceUriBase, AMT_RemoteAccessService, "AccessInfo", 1, 2, 3, "Username", "Password", "CommonName"), + AMTRemoteAccessService, + methods.GenerateAction(AMTRemoteAccessService, AddMps), + fmt.Sprintf(`%s%d%d%d%s%s%s`, resourceURIBase, AMTRemoteAccessService, "AccessInfo", 1, 2, 3, "Username", "Password", "CommonName"), func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError mpsServer := AddMpServerRequest{ H: "http://intel.com/wbem/wscim/1/amt-schema/1/AMT_RemoteAccessService", AccessInfo: "AccessInfo", @@ -344,6 +355,7 @@ func TestNegativeAMT_RemoteAccessService(t *testing.T) { Password: "Password", CommonName: "CommonName", } + return elementUnderTest.AddMPS(mpsServer) }, Body{ @@ -386,20 +398,21 @@ func TestNegativeAMT_RemoteAccessService(t *testing.T) { }, }, }, - //AddRemoteAccessPolicyRule + // AddRemoteAccessPolicyRule { "should create a valid AMT_RemoteAccessPolicyRule wsman message", - AMT_RemoteAccessService, - methods.GenerateAction(AMT_RemoteAccessService, AddRemoteAccessPolicyRule), - fmt.Sprintf(`%d%d%s
http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous
%s%strue
`, resourceUriBase, AMT_RemoteAccessService, 2, 0, "0300", "http://intel.com/wbem/wscim/1/amt-schema/1/", "AMT_ManagementPresenceRemoteSAP"), + AMTRemoteAccessService, + methods.GenerateAction(AMTRemoteAccessService, AddRemoteAccessPolicyRule), + fmt.Sprintf(`%d%d%s
http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous
%s%strue
`, resourceURIBase, AMTRemoteAccessService, 2, 0, "0300", "http://intel.com/wbem/wscim/1/amt-schema/1/", "AMT_ManagementPresenceRemoteSAP"), func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError remoteAccessPolicyRule := RemoteAccessPolicyRuleRequest{ H: "http://intel.com/wbem/wscim/1/amt-schema/1/AMT_RemoteAccessService", Trigger: 2, TunnelLifeTime: 0, ExtendedData: "0300", } + return elementUnderTest.AddRemoteAccessPolicyRule(remoteAccessPolicyRule, "true") }, Body{ @@ -446,10 +459,10 @@ func TestNegativeAMT_RemoteAccessService(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, "", test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, "", test.body) messageID++ response, err := test.responseFunc() - println(response.XMLOutput) + logrus.Print(response.XMLOutput) assert.Error(t, err) assert.Equal(t, expectedXMLInput, response.XMLInput) assert.NotEqual(t, test.expectedResponse, response.Body) diff --git a/pkg/wsman/amt/remoteaccess/types.go b/pkg/wsman/amt/remoteaccess/types.go index cd28ea38..b59a9ca0 100644 --- a/pkg/wsman/amt/remoteaccess/types.go +++ b/pkg/wsman/amt/remoteaccess/types.go @@ -26,7 +26,7 @@ type Service struct { } // OUTPUTS -// Response Types +// Response Types. type ( Response struct { *client.Message @@ -87,7 +87,6 @@ type ( XMLName xml.Name `xml:"AddRemoteAccessPolicyRule_OUTPUT"` PolicyRuleResponse PolicyRuleResponse `xml:"PolicyRule"` ReturnValue ReturnValue `xml:"ReturnValue"` // ValueMap={0, 1, 36, 38, 2058} Values={PT_STATUS_SUCCESS, PT_STATUS_INTERNAL_ERROR, PT_STATUS_INVALID_PARAMETER, PT_STATUS_FLASH_WRITE_LIMIT_EXCEEDED, PT_STATUS_DUPLICATE} - } MpServer struct { XMLName xml.Name `xml:"MpServer"` @@ -126,7 +125,7 @@ type ( ) // INPUTS -// Request Types +// Request Types. type ( AddMpServerRequest struct { XMLName xml.Name `xml:"h:AddMpServer_INPUT"` @@ -179,7 +178,7 @@ type ( } ) -// Property Types +// Property Types. type ( RemoteAccessPolicyRuleSelector message.Selector PolicyDecisionStrategy int // First Matching:1 | All:2 @@ -187,25 +186,25 @@ type ( // // ValueMap={3, 4, 201} // - // Values={IPv4 Address, IPv6 Address, FQDN} + // Values={IPv4 Address, IPv6 Address, FQDN}. MPServerInfoFormat int // Authentication method to be used when the Intel® AMT subsystem opens a tunnel to the MpServer // // ValueMap={1, 2} // - // Values={Mutual Authentication, Username Password Authentication} + // Values={Mutual Authentication, Username Password Authentication}. MPServerAuthMethod int // The event that will trigger the establishment of the remote connection to the MpServer. // // ValueMap={0, 1, 2, 3} // - // Values={User Initiated, Alert, Periodic, Home Provisioning} + // Values={User Initiated, Alert, Periodic, Home Provisioning}. Trigger int // This field indicates if the MpServer is to be used inside or outside of the organization, or both. Default is outside (0). // // ValueMap={0, 1, 2} // - // Values={External MPS, Internal MPS, Both} + // Values={External MPS, Internal MPS, Both}. MPSType int // ReturnValue is an integer enumeration that indicates the completion status of the method. A value of 0 indicates success. A non-zero value indicates an error. diff --git a/pkg/wsman/amt/setupandconfiguration/decoder.go b/pkg/wsman/amt/setupandconfiguration/decoder.go index 9400cf70..9b00240d 100644 --- a/pkg/wsman/amt/setupandconfiguration/decoder.go +++ b/pkg/wsman/amt/setupandconfiguration/decoder.go @@ -6,11 +6,12 @@ package setupandconfiguration const ( - AMT_SetupAndConfigurationService string = "AMT_SetupAndConfigurationService" - CommitChanges string = "CommitChanges" - Unprovision string = "Unprovision" - SetMEBxPassword string = "SetMEBxPassword" - GetUuid string = "GetUuid" + AMTSetupAndConfigurationService string = "AMT_SetupAndConfigurationService" + CommitChanges string = "CommitChanges" + Unprovision string = "Unprovision" + SetMEBxPassword string = "SetMEBxPassword" + GetUUID string = "GetUuid" + ValueNotFound string = "Value not found in map" ) const ( @@ -28,7 +29,7 @@ const ( RequestedStateUnknown RequestedState = 0 ) -// requestedStateToString is a map of RequestedState values to their string representations +// requestedStateToString is a map of RequestedState values to their string representations. var requestedStateToString = map[RequestedState]string{ RequestedStateEnabled: "RequestedStateEnabled", RequestedStateDisabled: "RequestedStateDisabled", @@ -44,12 +45,13 @@ var requestedStateToString = map[RequestedState]string{ RequestedStateUnknown: "RequestedStateUnknown", } -// String returns the string representation of the RequestedState value +// String returns the string representation of the RequestedState value. func (r RequestedState) String() string { if value, exists := requestedStateToString[r]; exists { return value } - return "Value not found in map" + + return ValueNotFound } const ( @@ -66,7 +68,7 @@ const ( EnabledStateStarting ) -// enabledStateToString is a map of EnabledState values to their string representations +// enabledStateToString is a map of EnabledState values to their string representations. var enabledStateToString = map[EnabledState]string{ EnabledStateUnknown: "EnabledStateUnknown", EnabledStateOther: "EnabledStateOther", @@ -81,12 +83,13 @@ var enabledStateToString = map[EnabledState]string{ EnabledStateStarting: "EnabledStateStarting", } -// String returns the string representation of the EnabledState value +// String returns the string representation of the EnabledState value. func (e EnabledState) String() string { if value, exists := enabledStateToString[e]; exists { return value } - return "Value not found in map" + + return ValueNotFound } const ( @@ -97,33 +100,35 @@ const ( PostProvisioning ProvisioningStateValue = 2 ) -// provisioningModeToString is a map of ProvisioningMode values to their string representations +// provisioningModeToString is a map of ProvisioningMode values to their string representations. var provisioningModeToString = map[ProvisioningModeValue]string{ AdminControlMode: "AdminControlMode", ClientControlMode: "ClientControlMode", } -// String returns the string representation of the ProvisioningMode value +// String returns the string representation of the ProvisioningMode value. func (p ProvisioningModeValue) String() string { if value, exists := provisioningModeToString[p]; exists { return value } - return "Value not found in map" + + return ValueNotFound } -// provisioningStateToString is a map of ProvisioningState values to their string representations +// provisioningStateToString is a map of ProvisioningState values to their string representations. var provisioningStateToString = map[ProvisioningStateValue]string{ PreProvisioning: "PreProvisioning", InProvisioning: "InProvisioning", PostProvisioning: "PostProvisioning", } -// String returns the string representation of the ProvisioningState value +// String returns the string representation of the ProvisioningState value. func (p ProvisioningStateValue) String() string { if value, exists := provisioningStateToString[p]; exists { return value } - return "Value not found in map" + + return ValueNotFound } const ( @@ -132,19 +137,20 @@ const ( SeparateHashPasswordModel ) -// PasswordModelToString is a map of PasswordModel values to their string representations +// PasswordModelToString is a map of PasswordModel values to their string representations. var PasswordModelToString = map[PasswordModelValue]string{ CoupledPasswordModel: "CoupledPasswordModel", SeparatePasswordModel: "SeparatePasswordModel", SeparateHashPasswordModel: "SeparateHashPasswordModel", } -// String returns the string representation of the PasswordModel value +// String returns the string representation of the PasswordModel value. func (p PasswordModelValue) String() string { if value, exists := PasswordModelToString[p]; exists { return value } - return "Value not found in map" + + return ValueNotFound } const ( @@ -167,10 +173,11 @@ var returnValueToString = map[ReturnValue]string{ ReturnValueBlockingComponent: "ReturnValueBlockingComponent", } -// String returns the string representation of the ReturnValue value +// String returns the string representation of the ReturnValue value. func (r ReturnValue) String() string { if value, exists := returnValueToString[r]; exists { return value } - return "Value not found in map" + + return ValueNotFound } diff --git a/pkg/wsman/amt/setupandconfiguration/marshal.go b/pkg/wsman/amt/setupandconfiguration/marshal.go index 8f56a66f..19db55b5 100644 --- a/pkg/wsman/amt/setupandconfiguration/marshal.go +++ b/pkg/wsman/amt/setupandconfiguration/marshal.go @@ -11,20 +11,22 @@ import ( "gopkg.in/yaml.v3" ) -// JSON marshals the type into JSON format +// JSON marshals the type into JSON format. func (r *Response) JSON() string { jsonOutput, err := json.Marshal(r.Body) if err != nil { return "" } + return string(jsonOutput) } -// YAML marshals the type into YAML format +// YAML marshals the type into YAML format. func (r *Response) YAML() string { yamlOutput, err := yaml.Marshal(r.Body) if err != nil { return "" } + return string(yamlOutput) } diff --git a/pkg/wsman/amt/setupandconfiguration/service.go b/pkg/wsman/amt/setupandconfiguration/service.go index fc12fd93..4fbcfe5b 100644 --- a/pkg/wsman/amt/setupandconfiguration/service.go +++ b/pkg/wsman/amt/setupandconfiguration/service.go @@ -19,12 +19,13 @@ import ( "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/client" ) -// DecodeUUID formats the returned AMT base64 encoded UUID into a human readable UUID -func (w *Response) DecodeUUID() (amtUuid string, err error) { - decodedBytes, err := base64.StdEncoding.DecodeString(w.Body.GetUuid_OUTPUT.UUID) +// DecodeUUID formats the returned AMT base64 encoded UUID into a human readable UUID. +func (r *Response) DecodeUUID() (amtUUID string, err error) { + decodedBytes, err := base64.StdEncoding.DecodeString(r.Body.GetUuid_OUTPUT.UUID) if err != nil { - return + return "", err } + rearrangeBytes := []byte{ decodedBytes[3], decodedBytes[2], decodedBytes[1], decodedBytes[0], decodedBytes[5], decodedBytes[4], @@ -32,59 +33,68 @@ func (w *Response) DecodeUUID() (amtUuid string, err error) { decodedBytes[8], decodedBytes[9], decodedBytes[10], decodedBytes[11], decodedBytes[12], decodedBytes[13], decodedBytes[14], decodedBytes[15], } + uuidSlice, err := uuid.FromBytes(rearrangeBytes) if err != nil { - return + return "", err } - amtUuid = uuidSlice.String() - return + + amtUUID = uuidSlice.String() + + return amtUUID, err } -// NewSetupAndConfigurationServiceWithClient instantiates a new Service +// NewSetupAndConfigurationServiceWithClient instantiates a new Service. func NewSetupAndConfigurationServiceWithClient(wsmanMessageCreator *message.WSManMessageCreator, client client.WSMan) Service { return Service{ - base: message.NewBaseWithClient(wsmanMessageCreator, AMT_SetupAndConfigurationService, client), + base: message.NewBaseWithClient(wsmanMessageCreator, AMTSetupAndConfigurationService, client), } } -// Gets the representation of the instance +// Gets the representation of the instance. func (s Service) Get() (response Response, err error) { response = Response{ Message: &client.Message{ XMLInput: s.base.Get(nil), }, } + // send the message to AMT err = s.base.Execute(response.Message) if err != nil { - return + return response, err } + // put the xml response into the go struct err = xml.Unmarshal([]byte(response.XMLOutput), &response) if err != nil { - return + return response, err } - return + + return response, err } -// Enumerate returns an enumeration context which is used in a subsequent Pull call +// Enumerate returns an enumeration context which is used in a subsequent Pull call. func (s Service) Enumerate() (response Response, err error) { response = Response{ Message: &client.Message{ XMLInput: s.base.Enumerate(), }, } + // send the message to AMT err = s.base.Execute(response.Message) if err != nil { - return + return response, err } + // put the xml response into the go struct err = xml.Unmarshal([]byte(response.XMLOutput), &response) if err != nil { - return + return response, err } - return + + return response, err } // Pull returns the instances of this class. An enumeration context provided by the Enumerate call is used as input. @@ -94,38 +104,45 @@ func (s Service) Pull(enumerationContext string) (response Response, err error) XMLInput: s.base.Pull(enumerationContext), }, } + // send the message to AMT err = s.base.Execute(response.Message) if err != nil { - return + return response, err } + // put the xml response into the go struct err = xml.Unmarshal([]byte(response.XMLOutput), &response) if err != nil { - return + return response, err } - return + + return response, err } -// Put will change properties of the selected instance +// Put will change properties of the selected instance. func (s Service) Put(setupAndConfigurationService SetupAndConfigurationServiceRequest) (response Response, err error) { - setupAndConfigurationService.H = fmt.Sprintf("%s%s", message.AMTSchema, AMT_SetupAndConfigurationService) + setupAndConfigurationService.H = fmt.Sprintf("%s%s", message.AMTSchema, AMTSetupAndConfigurationService) + response = Response{ Message: &client.Message{ XMLInput: s.base.Put(setupAndConfigurationService, false, nil), }, } + // send the message to AMT err = s.base.Execute(response.Message) if err != nil { - return + return response, err } + // put the xml response into the go struct err = xml.Unmarshal([]byte(response.XMLOutput), &response) if err != nil { - return + return response, err } - return + + return response, err } // CommitChanges saves pending configuration commands made to the Intel® AMT device. @@ -151,57 +168,64 @@ func (s Service) Put(setupAndConfigurationService SetupAndConfigurationServiceRe // // ValueMap={0, 1, 38, 2057} // -// Values={PT_STATUS_SUCCESS, PT_STATUS_INTERNAL_ERROR, PT_STATUS_FLASH_WRITE_LIMIT_EXCEEDED, PT_STATUS_DATA_MISSING} +// Values={PT_STATUS_SUCCESS, PT_STATUS_INTERNAL_ERROR, PT_STATUS_FLASH_WRITE_LIMIT_EXCEEDED, PT_STATUS_DATA_MISSING}. func (s Service) CommitChanges() (response Response, err error) { - header := s.base.WSManMessageCreator.CreateHeader(methods.GenerateAction(AMT_SetupAndConfigurationService, CommitChanges), AMT_SetupAndConfigurationService, nil, "", "") - body := s.base.WSManMessageCreator.CreateBody(methods.GenerateInputMethod(CommitChanges), AMT_SetupAndConfigurationService, nil) + header := s.base.WSManMessageCreator.CreateHeader(methods.GenerateAction(AMTSetupAndConfigurationService, CommitChanges), AMTSetupAndConfigurationService, nil, "", "") + body := s.base.WSManMessageCreator.CreateBody(methods.GenerateInputMethod(CommitChanges), AMTSetupAndConfigurationService, nil) + response = Response{ Message: &client.Message{ XMLInput: s.base.WSManMessageCreator.CreateXML(header, body), }, } + // send the message to AMT err = s.base.Execute(response.Message) if err != nil { - return + return response, err } + // put the xml response into the go struct err = xml.Unmarshal([]byte(response.XMLOutput), &response) if err != nil { - return + return response, err } + err = checkReturnValue(int(response.Body.SetMEBxPassword_OUTPUT.ReturnValue), "Commit Changes") - return + + return response, err } -// GetUuid gets the AMT UUID from the device. +// GetUUID gets the AMT UUID from the device. // // The returned value is in base64 format. DecodeUUID can be used to format this value into a human readable UUID // // ValueMap={0, 1} // -// Values={PT_STATUS_SUCCESS, PT_STATUS_INTERNAL_ERROR} -func (s Service) GetUuid() (response Response, err error) { - header := s.base.WSManMessageCreator.CreateHeader(methods.GenerateAction(AMT_SetupAndConfigurationService, GetUuid), AMT_SetupAndConfigurationService, nil, "", "") - body := s.base.WSManMessageCreator.CreateBody(methods.GenerateInputMethod(GetUuid), AMT_SetupAndConfigurationService, nil) +// Values={PT_STATUS_SUCCESS, PT_STATUS_INTERNAL_ERROR}. +func (s Service) GetUUID() (response Response, err error) { + header := s.base.WSManMessageCreator.CreateHeader(methods.GenerateAction(AMTSetupAndConfigurationService, GetUUID), AMTSetupAndConfigurationService, nil, "", "") + body := s.base.WSManMessageCreator.CreateBody(methods.GenerateInputMethod(GetUUID), AMTSetupAndConfigurationService, nil) + response = Response{ Message: &client.Message{ XMLInput: s.base.WSManMessageCreator.CreateXML(header, body), }, } + // send the message to AMT err = s.base.Execute(response.Message) if err != nil { - return + return response, err } // put the xml response into the go struct err = xml.Unmarshal([]byte(response.XMLOutput), &response) if err != nil { - return + return response, err } - return + return response, err } // SetMEBXPassword changes the ME Bios extension password. @@ -218,31 +242,36 @@ func (s Service) GetUuid() (response Response, err error) { // // ValueMap={0, 1, 16, 2054} // -// Values={PT_STATUS_SUCCESS, PT_STATUS_INTERNAL_ERROR, PT_STATUS_NOT_PERMITTED, PT_STATUS_INVALID_PASSWORD} +// Values={PT_STATUS_SUCCESS, PT_STATUS_INTERNAL_ERROR, PT_STATUS_NOT_PERMITTED, PT_STATUS_INVALID_PASSWORD}. func (s Service) SetMEBXPassword(password string) (response Response, err error) { - header := s.base.WSManMessageCreator.CreateHeader(methods.GenerateAction(AMT_SetupAndConfigurationService, SetMEBxPassword), AMT_SetupAndConfigurationService, nil, "", "") + header := s.base.WSManMessageCreator.CreateHeader(methods.GenerateAction(AMTSetupAndConfigurationService, SetMEBxPassword), AMTSetupAndConfigurationService, nil, "", "") + mebxPassword := MEBXPassword{ Password: password, } - body := s.base.WSManMessageCreator.CreateBody(methods.GenerateInputMethod(SetMEBxPassword), AMT_SetupAndConfigurationService, &mebxPassword) - // body := fmt.Sprintf(`%s`, s.base.WSManMessageCreator.ResourceURIBase, AMT_SetupAndConfigurationService, password) + body := s.base.WSManMessageCreator.CreateBody(methods.GenerateInputMethod(SetMEBxPassword), AMTSetupAndConfigurationService, &mebxPassword) + response = Response{ Message: &client.Message{ XMLInput: s.base.WSManMessageCreator.CreateXML(header, body), }, } + // send the message to AMT err = s.base.Execute(response.Message) if err != nil { - return + return response, err } + // put the xml response into the go struct err = xml.Unmarshal([]byte(response.XMLOutput), &response) if err != nil { - return + return response, err } + err = checkReturnValue(int(response.Body.SetMEBxPassword_OUTPUT.ReturnValue), "MEBx Password") - return + + return response, err } // Unprovision unconfigures and deactivates the Intel® AMT device. The device will need to be re-provisioned after this command before being able to use AMT features. @@ -251,39 +280,42 @@ func (s Service) SetMEBXPassword(password string) (response Response, err error) // // ValueMap={0, 1, 16, 36, 2076} // -// Values={PT_STATUS_SUCCESS, PT_STATUS_INTERNAL_ERROR, PT_STATUS_NOT_PERMITTED, PT_STATUS_INVALID_PARAMETER, PT_STATUS_BLOCKING_COMPONENT} +// Values={PT_STATUS_SUCCESS, PT_STATUS_INTERNAL_ERROR, PT_STATUS_NOT_PERMITTED, PT_STATUS_INVALID_PARAMETER, PT_STATUS_BLOCKING_COMPONENT}. func (s Service) Unprovision(provisioningMode ProvisioningModeValue) (response Response, err error) { if provisioningMode == 0 { provisioningMode = 1 } + pMode := ProvisioningMode{ ProvisioningMode: provisioningMode, } - header := s.base.WSManMessageCreator.CreateHeader(methods.GenerateAction(AMT_SetupAndConfigurationService, Unprovision), AMT_SetupAndConfigurationService, nil, "", "") - body := s.base.WSManMessageCreator.CreateBody(methods.GenerateInputMethod(Unprovision), AMT_SetupAndConfigurationService, &pMode) - // body := fmt.Sprintf(`%d`, s.base.WSManMessageCreator.ResourceURIBase, AMT_SetupAndConfigurationService, provisioningMode) + + header := s.base.WSManMessageCreator.CreateHeader(methods.GenerateAction(AMTSetupAndConfigurationService, Unprovision), AMTSetupAndConfigurationService, nil, "", "") + body := s.base.WSManMessageCreator.CreateBody(methods.GenerateInputMethod(Unprovision), AMTSetupAndConfigurationService, &pMode) + response = Response{ Message: &client.Message{ XMLInput: s.base.WSManMessageCreator.CreateXML(header, body), }, } + // send the message to AMT err = s.base.Execute(response.Message) if err != nil { - return + return response, err } + // put the xml response into the go struct err = xml.Unmarshal([]byte(response.XMLOutput), &response) if err != nil { - return + return response, err } + if response.Body.Unprovision_OUTPUT.ReturnValue != 0 { - // log.Error("Status: Failed to deactivate. ReturnValue: ", response.Body.Unprovision_OUTPUT.ReturnValue) err = errors.New("Status: Failed to deactivate. ReturnValue: " + fmt.Sprintf("%d", response.Body.Unprovision_OUTPUT.ReturnValue)) - return } - return + return response, err } func checkReturnValue(rc int, item string) (err error) { @@ -292,9 +324,10 @@ func checkReturnValue(rc int, item string) (err error) { return errors.New(item + " is not permitted") } else if rc == int(ReturnValueInvalidPassword) { return errors.New(item + " is invalid") - } else { - return errors.New(item + " non-zero return code: " + strconv.Itoa(rc)) } + + return errors.New(item + " non-zero return code: " + strconv.Itoa(rc)) } + return nil } diff --git a/pkg/wsman/amt/setupandconfiguration/service_test.go b/pkg/wsman/amt/setupandconfiguration/service_test.go index 0ae3bce6..206a9611 100644 --- a/pkg/wsman/amt/setupandconfiguration/service_test.go +++ b/pkg/wsman/amt/setupandconfiguration/service_test.go @@ -9,15 +9,17 @@ import ( "encoding/xml" "testing" - "github.com/stretchr/testify/assert" - "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/internal/message" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/amt/methods" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/common" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/wsmantesting" + "github.com/stretchr/testify/assert" ) -const GetUuid_BODY = "" +const ( + GetUUIDBody = "" + CurrentMessageGetUUID = "getuuid" +) func TestJson(t *testing.T) { response := Response{ @@ -25,7 +27,7 @@ func TestJson(t *testing.T) { GetResponse: SetupAndConfigurationServiceResponse{}, }, } - expectedResult := "{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"GetResponse\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"RequestedState\":0,\"EnabledState\":0,\"ElementName\":\"\",\"SystemCreationClassName\":\"\",\"SystemName\":\"\",\"CreationClassName\":\"\",\"Name\":\"\",\"ProvisioningMode\":0,\"ProvisioningState\":0,\"ZeroTouchConfigurationEnabled\":false,\"ProvisioningServerOTP\":\"\",\"ConfigurationServerFQDN\":\"\",\"PasswordModel\":0,\"DhcpDNSSuffix\":\"\",\"TrustedDNSSuffix\":\"\"},\"EnumerateResponse\":{\"EnumerationContext\":\"\"},\"PullResponse\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"SetupAndConfigurationServiceItems\":null},\"GetUuid_OUTPUT\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"UUID\":\"\"},\"Unprovision_OUTPUT\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"ReturnValue\":0},\"CommitChanges_OUTPUT\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"ReturnValue\":0},\"SetMEBxPassword_OUTPUT\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"ReturnValue\":0}}" + expectedResult := "{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"GetResponse\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"RequestedState\":0,\"EnabledState\":0,\"ElementName\":\"\",\"SystemCreationClassName\":\"\",\"SystemName\":\"\",\"CreationClassName\":\"\",\"Name\":\"\",\"ProvisioningMode\":0,\"ProvisioningState\":0,\"ZeroTouchConfigurationEnabled\":false,\"ProvisioningServerOTP\":\"\",\"ConfigurationServerFQDN\":\"\",\"PasswordModel\":0,\"DhcpDNSSuffix\":\"\",\"TrustedDNSSuffix\":\"\"},\"EnumerateResponse\":{\"EnumerationContext\":\"\"},\"PullResponse\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"SetupAndConfigurationServiceItems\":null},\"GetUUIDOutput\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"UUID\":\"\"},\"UnprovisionOutput\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"ReturnValue\":0},\"CommitChangesOutput\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"ReturnValue\":0},\"SetMEBxPasswordOutput\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"ReturnValue\":0}}" result := response.JSON() assert.Equal(t, expectedResult, result) } @@ -36,15 +38,15 @@ func TestYaml(t *testing.T) { GetResponse: SetupAndConfigurationServiceResponse{}, }, } - expectedResult := "xmlname:\n space: \"\"\n local: \"\"\ngetresponse:\n xmlname:\n space: \"\"\n local: \"\"\n requestedstate: 0\n enabledstate: 0\n elementname: \"\"\n systemcreationclassname: \"\"\n systemname: \"\"\n creationclassname: \"\"\n name: \"\"\n provisioningmode: 0\n provisioningstate: 0\n zerotouchconfigurationenabled: false\n provisioningserverotp: \"\"\n configurationserverfqdn: \"\"\n passwordmodel: 0\n dhcpdnssuffix: \"\"\n trusteddnssuffix: \"\"\nenumerateresponse:\n enumerationcontext: \"\"\npullresponse:\n xmlname:\n space: \"\"\n local: \"\"\n setupandconfigurationserviceitems: []\ngetuuid_output:\n xmlname:\n space: \"\"\n local: \"\"\n uuid: \"\"\nunprovision_output:\n xmlname:\n space: \"\"\n local: \"\"\n returnvalue: 0\ncommitchanges_output:\n xmlname:\n space: \"\"\n local: \"\"\n returnvalue: 0\nsetmebxpassword_output:\n xmlname:\n space: \"\"\n local: \"\"\n returnvalue: 0\n" + expectedResult := "xmlname:\n space: \"\"\n local: \"\"\ngetresponse:\n xmlname:\n space: \"\"\n local: \"\"\n requestedstate: 0\n enabledstate: 0\n elementname: \"\"\n systemcreationclassname: \"\"\n systemname: \"\"\n creationclassname: \"\"\n name: \"\"\n provisioningmode: 0\n provisioningstate: 0\n zerotouchconfigurationenabled: false\n provisioningserverotp: \"\"\n configurationserverfqdn: \"\"\n passwordmodel: 0\n dhcpdnssuffix: \"\"\n trusteddnssuffix: \"\"\nenumerateresponse:\n enumerationcontext: \"\"\npullresponse:\n xmlname:\n space: \"\"\n local: \"\"\n setupandconfigurationserviceitems: []\ngetuuidoutput:\n xmlname:\n space: \"\"\n local: \"\"\n uuid: \"\"\nunprovisionoutput:\n xmlname:\n space: \"\"\n local: \"\"\n returnvalue: 0\ncommitchangesoutput:\n xmlname:\n space: \"\"\n local: \"\"\n returnvalue: 0\nsetmebxpasswordoutput:\n xmlname:\n space: \"\"\n local: \"\"\n returnvalue: 0\n" result := response.YAML() assert.Equal(t, expectedResult, result) } func TestPositiveAMT_SetupAndConfigurationService(t *testing.T) { messageID := 0 - resourceUriBase := "http://intel.com/wbem/wscim/1/amt-schema/1/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.AMTResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "amt/setupandconfiguration", } @@ -59,20 +61,21 @@ func TestPositiveAMT_SetupAndConfigurationService(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //GETS + // GETS { "should create a valid AMT_SetupAndConfigurationService Get wsman message", - AMT_SetupAndConfigurationService, - wsmantesting.GET, "", + AMTSetupAndConfigurationService, + wsmantesting.Get, "", func() (Response, error) { - client.CurrentMessage = "Get" + client.CurrentMessage = wsmantesting.CurrentMessageGet + return elementUnderTest.Get() }, Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, GetResponse: SetupAndConfigurationServiceResponse{ XMLName: xml.Name{Space: "http://intel.com/wbem/wscim/1/amt-schema/1/AMT_SetupAndConfigurationService", Local: "AMT_SetupAndConfigurationService"}, - CreationClassName: AMT_SetupAndConfigurationService, + CreationClassName: AMTSetupAndConfigurationService, ElementName: "Intel(r) AMT Setup and Configuration Service", EnabledState: 5, Name: "Intel(r) AMT Setup and Configuration Service", @@ -87,14 +90,15 @@ func TestPositiveAMT_SetupAndConfigurationService(t *testing.T) { }, }, }, - //ENUMERATES + // ENUMERATES { "should create a valid AMT_SetupAndConfigurationService Enumerate wsman message", - AMT_SetupAndConfigurationService, - wsmantesting.ENUMERATE, - wsmantesting.ENUMERATE_BODY, + AMTSetupAndConfigurationService, + wsmantesting.Enumerate, + wsmantesting.EnumerateBody, func() (Response, error) { - client.CurrentMessage = "Enumerate" + client.CurrentMessage = wsmantesting.CurrentMessageEnumerate + return elementUnderTest.Enumerate() }, Body{ @@ -104,14 +108,15 @@ func TestPositiveAMT_SetupAndConfigurationService(t *testing.T) { }, }, }, - //PULLS + // PULLS { "should create a valid AMT_SetupAndConfigurationService Pull wsman message", - AMT_SetupAndConfigurationService, - wsmantesting.PULL, - wsmantesting.PULL_BODY, + AMTSetupAndConfigurationService, + wsmantesting.Pull, + wsmantesting.PullBody, func() (Response, error) { - client.CurrentMessage = "Pull" + client.CurrentMessage = wsmantesting.CurrentMessagePull + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -121,7 +126,7 @@ func TestPositiveAMT_SetupAndConfigurationService(t *testing.T) { SetupAndConfigurationServiceItems: []SetupAndConfigurationServiceResponse{ { XMLName: xml.Name{Space: "http://intel.com/wbem/wscim/1/amt-schema/1/AMT_SetupAndConfigurationService", Local: "AMT_SetupAndConfigurationService"}, - CreationClassName: AMT_SetupAndConfigurationService, + CreationClassName: AMTSetupAndConfigurationService, ElementName: "Intel(r) AMT Setup and Configuration Service", EnabledState: 5, Name: "Intel(r) AMT Setup and Configuration Service", @@ -138,15 +143,16 @@ func TestPositiveAMT_SetupAndConfigurationService(t *testing.T) { }, }, }, - //GetUuid + // GetUuid { "should return a valid AMT_GetUuid response", - AMT_SetupAndConfigurationService, - methods.GenerateAction(AMT_SetupAndConfigurationService, GetUuid), - GetUuid_BODY, + AMTSetupAndConfigurationService, + methods.GenerateAction(AMTSetupAndConfigurationService, GetUUID), + GetUUIDBody, func() (Response, error) { - client.CurrentMessage = "getuuid" - return elementUnderTest.GetUuid() + client.CurrentMessage = CurrentMessageGetUUID + + return elementUnderTest.GetUUID() }, Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, @@ -156,14 +162,15 @@ func TestPositiveAMT_SetupAndConfigurationService(t *testing.T) { }, }, }, - //CommitChanges + // CommitChanges { "should create a valid AMT_SetupAndConfigurationService CommitChanges wsman message", - AMT_SetupAndConfigurationService, - methods.GenerateAction(AMT_SetupAndConfigurationService, CommitChanges), + AMTSetupAndConfigurationService, + methods.GenerateAction(AMTSetupAndConfigurationService, CommitChanges), ``, func() (Response, error) { client.CurrentMessage = "CommitChanges" + return elementUnderTest.CommitChanges() }, Body{ @@ -174,14 +181,15 @@ func TestPositiveAMT_SetupAndConfigurationService(t *testing.T) { }, }, }, - //SetMEBxPassword + // SetMEBxPassword { "should create a valid AMT_SetupAndConfigurationService SetMEBxPassword wsman message", - AMT_SetupAndConfigurationService, - methods.GenerateAction(AMT_SetupAndConfigurationService, SetMEBxPassword), + AMTSetupAndConfigurationService, + methods.GenerateAction(AMTSetupAndConfigurationService, SetMEBxPassword), `P@ssw0rd`, func() (Response, error) { client.CurrentMessage = "SetMEBxPassword" + return elementUnderTest.SetMEBXPassword("P@ssw0rd") }, Body{ @@ -192,14 +200,15 @@ func TestPositiveAMT_SetupAndConfigurationService(t *testing.T) { }, }, }, - //Unprovision + // Unprovision { "should create a valid AMT_SetupAndConfigurationService Unprovision wsman message", - AMT_SetupAndConfigurationService, - methods.GenerateAction(AMT_SetupAndConfigurationService, Unprovision), + AMTSetupAndConfigurationService, + methods.GenerateAction(AMTSetupAndConfigurationService, Unprovision), `1`, func() (Response, error) { client.CurrentMessage = "Unprovision" + return elementUnderTest.Unprovision(1) }, Body{ @@ -214,7 +223,7 @@ func TestPositiveAMT_SetupAndConfigurationService(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, "", test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, "", test.body) messageID++ response, err := test.responseFunc() assert.NoError(t, err) @@ -229,16 +238,18 @@ func TestPositiveAMT_SetupAndConfigurationService(t *testing.T) { name string responseFunc func() (string, error, error) expectedResponse string - }{{ - "should properly decode AMT GetUuid Response to a UUID string", - func() (string, error, error) { - client.CurrentMessage = "getuuid" - response, err1 := elementUnderTest.GetUuid() - uuid, err2 := response.DecodeUUID() - return uuid, err1, err2 + }{ + { + "should properly decode AMT GetUuid Response to a UUID string", + func() (string, error, error) { + client.CurrentMessage = CurrentMessageGetUUID + response, err1 := elementUnderTest.GetUUID() + uuid, err2 := response.DecodeUUID() + + return uuid, err1, err2 + }, + "55e3ae13-bfd2-61bb-17a0-88aedd7037ea", }, - "55e3ae13-bfd2-61bb-17a0-88aedd7037ea", - }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { @@ -249,17 +260,17 @@ func TestPositiveAMT_SetupAndConfigurationService(t *testing.T) { }) } }) - } func TestNegativeAMT_SetupAndConfigurationService(t *testing.T) { messageID := 0 - resourceUriBase := "http://intel.com/wbem/wscim/1/amt-schema/1/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.AMTResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "amt/setupandconfiguration", } elementUnderTest := NewSetupAndConfigurationServiceWithClient(wsmanMessageCreator, &client) + t.Run("amt_* Tests", func(t *testing.T) { tests := []struct { name string @@ -273,12 +284,13 @@ func TestNegativeAMT_SetupAndConfigurationService(t *testing.T) { { "should create an invalid AMT_SetupAndConfigurationService Pull wsman message", "AMT_EthernetPortSettings", - wsmantesting.PULL, - wsmantesting.PULL_BODY, + wsmantesting.Pull, + wsmantesting.PullBody, "", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError response, err := elementUnderTest.Pull("") + return response, err }, Body{ @@ -288,7 +300,7 @@ func TestNegativeAMT_SetupAndConfigurationService(t *testing.T) { SetupAndConfigurationServiceItems: []SetupAndConfigurationServiceResponse{ { XMLName: xml.Name{Space: "http://intel.com/wbem/wscim/1/amt-schema/1/AMT_SetupAndConfigurationService", Local: "AMT_SetupAndConfigurationService"}, - CreationClassName: AMT_SetupAndConfigurationService, + CreationClassName: AMTSetupAndConfigurationService, ElementName: "Intel(r) AMT Setup and Configuration Service", EnabledState: 5, Name: "Intel(r) AMT Setup and Configuration Service", @@ -309,7 +321,7 @@ func TestNegativeAMT_SetupAndConfigurationService(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, test.extraHeader, test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, test.extraHeader, test.body) messageID++ response, err := test.responseFunc() assert.Error(t, err) @@ -323,16 +335,21 @@ func TestNegativeAMT_SetupAndConfigurationService(t *testing.T) { name string responseFunc func() (string, error) expectedResponse string - }{{ - "should return error due to bad UUID returned", - func() (string, error) { - client.CurrentMessage = "getuuid-bad" - response, _ := elementUnderTest.GetUuid() - uuid, err := response.DecodeUUID() - return uuid, err + }{ + { + "should return error due to bad UUID returned", + func() (string, error) { + client.CurrentMessage = "getuuid-bad" + response, err := elementUnderTest.GetUUID() + if err != nil { + return "", err + } + uuid, err := response.DecodeUUID() + + return uuid, err + }, + "55e3ae13-bfd2-61bb-17a0-88aedd7037ea", }, - "55e3ae13-bfd2-61bb-17a0-88aedd7037ea", - }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { diff --git a/pkg/wsman/amt/setupandconfiguration/types.go b/pkg/wsman/amt/setupandconfiguration/types.go index f751876f..fed3cea0 100644 --- a/pkg/wsman/amt/setupandconfiguration/types.go +++ b/pkg/wsman/amt/setupandconfiguration/types.go @@ -17,7 +17,7 @@ type Service struct { base message.Base } -// Response Types +// Response Types. type ( Response struct { *client.Message @@ -59,7 +59,7 @@ type ( SetupAndConfigurationServiceItems []SetupAndConfigurationServiceResponse `xml:"Items>AMT_SetupAndConfigurationService"` } - // UUID of the system. If the value is all FFh, the ID is not currently present in the system, but is settable. If the value is all 00h, the ID is not present in the system. Corresponds to the UUID field of the SMBIOS Type 1 structure + // UUID of the system. If the value is all FFh, the ID is not currently present in the system, but is settable. If the value is all 00h, the ID is not present in the system. Corresponds to the UUID field of the SMBIOS Type 1 structure. GetUuid_OUTPUT struct { XMLName xml.Name `xml:"GetUuid_OUTPUT"` UUID string `xml:"UUID"` @@ -67,7 +67,7 @@ type ( // ValueMap={0, 1, 16, 36, 2076} // - // Values={PT_STATUS_SUCCESS, PT_STATUS_INTERNAL_ERROR, PT_STATUS_NOT_PERMITTED, PT_STATUS_INVALID_PARAMETER, PT_STATUS_BLOCKING_COMPONENT} + // Values={PT_STATUS_SUCCESS, PT_STATUS_INTERNAL_ERROR, PT_STATUS_NOT_PERMITTED, PT_STATUS_INVALID_PARAMETER, PT_STATUS_BLOCKING_COMPONENT}. Unprovision_OUTPUT struct { XMLName xml.Name `xml:"Unprovision_OUTPUT"` ReturnValue ReturnValue @@ -75,7 +75,7 @@ type ( // ValueMap={0, 1, 38, 2057} // - // Values={PT_STATUS_SUCCESS, PT_STATUS_INTERNAL_ERROR, PT_STATUS_FLASH_WRITE_LIMIT_EXCEEDED, PT_STATUS_DATA_MISSING} + // Values={PT_STATUS_SUCCESS, PT_STATUS_INTERNAL_ERROR, PT_STATUS_FLASH_WRITE_LIMIT_EXCEEDED, PT_STATUS_DATA_MISSING}. CommitChanges_OUTPUT struct { XMLName xml.Name `xml:"CommitChanges_OUTPUT"` ReturnValue ReturnValue @@ -83,14 +83,14 @@ type ( // ValueMap={0, 1, 16, 2054} // - // Values={PT_STATUS_SUCCESS, PT_STATUS_INTERNAL_ERROR, PT_STATUS_NOT_PERMITTED, PT_STATUS_INVALID_PASSWORD} + // Values={PT_STATUS_SUCCESS, PT_STATUS_INTERNAL_ERROR, PT_STATUS_NOT_PERMITTED, PT_STATUS_INVALID_PASSWORD}. SetMEBxPassword_OUTPUT struct { XMLName xml.Name `xml:"SetMEBxPassword_OUTPUT"` ReturnValue ReturnValue } ) -// Request Types +// Request Types. type ( SetupAndConfigurationServiceRequest struct { XMLName xml.Name `xml:"h:AMT_SetupAndConfigurationService"` @@ -114,7 +114,7 @@ type ( // Password needs to be strong: Contain at least one of: upper-case, lower-case, digit and special character // - // MinLen=8, MaxLen=32 + // MinLen=8, MaxLen=32. MEBXPassword struct { XMLName xml.Name `xml:"h:SetMEBxPassword_INPUT"` H string `xml:"xmlns:h,attr"` @@ -125,7 +125,7 @@ type ( // // ValueMap={0, 1, 2, 3} // - // Values={ProvisioningModeCurrent, ProvisioningModeEnterprise, ProvisioningModeSmallBusiness, ProvisioningRemoteConnectivity} + // Values={ProvisioningModeCurrent, ProvisioningModeEnterprise, ProvisioningModeSmallBusiness, ProvisioningRemoteConnectivity}. ProvisioningMode struct { XMLName xml.Name `xml:"h:Unprovision_INPUT"` H string `xml:"xmlns:h,attr"` diff --git a/pkg/wsman/amt/timesynchronization/decoder.go b/pkg/wsman/amt/timesynchronization/decoder.go index de1f628c..78c4af65 100644 --- a/pkg/wsman/amt/timesynchronization/decoder.go +++ b/pkg/wsman/amt/timesynchronization/decoder.go @@ -6,9 +6,10 @@ package timesynchronization const ( - AMT_TimeSynchronizationService string = "AMT_TimeSynchronizationService" - GetLowAccuracyTimeSynch string = "GetLowAccuracyTimeSynch" - SetHighAccuracyTimeSynch string = "SetHighAccuracyTimeSynch" + AMTTimeSynchronizationService string = "AMT_TimeSynchronizationService" + GetLowAccuracyTimeSynch string = "GetLowAccuracyTimeSynch" + SetHighAccuracyTimeSynch string = "SetHighAccuracyTimeSynch" + ValueNotFound string = "Value not found in map" ) const ( @@ -17,20 +18,20 @@ const ( LocalTimeSyncEnabledFalse ) -// localTimeSyncEnabledString is a map of LocalTimeSyncEnabled values to their string representations +// localTimeSyncEnabledString is a map of LocalTimeSyncEnabled values to their string representations. var localTimeSyncEnabledString = map[LocalTimeSyncEnabled]string{ LocalTimeSyncEnabledDefaultTrue: "LocalTimeSyncEnabledDefaultTrue", LocalTimeSyncEnabledConfiguredTrue: "LocalTimeSyncEnabledConfiguredTrue", LocalTimeSyncEnabledFalse: "LocalTimeSyncEnabledFalse", } -// String returns the string representation of the LocalTimeSyncEnabled value +// String returns the string representation of the LocalTimeSyncEnabled value. func (l LocalTimeSyncEnabled) String() string { if value, exists := localTimeSyncEnabledString[l]; exists { return value } - return "Value not found in map" + return ValueNotFound } const ( @@ -38,19 +39,19 @@ const ( TimeSourceConfigured ) -// timeSourceString is a map of TimeSource values to their string representations +// timeSourceString is a map of TimeSource values to their string representations. var timeSourceString = map[TimeSource]string{ TimeSourceBiosRTC: "TimeSourceBiosRTC", TimeSourceConfigured: "TimeSourceConfigured", } -// String returns the string representation of the TimeSource value +// String returns the string representation of the TimeSource value. func (t TimeSource) String() string { if value, exists := timeSourceString[t]; exists { return value } - return "Value not found in map" + return ValueNotFound } const ( @@ -67,7 +68,7 @@ const ( EnabledStateStarting ) -// enabledStateString is a map of EnabledState values to their string representations +// enabledStateString is a map of EnabledState values to their string representations. var enabledStateString = map[EnabledState]string{ EnabledStateUnknown: "EnabledStateUnknown", EnabledStateOther: "EnabledStateOther", @@ -82,13 +83,13 @@ var enabledStateString = map[EnabledState]string{ EnabledStateStarting: "EnabledStateStarting", } -// String returns the string representation of the EnabledState value +// String returns the string representation of the EnabledState value. func (e EnabledState) String() string { if value, exists := enabledStateString[e]; exists { return value } - return "Value not found in map" + return ValueNotFound } const ( @@ -106,7 +107,7 @@ const ( RequestedStateNotApplicable RequestedState = 12 ) -// requestedStateString is a map of RequestedState values to their string representations +// requestedStateString is a map of RequestedState values to their string representations. var requestedStateString = map[RequestedState]string{ RequestedStateUnknown: "RequestedStateUnknown", RequestedStateEnabled: "RequestedStateEnabled", @@ -122,13 +123,13 @@ var requestedStateString = map[RequestedState]string{ RequestedStateNotApplicable: "RequestedStateNotApplicable", } -// String returns the string representation of the RequestedState value +// String returns the string representation of the RequestedState value. func (r RequestedState) String() string { if value, exists := requestedStateString[r]; exists { return value } - return "Value not found in map" + return ValueNotFound } const ( @@ -138,7 +139,7 @@ const ( ReturnValueFlashWriteLimitExceeded ReturnValue = 38 ) -// returnValueString is a map of ReturnValue values to their string representations +// returnValueString is a map of ReturnValue values to their string representations. var returnValueString = map[ReturnValue]string{ ReturnValueSuccess: "ReturnValueSuccess", ReturnValueInternalError: "ReturnValueInternalError", @@ -146,11 +147,11 @@ var returnValueString = map[ReturnValue]string{ ReturnValueFlashWriteLimitExceeded: "ReturnValueFlashWriteLimitExceeded", } -// String returns the string representation of the ReturnValue value +// String returns the string representation of the ReturnValue value. func (r ReturnValue) String() string { if value, exists := returnValueString[r]; exists { return value } - return "Value not found in map" + return ValueNotFound } diff --git a/pkg/wsman/amt/timesynchronization/marshal.go b/pkg/wsman/amt/timesynchronization/marshal.go index ad17d67f..d3ee6774 100644 --- a/pkg/wsman/amt/timesynchronization/marshal.go +++ b/pkg/wsman/amt/timesynchronization/marshal.go @@ -11,20 +11,22 @@ import ( "gopkg.in/yaml.v3" ) -// JSON marshals the type into JSON format +// JSON marshals the type into JSON format. func (r *Response) JSON() string { jsonOutput, err := json.Marshal(r.Body) if err != nil { return "" } + return string(jsonOutput) } -// YAML marshals the type into YAML format +// YAML marshals the type into YAML format. func (r *Response) YAML() string { yamlOutput, err := yaml.Marshal(r.Body) if err != nil { return "" } + return string(yamlOutput) } diff --git a/pkg/wsman/amt/timesynchronization/service.go b/pkg/wsman/amt/timesynchronization/service.go index c05ef633..b6f4a038 100644 --- a/pkg/wsman/amt/timesynchronization/service.go +++ b/pkg/wsman/amt/timesynchronization/service.go @@ -14,14 +14,14 @@ import ( "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/client" ) -// NewTimeSynchronizationServiceWithClient instantiates a new Service +// NewTimeSynchronizationServiceWithClient instantiates a new Service. func NewTimeSynchronizationServiceWithClient(wsmanMessageCreator *message.WSManMessageCreator, client client.WSMan) Service { return Service{ - base: message.NewBaseWithClient(wsmanMessageCreator, AMT_TimeSynchronizationService, client), + base: message.NewBaseWithClient(wsmanMessageCreator, AMTTimeSynchronizationService, client), } } -// Get retrieves the representation of the instance +// Get retrieves the representation of the instance. func (service Service) Get() (response Response, err error) { response = Response{ Message: &client.Message{ @@ -38,10 +38,11 @@ func (service Service) Get() (response Response, err error) { if err != nil { return } + return } -// Enumerate returns an enumeration context which is used in a subsequent Pull call +// Enumerate returns an enumeration context which is used in a subsequent Pull call. func (service Service) Enumerate() (response Response, err error) { response = Response{ Message: &client.Message{ @@ -58,6 +59,7 @@ func (service Service) Enumerate() (response Response, err error) { if err != nil { return } + return } @@ -78,6 +80,7 @@ func (service Service) Pull(enumerationContext string) (response Response, err e if err != nil { return } + return } @@ -91,10 +94,10 @@ func (service Service) Pull(enumerationContext string) (response Response, err e // // ValueMap={0, 1, 36, 38} // -// Values={PT_STATUS_SUCCESS, PT_STATUS_INTERNAL_ERROR, PT_STATUS_INVALID_PARAMETER, PT_STATUS_FLASH_WRITE_LIMIT_EXCEEDED} +// Values={PT_STATUS_SUCCESS, PT_STATUS_INTERNAL_ERROR, PT_STATUS_INVALID_PARAMETER, PT_STATUS_FLASH_WRITE_LIMIT_EXCEEDED}. func (service Service) SetHighAccuracyTimeSynch(ta0, tm1, tm2 int64) (response Response, err error) { - header := service.base.WSManMessageCreator.CreateHeader(methods.GenerateAction(AMT_TimeSynchronizationService, SetHighAccuracyTimeSynch), AMT_TimeSynchronizationService, nil, "", "") - body := service.base.WSManMessageCreator.CreateBody(methods.GenerateInputMethod(SetHighAccuracyTimeSynch), AMT_TimeSynchronizationService, &SetHighAccuracyTimeSynch_INPUT{ + header := service.base.WSManMessageCreator.CreateHeader(methods.GenerateAction(AMTTimeSynchronizationService, SetHighAccuracyTimeSynch), AMTTimeSynchronizationService, nil, "", "") + body := service.base.WSManMessageCreator.CreateBody(methods.GenerateInputMethod(SetHighAccuracyTimeSynch), AMTTimeSynchronizationService, &SetHighAccuracyTimeSynch_INPUT{ H: "http://intel.com/wbem/wscim/1/amt-schema/1/AMT_TimeSynchronizationService", Ta0: ta0, Tm1: tm1, @@ -115,13 +118,14 @@ func (service Service) SetHighAccuracyTimeSynch(ta0, tm1, tm2 int64) (response R if err != nil { return } + return } // GetLowAccuracyTimeSynch is used for reading the Intel® AMT device's internal clock. func (service Service) GetLowAccuracyTimeSynch() (response Response, err error) { - header := service.base.WSManMessageCreator.CreateHeader(methods.GenerateAction(AMT_TimeSynchronizationService, GetLowAccuracyTimeSynch), AMT_TimeSynchronizationService, nil, "", "") - body := service.base.WSManMessageCreator.CreateBody(methods.GenerateInputMethod(GetLowAccuracyTimeSynch), AMT_TimeSynchronizationService, nil) + header := service.base.WSManMessageCreator.CreateHeader(methods.GenerateAction(AMTTimeSynchronizationService, GetLowAccuracyTimeSynch), AMTTimeSynchronizationService, nil, "", "") + body := service.base.WSManMessageCreator.CreateBody(methods.GenerateInputMethod(GetLowAccuracyTimeSynch), AMTTimeSynchronizationService, nil) response = Response{ Message: &client.Message{ XMLInput: service.base.WSManMessageCreator.CreateXML(header, body), @@ -137,5 +141,6 @@ func (service Service) GetLowAccuracyTimeSynch() (response Response, err error) if err != nil { return } + return } diff --git a/pkg/wsman/amt/timesynchronization/service_test.go b/pkg/wsman/amt/timesynchronization/service_test.go index 8061d2e1..181c2780 100644 --- a/pkg/wsman/amt/timesynchronization/service_test.go +++ b/pkg/wsman/amt/timesynchronization/service_test.go @@ -9,12 +9,11 @@ import ( "encoding/xml" "testing" - "github.com/stretchr/testify/assert" - "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/internal/message" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/amt/methods" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/common" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/wsmantesting" + "github.com/stretchr/testify/assert" ) func TestJson(t *testing.T) { @@ -41,8 +40,8 @@ func TestYaml(t *testing.T) { func TestPositiveAMT_TimeSynchronizationService(t *testing.T) { messageID := 0 - resourceUriBase := "http://intel.com/wbem/wscim/1/amt-schema/1/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.AMTResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "amt/timesynchronization", } @@ -57,14 +56,15 @@ func TestPositiveAMT_TimeSynchronizationService(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //GETS + // GETS { "should create a valid AMT_TimeSynchronizationService Get wsman message", - AMT_TimeSynchronizationService, - wsmantesting.GET, + AMTTimeSynchronizationService, + wsmantesting.Get, "", func() (Response, error) { - client.CurrentMessage = "Get" + client.CurrentMessage = wsmantesting.CurrentMessageGet + return elementUnderTest.Get() }, Body{ @@ -83,14 +83,15 @@ func TestPositiveAMT_TimeSynchronizationService(t *testing.T) { }, }, }, - //ENUMERATES + // ENUMERATES { "should create a valid AMT_TimeSynchronizationService Enumerate wsman message", - AMT_TimeSynchronizationService, - wsmantesting.ENUMERATE, - wsmantesting.ENUMERATE_BODY, + AMTTimeSynchronizationService, + wsmantesting.Enumerate, + wsmantesting.EnumerateBody, func() (Response, error) { - client.CurrentMessage = "Enumerate" + client.CurrentMessage = wsmantesting.CurrentMessageEnumerate + return elementUnderTest.Enumerate() }, Body{ @@ -100,14 +101,15 @@ func TestPositiveAMT_TimeSynchronizationService(t *testing.T) { }, }, }, - //PULLS + // PULLS { "should create a valid AMT_TimeSynchronizationService Pull wsman message", - AMT_TimeSynchronizationService, - wsmantesting.PULL, - wsmantesting.PULL_BODY, + AMTTimeSynchronizationService, + wsmantesting.Pull, + wsmantesting.PullBody, func() (Response, error) { - client.CurrentMessage = "Pull" + client.CurrentMessage = wsmantesting.CurrentMessagePull + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -132,13 +134,14 @@ func TestPositiveAMT_TimeSynchronizationService(t *testing.T) { }, }, { - //GetLowAccuracyTimeSynch + // GetLowAccuracyTimeSynch "should create a valid AMT_TimeSynchronizationService GetLowAccuracyTimeSynch wsman message", - AMT_TimeSynchronizationService, - methods.GenerateAction(AMT_TimeSynchronizationService, GetLowAccuracyTimeSynch), + AMTTimeSynchronizationService, + methods.GenerateAction(AMTTimeSynchronizationService, GetLowAccuracyTimeSynch), ``, func() (Response, error) { client.CurrentMessage = "GetLowAccuracyTimeSynch" + return elementUnderTest.GetLowAccuracyTimeSynch() }, Body{ @@ -151,13 +154,14 @@ func TestPositiveAMT_TimeSynchronizationService(t *testing.T) { }, }, { - //SetHighAccuracyTimeSynch + // SetHighAccuracyTimeSynch "should create a valid AMT_TimeSynchronizationService SetHighAccuracyTimeSynch wsman message", - AMT_TimeSynchronizationService, - methods.GenerateAction(AMT_TimeSynchronizationService, SetHighAccuracyTimeSynch), + AMTTimeSynchronizationService, + methods.GenerateAction(AMTTimeSynchronizationService, SetHighAccuracyTimeSynch), "164424091116442409431644240943", func() (Response, error) { client.CurrentMessage = "SetHighAccuracyTimeSynch" + return elementUnderTest.SetHighAccuracyTimeSynch(1644240911, 1644240943, 1644240943) }, Body{ @@ -172,7 +176,7 @@ func TestPositiveAMT_TimeSynchronizationService(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, "", test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, "", test.body) messageID++ response, err := test.responseFunc() assert.NoError(t, err) @@ -182,10 +186,11 @@ func TestPositiveAMT_TimeSynchronizationService(t *testing.T) { } }) } + func TestNegativeAMT_TimeSynchronizationService(t *testing.T) { messageID := 0 - resourceUriBase := "http://intel.com/wbem/wscim/1/amt-schema/1/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.AMTResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "amt/timesynchronization", } @@ -200,14 +205,15 @@ func TestNegativeAMT_TimeSynchronizationService(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //GETS + // GETS { "should create a valid AMT_TimeSynchronizationService Get wsman message", - AMT_TimeSynchronizationService, - wsmantesting.GET, + AMTTimeSynchronizationService, + wsmantesting.Get, "", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Get() }, Body{ @@ -226,14 +232,15 @@ func TestNegativeAMT_TimeSynchronizationService(t *testing.T) { }, }, }, - //ENUMERATES + // ENUMERATES { "should create a valid AMT_TimeSynchronizationService Enumerate wsman message", - AMT_TimeSynchronizationService, - wsmantesting.ENUMERATE, - wsmantesting.ENUMERATE_BODY, + AMTTimeSynchronizationService, + wsmantesting.Enumerate, + wsmantesting.EnumerateBody, func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Enumerate() }, Body{ @@ -243,14 +250,15 @@ func TestNegativeAMT_TimeSynchronizationService(t *testing.T) { }, }, }, - //PULLS + // PULLS { "should create a valid AMT_TimeSynchronizationService Pull wsman message", - AMT_TimeSynchronizationService, - wsmantesting.PULL, - wsmantesting.PULL_BODY, + AMTTimeSynchronizationService, + wsmantesting.Pull, + wsmantesting.PullBody, func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -275,13 +283,14 @@ func TestNegativeAMT_TimeSynchronizationService(t *testing.T) { }, }, { - //GetLowAccuracyTimeSynch + // GetLowAccuracyTimeSynch "should create a valid AMT_TimeSynchronizationService GetLowAccuracyTimeSynch wsman message", - AMT_TimeSynchronizationService, - methods.GenerateAction(AMT_TimeSynchronizationService, GetLowAccuracyTimeSynch), + AMTTimeSynchronizationService, + methods.GenerateAction(AMTTimeSynchronizationService, GetLowAccuracyTimeSynch), ``, func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.GetLowAccuracyTimeSynch() }, Body{ @@ -294,13 +303,14 @@ func TestNegativeAMT_TimeSynchronizationService(t *testing.T) { }, }, { - //SetHighAccuracyTimeSynch + // SetHighAccuracyTimeSynch "should create a valid AMT_TimeSynchronizationService SetHighAccuracyTimeSynch wsman message", - AMT_TimeSynchronizationService, - methods.GenerateAction(AMT_TimeSynchronizationService, SetHighAccuracyTimeSynch), + AMTTimeSynchronizationService, + methods.GenerateAction(AMTTimeSynchronizationService, SetHighAccuracyTimeSynch), "164424091116442409431644240943", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.SetHighAccuracyTimeSynch(1644240911, 1644240943, 1644240943) }, Body{ @@ -315,7 +325,7 @@ func TestNegativeAMT_TimeSynchronizationService(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, "", test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, "", test.body) messageID++ response, err := test.responseFunc() assert.Error(t, err) diff --git a/pkg/wsman/amt/timesynchronization/types.go b/pkg/wsman/amt/timesynchronization/types.go index bfeb5144..65b0b9c2 100644 --- a/pkg/wsman/amt/timesynchronization/types.go +++ b/pkg/wsman/amt/timesynchronization/types.go @@ -17,7 +17,7 @@ type Service struct { base message.Base } -// Response Types +// Response Types. type ( Response struct { *client.Message @@ -54,7 +54,7 @@ type ( // ValueMap={0, 1} // - // Values={PT_STATUS_SUCCESS, PT_STATUS_INTERNAL_ERROR} + // Values={PT_STATUS_SUCCESS, PT_STATUS_INTERNAL_ERROR}. GetLowAccuracyTimeSynchResponse struct { XMLName xml.Name `xml:"GetLowAccuracyTimeSynch_OUTPUT"` Ta0 int64 `xml:"Ta0"` @@ -63,7 +63,7 @@ type ( // ValueMap={0, 1, 36, 38} // - // Values={PT_STATUS_SUCCESS, PT_STATUS_INTERNAL_ERROR, PT_STATUS_INVALID_PARAMETER, PT_STATUS_FLASH_WRITE_LIMIT_EXCEEDED} + // Values={PT_STATUS_SUCCESS, PT_STATUS_INTERNAL_ERROR, PT_STATUS_INVALID_PARAMETER, PT_STATUS_FLASH_WRITE_LIMIT_EXCEEDED}. SetHighAccuracyTimeSynchResponse struct { XMLName xml.Name `xml:"SetHighAccuracyTimeSynch_OUTPUT"` ReturnValue ReturnValue `xml:"ReturnValue"` @@ -81,7 +81,7 @@ type ( TimeSource int ) -// Request Types +// Request Types. type ( // Ta0: The time value received from invoking GetLowAccuracyTimeSynch(). // diff --git a/pkg/wsman/amt/tls/constants.go b/pkg/wsman/amt/tls/constants.go index 4f1cf447..7cc9eb57 100644 --- a/pkg/wsman/amt/tls/constants.go +++ b/pkg/wsman/amt/tls/constants.go @@ -6,7 +6,7 @@ package tls const ( - AMT_TLSCredentialContext string = "AMT_TLSCredentialContext" - AMT_TLSSettingData string = "AMT_TLSSettingData" - AMT_TLSProtocolEndpointCollection string = "AMT_TLSProtocolEndpointCollection" + AMTTLSCredentialContext string = "AMT_TLSCredentialContext" + AMTTLSSettingData string = "AMT_TLSSettingData" + AMTTLSProtocolEndpointCollection string = "AMT_TLSProtocolEndpointCollection" ) diff --git a/pkg/wsman/amt/tls/credentialcontext.go b/pkg/wsman/amt/tls/credentialcontext.go index 747a8f43..66773ecf 100644 --- a/pkg/wsman/amt/tls/credentialcontext.go +++ b/pkg/wsman/amt/tls/credentialcontext.go @@ -26,14 +26,14 @@ import ( "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/client" ) -// NewTLSCredentialContextWithClient instantiates a new CredentialContext +// NewTLSCredentialContextWithClient instantiates a new CredentialContext. func NewTLSCredentialContextWithClient(wsmanMessageCreator *message.WSManMessageCreator, client client.WSMan) CredentialContext { return CredentialContext{ - base: message.NewBaseWithClient(wsmanMessageCreator, AMT_TLSCredentialContext, client), + base: message.NewBaseWithClient(wsmanMessageCreator, AMTTLSCredentialContext, client), } } -// Get retrieves the representation of the instance +// Get retrieves the representation of the instance. func (credentialContext CredentialContext) Get() (response Response, err error) { response = Response{ Message: &client.Message{ @@ -50,10 +50,11 @@ func (credentialContext CredentialContext) Get() (response Response, err error) if err != nil { return } + return } -// Enumerate returns an enumeration context which is used in a subsequent Pull call +// Enumerate returns an enumeration context which is used in a subsequent Pull call. func (credentialContext CredentialContext) Enumerate() (response Response, err error) { response = Response{ Message: &client.Message{ @@ -70,6 +71,7 @@ func (credentialContext CredentialContext) Enumerate() (response Response, err e if err != nil { return } + return } @@ -90,10 +92,11 @@ func (credentialContext CredentialContext) Pull(enumerationContext string) (resp if err != nil { return } + return } -// Delete removes a the specified instance +// Delete removes a the specified instance. func (credentialContext CredentialContext) Delete(handle string) (response Response, err error) { selector := message.Selector{Name: "Name", Value: handle} response = Response{ @@ -111,13 +114,13 @@ func (credentialContext CredentialContext) Delete(handle string) (response Respo if err != nil { return } + return } -// Creates a new instance of this class +// Creates a new instance of this class. func (credentialContext CredentialContext) Create(certHandle string) (response Response, err error) { - - header := credentialContext.base.WSManMessageCreator.CreateHeader(message.BaseActionsCreate, AMT_TLSCredentialContext, nil, "", "") + header := credentialContext.base.WSManMessageCreator.CreateHeader(message.BaseActionsCreate, AMTTLSCredentialContext, nil, "", "") body := fmt.Sprintf(`/wsman%sAMT_PublicKeyCertificate%s/wsman%sAMT_TLSProtocolEndpointCollectionTLSProtocolEndpointInstances Collection`, credentialContext.base.WSManMessageCreator.ResourceURIBase, credentialContext.base.WSManMessageCreator.ResourceURIBase, certHandle, credentialContext.base.WSManMessageCreator.ResourceURIBase) response = Response{ Message: &client.Message{ @@ -134,5 +137,6 @@ func (credentialContext CredentialContext) Create(certHandle string) (response R if err != nil { return } + return } diff --git a/pkg/wsman/amt/tls/credentialcontext_test.go b/pkg/wsman/amt/tls/credentialcontext_test.go index 877082db..d3a2d79b 100644 --- a/pkg/wsman/amt/tls/credentialcontext_test.go +++ b/pkg/wsman/amt/tls/credentialcontext_test.go @@ -9,11 +9,10 @@ import ( "encoding/xml" "testing" - "github.com/stretchr/testify/assert" - "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/internal/message" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/common" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/wsmantesting" + "github.com/stretchr/testify/assert" ) func TestJson(t *testing.T) { @@ -40,8 +39,8 @@ func TestYaml(t *testing.T) { func TestPositiveAMT_TLSCredentialContext(t *testing.T) { messageID := 0 - resourceUriBase := "http://intel.com/wbem/wscim/1/amt-schema/1/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.AMTResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "amt/tls/credentialcontext", } @@ -57,7 +56,7 @@ func TestPositiveAMT_TLSCredentialContext(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //GETS + // GETS // { // "should create a valid AMT_TLSCredentialContext Get wsman message", // AMT_TLSCredentialContext, @@ -65,20 +64,21 @@ func TestPositiveAMT_TLSCredentialContext(t *testing.T) { // "", // "", // func() (Response, error) { - // client.CurrentMessage = "Get" + // client.CurrentMessage = wsmantesting.CurrentMessageGet // return elementUnderTest.Get() // }, // Body{}, // }, - //ENUMERATES + // ENUMERATES { "should create a valid AMT_TLSCredentialContext Enumerate wsman message", - AMT_TLSCredentialContext, - wsmantesting.ENUMERATE, - wsmantesting.ENUMERATE_BODY, + AMTTLSCredentialContext, + wsmantesting.Enumerate, + wsmantesting.EnumerateBody, "", func() (Response, error) { - client.CurrentMessage = "Enumerate" + client.CurrentMessage = wsmantesting.CurrentMessageEnumerate + return elementUnderTest.Enumerate() }, Body{ @@ -88,7 +88,8 @@ func TestPositiveAMT_TLSCredentialContext(t *testing.T) { }, }, }, - //PULLS + + // PULLS // { // "should create a valid AMT_TLSCredentialContext Pull wsman message", // AMT_TLSCredentialContext, @@ -96,7 +97,7 @@ func TestPositiveAMT_TLSCredentialContext(t *testing.T) { // wsmantesting.PULL_BODY, // "", // func() (Response, error) { - // client.CurrentMessage = "Pull" + // client.CurrentMessage = wsmantesting.CurrentMessagePull // return elementUnderTest.Pull(wsmantesting.EnumerationContext) // }, // Body{ @@ -106,7 +107,7 @@ func TestPositiveAMT_TLSCredentialContext(t *testing.T) { // }, // }, // }, - //DELETE + // DELETE // { // "should create a valid AMT_TLSCredentialContext Delete wsman message", // AMT_TLSCredentialContext, @@ -114,18 +115,18 @@ func TestPositiveAMT_TLSCredentialContext(t *testing.T) { // "", // "instanceID123", // func() (Response, error) { - // client.CurrentMessage = "Delete" + // client.CurrentMessage = wsmantesting.CurrentMessageDelete // return elementUnderTest.Delete("instanceID123") // }, // Body{}, // }, - //Create + // Create // { // "should create a valid AMT_TLSCredentialContext Create wsman message", // AMT_TLSCredentialContext, // wsmantesting.CREATE, // "", - // "", //fmt.Sprintf(`/wsman%sAMT_PublicKeyCertificate%s/wsman%sAMT_TLSProtocolEndpointCollectionTLSProtocolEndpointInstances Collection`, credentialContext.base.WSManMessageCreator.ResourceURIBase, credentialContext.base.WSManMessageCreator.ResourceURIBase, certHandle, credentialContext.base.WSManMessageCreator.ResourceURIBase), + // "", //logrus.Sprintf(`/wsman%sAMT_PublicKeyCertificate%s/wsman%sAMT_TLSProtocolEndpointCollectionTLSProtocolEndpointInstances Collection`, credentialContext.base.WSManMessageCreator.ResourceURIBase, credentialContext.base.WSManMessageCreator.ResourceURIBase, certHandle, credentialContext.base.WSManMessageCreator.ResourceURIBase), // func() (Response, error) { // client.CurrentMessage = "Create" // return elementUnderTest.Create("test") @@ -135,7 +136,7 @@ func TestPositiveAMT_TLSCredentialContext(t *testing.T) { } for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, test.extraHeader, test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, test.extraHeader, test.body) messageID++ response, err := test.responseFunc() assert.NoError(t, err) diff --git a/pkg/wsman/amt/tls/marshal.go b/pkg/wsman/amt/tls/marshal.go index 5d85fa40..130c68e9 100644 --- a/pkg/wsman/amt/tls/marshal.go +++ b/pkg/wsman/amt/tls/marshal.go @@ -11,20 +11,22 @@ import ( "gopkg.in/yaml.v3" ) -// JSON marshals the type into JSON format +// JSON marshals the type into JSON format. func (r *Response) JSON() string { jsonOutput, err := json.Marshal(r.Body) if err != nil { return "" } + return string(jsonOutput) } -// YAML marshals the type into YAML format +// YAML marshals the type into YAML format. func (r *Response) YAML() string { yamlOutput, err := yaml.Marshal(r.Body) if err != nil { return "" } + return string(yamlOutput) } diff --git a/pkg/wsman/amt/tls/protocolendpointcollection.go b/pkg/wsman/amt/tls/protocolendpointcollection.go index d4b285a6..f69cbaf6 100644 --- a/pkg/wsman/amt/tls/protocolendpointcollection.go +++ b/pkg/wsman/amt/tls/protocolendpointcollection.go @@ -12,14 +12,14 @@ import ( "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/client" ) -// NewTLSProtocolEndpointCollectionWithClient instantiates a new ProtocolEndpointCollection +// NewTLSProtocolEndpointCollectionWithClient instantiates a new ProtocolEndpointCollection. func NewTLSProtocolEndpointCollectionWithClient(wsmanMessageCreator *message.WSManMessageCreator, client client.WSMan) ProtocolEndpointCollection { return ProtocolEndpointCollection{ - base: message.NewBaseWithClient(wsmanMessageCreator, AMT_TLSProtocolEndpointCollection, client), + base: message.NewBaseWithClient(wsmanMessageCreator, AMTTLSProtocolEndpointCollection, client), } } -// Get retrieves the representation of the instance +// Get retrieves the representation of the instance. func (collection ProtocolEndpointCollection) Get() (response Response, err error) { response = Response{ Message: &client.Message{ @@ -36,10 +36,11 @@ func (collection ProtocolEndpointCollection) Get() (response Response, err error if err != nil { return } + return } -// Enumerate returns an enumeration context which is used in a subsequent Pull call +// Enumerate returns an enumeration context which is used in a subsequent Pull call. func (collection ProtocolEndpointCollection) Enumerate() (response Response, err error) { response = Response{ Message: &client.Message{ @@ -56,6 +57,7 @@ func (collection ProtocolEndpointCollection) Enumerate() (response Response, err if err != nil { return } + return } @@ -76,5 +78,6 @@ func (collection ProtocolEndpointCollection) Pull(enumerationContext string) (re if err != nil { return } + return } diff --git a/pkg/wsman/amt/tls/protocolendpointcollection_test.go b/pkg/wsman/amt/tls/protocolendpointcollection_test.go index 993c5f70..7ece8098 100644 --- a/pkg/wsman/amt/tls/protocolendpointcollection_test.go +++ b/pkg/wsman/amt/tls/protocolendpointcollection_test.go @@ -10,17 +10,16 @@ import ( "fmt" "testing" - "github.com/stretchr/testify/assert" - "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/internal/message" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/common" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/wsmantesting" + "github.com/stretchr/testify/assert" ) func TestPositiveAMT_TLSProtocolEndpointCollection(t *testing.T) { messageID := 0 - resourceUriBase := "http://intel.com/wbem/wscim/1/amt-schema/1/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.AMTResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "amt/tls/protocolendpointcollection", } @@ -36,34 +35,36 @@ func TestPositiveAMT_TLSProtocolEndpointCollection(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //GETS + // GETS { "should create a valid AMT_TLSProtocolEndpointCollection Get wsman message", - AMT_TLSProtocolEndpointCollection, - wsmantesting.GET, + AMTTLSProtocolEndpointCollection, + wsmantesting.Get, "", "", func() (Response, error) { - client.CurrentMessage = "Get" + client.CurrentMessage = wsmantesting.CurrentMessageGet + return elementUnderTest.Get() }, Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, ProtocolEndpointCollectionGetResponse: ProtocolEndpointCollectionResponse{ - XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMT_TLSProtocolEndpointCollection), Local: AMT_TLSProtocolEndpointCollection}, + XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMTTLSProtocolEndpointCollection), Local: AMTTLSProtocolEndpointCollection}, ElementName: "TLSProtocolEndpoint Instances Collection", }, }, }, - //ENUMERATES + // ENUMERATES { "should create a valid AMT_TLSProtocolEndpointCollection Enumerate wsman message", - AMT_TLSProtocolEndpointCollection, - wsmantesting.ENUMERATE, - wsmantesting.ENUMERATE_BODY, + AMTTLSProtocolEndpointCollection, + wsmantesting.Enumerate, + wsmantesting.EnumerateBody, "", func() (Response, error) { - client.CurrentMessage = "Enumerate" + client.CurrentMessage = wsmantesting.CurrentMessageEnumerate + return elementUnderTest.Enumerate() }, Body{ @@ -73,15 +74,16 @@ func TestPositiveAMT_TLSProtocolEndpointCollection(t *testing.T) { }, }, }, - //PULLS + // PULLS { "should create a valid AMT_TLSProtocolEndpointCollection Pull wsman message", - AMT_TLSProtocolEndpointCollection, - wsmantesting.PULL, - wsmantesting.PULL_BODY, + AMTTLSProtocolEndpointCollection, + wsmantesting.Pull, + wsmantesting.PullBody, "", func() (Response, error) { - client.CurrentMessage = "Pull" + client.CurrentMessage = wsmantesting.CurrentMessagePull + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -90,7 +92,7 @@ func TestPositiveAMT_TLSProtocolEndpointCollection(t *testing.T) { XMLName: xml.Name{Space: message.XMLPullResponseSpace, Local: "PullResponse"}, ProtocolEndpointCollectionItems: []ProtocolEndpointCollectionResponse{ { - XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMT_TLSProtocolEndpointCollection), Local: AMT_TLSProtocolEndpointCollection}, + XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMTTLSProtocolEndpointCollection), Local: AMTTLSProtocolEndpointCollection}, ElementName: "TLSProtocolEndpoint Instances Collection", }, }, @@ -100,7 +102,7 @@ func TestPositiveAMT_TLSProtocolEndpointCollection(t *testing.T) { } for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, test.extraHeader, test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, test.extraHeader, test.body) messageID++ response, err := test.responseFunc() assert.NoError(t, err) @@ -110,10 +112,11 @@ func TestPositiveAMT_TLSProtocolEndpointCollection(t *testing.T) { } }) } + func TestNegativeAMT_TLSProtocolEndpointCollection(t *testing.T) { messageID := 0 - resourceUriBase := "http://intel.com/wbem/wscim/1/amt-schema/1/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.AMTResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "amt/tls/protocolendpointcollection", } @@ -129,34 +132,36 @@ func TestNegativeAMT_TLSProtocolEndpointCollection(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //GETS + // GETS { "should create a valid AMT_TLSProtocolEndpointCollection Get wsman message", - AMT_TLSProtocolEndpointCollection, - wsmantesting.GET, + AMTTLSProtocolEndpointCollection, + wsmantesting.Get, "", "", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Get() }, Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, ProtocolEndpointCollectionGetResponse: ProtocolEndpointCollectionResponse{ - XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMT_TLSProtocolEndpointCollection), Local: AMT_TLSProtocolEndpointCollection}, + XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMTTLSProtocolEndpointCollection), Local: AMTTLSProtocolEndpointCollection}, ElementName: "TLSProtocolEndpoint Instances Collection", }, }, }, - //ENUMERATES + // ENUMERATES { "should create a valid AMT_TLSProtocolEndpointCollection Enumerate wsman message", - AMT_TLSProtocolEndpointCollection, - wsmantesting.ENUMERATE, - wsmantesting.ENUMERATE_BODY, + AMTTLSProtocolEndpointCollection, + wsmantesting.Enumerate, + wsmantesting.EnumerateBody, "", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Enumerate() }, Body{ @@ -166,15 +171,16 @@ func TestNegativeAMT_TLSProtocolEndpointCollection(t *testing.T) { }, }, }, - //PULLS + // PULLS { "should create a valid AMT_TLSProtocolEndpointCollection Pull wsman message", - AMT_TLSProtocolEndpointCollection, - wsmantesting.PULL, - wsmantesting.PULL_BODY, + AMTTLSProtocolEndpointCollection, + wsmantesting.Pull, + wsmantesting.PullBody, "", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -183,7 +189,7 @@ func TestNegativeAMT_TLSProtocolEndpointCollection(t *testing.T) { XMLName: xml.Name{Space: message.XMLPullResponseSpace, Local: "PullResponse"}, ProtocolEndpointCollectionItems: []ProtocolEndpointCollectionResponse{ { - XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMT_TLSProtocolEndpointCollection), Local: AMT_TLSProtocolEndpointCollection}, + XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMTTLSProtocolEndpointCollection), Local: AMTTLSProtocolEndpointCollection}, ElementName: "TLSProtocolEndpoint Instances Collection", }, }, @@ -193,7 +199,7 @@ func TestNegativeAMT_TLSProtocolEndpointCollection(t *testing.T) { } for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, test.extraHeader, test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, test.extraHeader, test.body) messageID++ response, err := test.responseFunc() assert.Error(t, err) diff --git a/pkg/wsman/amt/tls/settingdata.go b/pkg/wsman/amt/tls/settingdata.go index bb28db45..84a66df7 100644 --- a/pkg/wsman/amt/tls/settingdata.go +++ b/pkg/wsman/amt/tls/settingdata.go @@ -13,14 +13,14 @@ import ( "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/client" ) -// NewTLSSettingDataWithClient instantiates a new SettingData +// NewTLSSettingDataWithClient instantiates a new SettingData. func NewTLSSettingDataWithClient(wsmanMessageCreator *message.WSManMessageCreator, client client.WSMan) SettingData { return SettingData{ - base: message.NewBaseWithClient(wsmanMessageCreator, AMT_TLSSettingData, client), + base: message.NewBaseWithClient(wsmanMessageCreator, AMTTLSSettingData, client), } } -// Get retrieves the representation of the instance +// Get retrieves the representation of the instance. func (settingData SettingData) Get(instanceID string) (response Response, err error) { selector := message.Selector{ Name: "InstanceID", @@ -41,10 +41,11 @@ func (settingData SettingData) Get(instanceID string) (response Response, err er if err != nil { return } + return } -// Enumerate returns an enumeration context which is used in a subsequent Pull call +// Enumerate returns an enumeration context which is used in a subsequent Pull call. func (settingData SettingData) Enumerate() (response Response, err error) { response = Response{ Message: &client.Message{ @@ -61,6 +62,7 @@ func (settingData SettingData) Enumerate() (response Response, err error) { if err != nil { return } + return } @@ -81,6 +83,7 @@ func (settingData SettingData) Pull(enumerationContext string) (response Respons if err != nil { return } + return } @@ -95,7 +98,7 @@ func (settingData SettingData) Pull(enumerationContext string) (response Respons // // This method will not modify the flash ("Enabled" property) until setupandconfiguration.CommitChanges() is issued and performed successfully. func (settingData SettingData) Put(instanceID string, tlsSettingData SettingDataRequest) (response Response, err error) { - tlsSettingData.H = fmt.Sprintf("%s%s", message.AMTSchema, AMT_TLSSettingData) + tlsSettingData.H = fmt.Sprintf("%s%s", message.AMTSchema, AMTTLSSettingData) selector := message.Selector{ Name: "InstanceID", Value: instanceID, @@ -115,5 +118,6 @@ func (settingData SettingData) Put(instanceID string, tlsSettingData SettingData if err != nil { return } + return } diff --git a/pkg/wsman/amt/tls/settingdata_test.go b/pkg/wsman/amt/tls/settingdata_test.go index e825fcc7..e0438f4b 100644 --- a/pkg/wsman/amt/tls/settingdata_test.go +++ b/pkg/wsman/amt/tls/settingdata_test.go @@ -23,8 +23,8 @@ const ( func TestPositiveAMT_TLSSettingData(t *testing.T) { messageID := 0 - resourceUriBase := "http://intel.com/wbem/wscim/1/amt-schema/1/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.AMTResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "amt/tls/settingdata", } @@ -40,21 +40,22 @@ func TestPositiveAMT_TLSSettingData(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //GETS + // GETS { "should create a valid AMT_TLSSettingData Get wsman message", - AMT_TLSSettingData, - wsmantesting.GET, + AMTTLSSettingData, + wsmantesting.Get, "Intel(r) AMT 802.3 TLS Settings", "", func() (Response, error) { - client.CurrentMessage = "Get" + client.CurrentMessage = wsmantesting.CurrentMessageGet + return elementUnderTest.Get("Intel(r) AMT 802.3 TLS Settings") }, Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, SettingDataGetAndPutResponse: SettingDataResponse{ - XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMT_TLSSettingData), Local: AMT_TLSSettingData}, + XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMTTLSSettingData), Local: AMTTLSSettingData}, AcceptNonSecureConnections: false, ElementName: "Intel(r) AMT 802.3 TLS Settings", Enabled: false, @@ -64,15 +65,16 @@ func TestPositiveAMT_TLSSettingData(t *testing.T) { }, }, - //ENUMERATES + // ENUMERATES { "should create a valid AMT_TLSSettingData Enumerate wsman message", - AMT_TLSSettingData, - wsmantesting.ENUMERATE, + AMTTLSSettingData, + wsmantesting.Enumerate, "", - wsmantesting.ENUMERATE_BODY, + wsmantesting.EnumerateBody, func() (Response, error) { - client.CurrentMessage = "Enumerate" + client.CurrentMessage = wsmantesting.CurrentMessageEnumerate + return elementUnderTest.Enumerate() }, Body{ @@ -82,15 +84,16 @@ func TestPositiveAMT_TLSSettingData(t *testing.T) { }, }, }, - //PULLS + // PULLS { "should create a valid AMT_TLSSettingData Pull wsman message", - AMT_TLSSettingData, - wsmantesting.PULL, + AMTTLSSettingData, + wsmantesting.Pull, "", - wsmantesting.PULL_BODY, + wsmantesting.PullBody, func() (Response, error) { - client.CurrentMessage = "Pull" + client.CurrentMessage = wsmantesting.CurrentMessagePull + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -99,7 +102,7 @@ func TestPositiveAMT_TLSSettingData(t *testing.T) { XMLName: xml.Name{Space: message.XMLPullResponseSpace, Local: "PullResponse"}, SettingDataItems: []SettingDataResponse{ { - XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMT_TLSSettingData), Local: AMT_TLSSettingData}, + XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMTTLSSettingData), Local: AMTTLSSettingData}, AcceptNonSecureConnections: false, ElementName: "Intel(r) AMT 802.3 TLS Settings", Enabled: false, @@ -107,7 +110,7 @@ func TestPositiveAMT_TLSSettingData(t *testing.T) { MutualAuthentication: false, }, { - XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMT_TLSSettingData), Local: AMT_TLSSettingData}, + XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMTTLSSettingData), Local: AMTTLSSettingData}, AcceptNonSecureConnections: true, ElementName: "Intel(r) AMT LMS TLS Settings", Enabled: false, @@ -119,26 +122,27 @@ func TestPositiveAMT_TLSSettingData(t *testing.T) { }, }, - //PUTS + // PUTS { "should create a valid AMT_TLSSettingData Put wsman message", - AMT_TLSSettingData, - wsmantesting.PUT, + AMTTLSSettingData, + wsmantesting.Put, "Intel(r) AMT 802.3 TLS Settings", "Intel(r) AMT 802.3 TLS SettingsIntel(r) AMT 802.3 TLS Settingsfalsetruefalsefalse", func() (Response, error) { - client.CurrentMessage = "Put" + client.CurrentMessage = wsmantesting.CurrentMessagePut tlsSettingData := SettingDataRequest{ ElementName: "Intel(r) AMT 802.3 TLS Settings", InstanceID: "Intel(r) AMT 802.3 TLS Settings", Enabled: true, } + return elementUnderTest.Put("Intel(r) AMT 802.3 TLS Settings", tlsSettingData) }, Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, SettingDataGetAndPutResponse: SettingDataResponse{ - XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMT_TLSSettingData), Local: AMT_TLSSettingData}, + XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMTTLSSettingData), Local: AMTTLSSettingData}, AcceptNonSecureConnections: false, ElementName: "Intel(r) AMT 802.3 TLS Settings", Enabled: false, @@ -151,7 +155,7 @@ func TestPositiveAMT_TLSSettingData(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, test.extraHeader, test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, test.extraHeader, test.body) messageID++ response, err := test.responseFunc() assert.NoError(t, err) @@ -161,10 +165,11 @@ func TestPositiveAMT_TLSSettingData(t *testing.T) { } }) } + func TestNegativeAMT_TLSSettingData(t *testing.T) { messageID := 0 - resourceUriBase := "http://intel.com/wbem/wscim/1/amt-schema/1/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.AMTResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "amt/tls/settingdata", } @@ -180,21 +185,22 @@ func TestNegativeAMT_TLSSettingData(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //GETS + // GETS { "should create a valid AMT_TLSSettingData Get wsman message", - AMT_TLSSettingData, - wsmantesting.GET, + AMTTLSSettingData, + wsmantesting.Get, "Intel(r) AMT 802.3 TLS Settings", "", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Get("Intel(r) AMT 802.3 TLS Settings") }, Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, SettingDataGetAndPutResponse: SettingDataResponse{ - XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMT_TLSSettingData), Local: AMT_TLSSettingData}, + XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMTTLSSettingData), Local: AMTTLSSettingData}, AcceptNonSecureConnections: false, ElementName: "Intel(r) AMT 802.3 TLS Settings", Enabled: false, @@ -204,15 +210,16 @@ func TestNegativeAMT_TLSSettingData(t *testing.T) { }, }, - //ENUMERATES + // ENUMERATES { "should create a valid AMT_TLSSettingData Enumerate wsman message", - AMT_TLSSettingData, - wsmantesting.ENUMERATE, + AMTTLSSettingData, + wsmantesting.Enumerate, "", - wsmantesting.ENUMERATE_BODY, + wsmantesting.EnumerateBody, func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Enumerate() }, Body{ @@ -222,15 +229,16 @@ func TestNegativeAMT_TLSSettingData(t *testing.T) { }, }, }, - //PULLS + // PULLS { "should create a valid AMT_TLSSettingData Pull wsman message", - AMT_TLSSettingData, - wsmantesting.PULL, + AMTTLSSettingData, + wsmantesting.Pull, "", - wsmantesting.PULL_BODY, + wsmantesting.PullBody, func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -239,7 +247,7 @@ func TestNegativeAMT_TLSSettingData(t *testing.T) { XMLName: xml.Name{Space: message.XMLPullResponseSpace, Local: "PullResponse"}, SettingDataItems: []SettingDataResponse{ { - XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMT_TLSSettingData), Local: AMT_TLSSettingData}, + XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMTTLSSettingData), Local: AMTTLSSettingData}, AcceptNonSecureConnections: false, ElementName: "Intel(r) AMT 802.3 TLS Settings", Enabled: false, @@ -247,7 +255,7 @@ func TestNegativeAMT_TLSSettingData(t *testing.T) { MutualAuthentication: false, }, { - XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMT_TLSSettingData), Local: AMT_TLSSettingData}, + XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMTTLSSettingData), Local: AMTTLSSettingData}, AcceptNonSecureConnections: true, ElementName: "Intel(r) AMT LMS TLS Settings", Enabled: false, @@ -259,26 +267,27 @@ func TestNegativeAMT_TLSSettingData(t *testing.T) { }, }, - //PUTS + // PUTS { "should create a valid AMT_TLSSettingData Put wsman message", - AMT_TLSSettingData, - wsmantesting.PUT, + AMTTLSSettingData, + wsmantesting.Put, "Intel(r) AMT 802.3 TLS Settings", "Intel(r) AMT 802.3 TLS SettingsIntel(r) AMT 802.3 TLS Settingsfalsetruefalsefalse", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError tlsSettingData := SettingDataRequest{ ElementName: "Intel(r) AMT 802.3 TLS Settings", InstanceID: "Intel(r) AMT 802.3 TLS Settings", Enabled: true, } + return elementUnderTest.Put("Intel(r) AMT 802.3 TLS Settings", tlsSettingData) }, Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, SettingDataGetAndPutResponse: SettingDataResponse{ - XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMT_TLSSettingData), Local: AMT_TLSSettingData}, + XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMTTLSSettingData), Local: AMTTLSSettingData}, AcceptNonSecureConnections: false, ElementName: "Intel(r) AMT 802.3 TLS Settings", Enabled: false, @@ -291,7 +300,7 @@ func TestNegativeAMT_TLSSettingData(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, test.extraHeader, test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, test.extraHeader, test.body) messageID++ response, err := test.responseFunc() assert.Error(t, err) diff --git a/pkg/wsman/amt/tls/types.go b/pkg/wsman/amt/tls/types.go index 7506cf49..e7622297 100644 --- a/pkg/wsman/amt/tls/types.go +++ b/pkg/wsman/amt/tls/types.go @@ -26,7 +26,7 @@ type ( ) // OUTPUT -// Response Types +// Response Types. type ( Response struct { *client.Message @@ -46,7 +46,7 @@ type ( XMLName xml.Name `xml:"AMT_TLSSettingData"` ElementName string `xml:"ElementName,omitempty"` // The user-friendly name for this instance of SettingData. In addition, the user-friendly name can be used as an index property for a search or query. (Note: The name does not have to be unique within a namespace.) InstanceID string `xml:"InstanceID,omitempty"` // Within the scope of the instantiating Namespace, InstanceID opaquely and uniquely identifies an instance of this class. To ensure uniqueness within the NameSpace, the value of InstanceID should be constructed using the following "preferred" algorithm: : Where and are separated by a colon (:), and where must include a copyrighted, trademarked, or otherwise unique name that is owned by the business entity that is creating or defining the InstanceID or that is a registered ID assigned to the business entity by a recognized global authority. (This requirement is similar to the _ structure of Schema class names.) In addition, to ensure uniqueness, must not contain a colon (:). When using this algorithm, the first colon to appear in InstanceID must appear between and . is chosen by the business entity and should not be reused to identify different underlying (real-world) elements. If the above "preferred" algorithm is not used, the defining entity must assure that the resulting InstanceID is not reused across any InstanceIDs produced by this or other providers for the NameSpace of this instance. For DMTF-defined instances, the "preferred" algorithm must be used with the set to CIM. - MutualAuthentication bool `xml:"MutualAuthentication"` // Adminstrator-settable property that determines whether or not mutual authentication is used at the TLS layer is used on the associated service access point. If False, then only the server authenticates itself at the TLS layer. Use of Mutual Authentication on the local interface is deprecated in Release 6.0. The feature will be removed in a future release. This property is only visible / usable for users of ADMIN_SECURITY_ADMINISTRATION realm. This property must be supplied if Enabled property is True. + MutualAuthentication bool `xml:"MutualAuthentication"` // Administrator-settable property that determines whether or not mutual authentication is used at the TLS layer is used on the associated service access point. If False, then only the server authenticates itself at the TLS layer. Use of Mutual Authentication on the local interface is deprecated in Release 6.0. The feature will be removed in a future release. This property is only visible / usable for users of ADMIN_SECURITY_ADMINISTRATION realm. This property must be supplied if Enabled property is True. Enabled bool `xml:"Enabled"` // Administrator-settable property that determines whether or not TLS is used on the associated service access point. TrustedCN []string `xml:"TrustedCN,omitempty"` // An array of strings, used to validate the CN subfield of the subject field in X.509 certificates presented to Intel® AMT in the TLS handshake. This value must comply with the requirements of RFC 1035. AcceptNonSecureConnections bool `xml:"AcceptNonSecureConnections"` // This setting defines once TLS is enabled and configured whether non-secure EOI/WSMAN connections are still accepted by FW on ports 16992 and 623. If AcceptNonSecureConnections is set to TRUE then non-secure connections are still accepted. If set to FALSE then non-secure connections are rejected. This setting may be set per interface for the local and network interfaces. AMT_TLSSettingData.AcceptNonSecureConnections may only be modified for the remote interface. It is a read-only property for the local interface instance. @@ -99,7 +99,7 @@ type ( H string `xml:"xmlns:h,attr"` ElementName string `xml:"h:ElementName,omitempty"` // The user-friendly name for this instance of SettingData. In addition, the user-friendly name can be used as an index property for a search or query. (Note: The name does not have to be unique within a namespace.) InstanceID string `xml:"h:InstanceID,omitempty"` // Within the scope of the instantiating Namespace, InstanceID opaquely and uniquely identifies an instance of this class. To ensure uniqueness within the NameSpace, the value of InstanceID should be constructed using the following "preferred" algorithm: : Where and are separated by a colon (:), and where must include a copyrighted, trademarked, or otherwise unique name that is owned by the business entity that is creating or defining the InstanceID or that is a registered ID assigned to the business entity by a recognized global authority. (This requirement is similar to the _ structure of Schema class names.) In addition, to ensure uniqueness, must not contain a colon (:). When using this algorithm, the first colon to appear in InstanceID must appear between and . is chosen by the business entity and should not be reused to identify different underlying (real-world) elements. If the above "preferred" algorithm is not used, the defining entity must assure that the resulting InstanceID is not reused across any InstanceIDs produced by this or other providers for the NameSpace of this instance. For DMTF-defined instances, the "preferred" algorithm must be used with the set to CIM. - MutualAuthentication bool `xml:"h:MutualAuthentication"` // Adminstrator-settable property that determines whether or not mutual authentication is used at the TLS layer is used on the associated service access point. If False, then only the server authenticates itself at the TLS layer. Use of Mutual Authentication on the local interface is deprecated in Release 6.0. The feature will be removed in a future release. This property is only visible / usable for users of ADMIN_SECURITY_ADMINISTRATION realm. This property must be supplied if Enabled property is True. + MutualAuthentication bool `xml:"h:MutualAuthentication"` // Administrator-settable property that determines whether or not mutual authentication is used at the TLS layer is used on the associated service access point. If False, then only the server authenticates itself at the TLS layer. Use of Mutual Authentication on the local interface is deprecated in Release 6.0. The feature will be removed in a future release. This property is only visible / usable for users of ADMIN_SECURITY_ADMINISTRATION realm. This property must be supplied if Enabled property is True. Enabled bool `xml:"h:Enabled"` // Administrator-settable property that determines whether or not TLS is used on the associated service access point. TrustedCN []string `xml:"h:TrustedCN,omitempty"` // An array of strings, used to validate the CN subfield of the subject field in X.509 certificates presented to Intel® AMT in the TLS handshake. This value must comply with the requirements of RFC 1035. AcceptNonSecureConnections bool `xml:"h:AcceptNonSecureConnections"` // This setting defines once TLS is enabled and configured whether non-secure EOI/WSMAN connections are still accepted by FW on ports 16992 and 623. If AcceptNonSecureConnections is set to TRUE then non-secure connections are still accepted. If set to FALSE then non-secure connections are rejected. This setting may be set per interface for the local and network interfaces. AMT_TLSSettingData.AcceptNonSecureConnections may only be modified for the remote interface. It is a read-only property for the local interface instance. diff --git a/pkg/wsman/amt/userinitiatedconnection/decoder.go b/pkg/wsman/amt/userinitiatedconnection/decoder.go index b59bb45c..8d27ad8b 100644 --- a/pkg/wsman/amt/userinitiatedconnection/decoder.go +++ b/pkg/wsman/amt/userinitiatedconnection/decoder.go @@ -8,7 +8,8 @@ package userinitiatedconnection // INPUTS constants const ( - AMT_UserInitiatedConnectionService string = "AMT_UserInitiatedConnectionService" + AMTUserInitiatedConnectionService string = "AMT_UserInitiatedConnectionService" + ValueNotFound string = "Value not found in map" ) const ( @@ -36,7 +37,7 @@ const ( EnabledStateBIOSAndOSInterfacesEnabled EnabledState = 32771 ) -// enabledStateToString is a map of EnabledState value to string +// enabledStateToString is a map of EnabledState value to string. var enabledStateToString = map[EnabledState]string{ EnabledStateUnknown: "Unknown", EnabledStateOther: "Other", @@ -55,12 +56,13 @@ var enabledStateToString = map[EnabledState]string{ EnabledStateBIOSAndOSInterfacesEnabled: "BIOSAndOSInterfacesEnabled", } -// String returns the string representation of the EnabledState value +// String returns the string representation of the EnabledState value. func (e EnabledState) String() string { if value, exists := enabledStateToString[e]; exists { return value } - return "Value not found in map" + + return ValueNotFound } const ( @@ -77,7 +79,7 @@ const ( ReturnValueBusy ReturnValue = 4099 ) -// returnValueToString is a map of ReturnValue value to string +// returnValueToString is a map of ReturnValue value to string. var returnValueToString = map[ReturnValue]string{ ReturnValueCompletedWithNoError: "CompletedWithNoError", ReturnValueNotSupported: "NotSupported", @@ -92,10 +94,11 @@ var returnValueToString = map[ReturnValue]string{ ReturnValueBusy: "Busy", } -// String returns the string representation of the ReturnValue value +// String returns the string representation of the ReturnValue value. func (r ReturnValue) String() string { if value, exists := returnValueToString[r]; exists { return value } - return "Value not found in map" + + return ValueNotFound } diff --git a/pkg/wsman/amt/userinitiatedconnection/marshal.go b/pkg/wsman/amt/userinitiatedconnection/marshal.go index 1fa1b009..92bd9dad 100644 --- a/pkg/wsman/amt/userinitiatedconnection/marshal.go +++ b/pkg/wsman/amt/userinitiatedconnection/marshal.go @@ -11,20 +11,22 @@ import ( "gopkg.in/yaml.v3" ) -// JSON marshals the type into JSON format +// JSON marshals the type into JSON format. func (r *Response) JSON() string { jsonOutput, err := json.Marshal(r.Body) if err != nil { return "" } + return string(jsonOutput) } -// YAML marshals the type into YAML format +// YAML marshals the type into YAML format. func (r *Response) YAML() string { yamlOutput, err := yaml.Marshal(r.Body) if err != nil { return "" } + return string(yamlOutput) } diff --git a/pkg/wsman/amt/userinitiatedconnection/service.go b/pkg/wsman/amt/userinitiatedconnection/service.go index 0f399938..6ca1b1fd 100644 --- a/pkg/wsman/amt/userinitiatedconnection/service.go +++ b/pkg/wsman/amt/userinitiatedconnection/service.go @@ -16,11 +16,11 @@ import ( func NewUserInitiatedConnectionServiceWithClient(wsmanMessageCreator *message.WSManMessageCreator, client client.WSMan) Service { return Service{ - base: message.NewBaseWithClient(wsmanMessageCreator, AMT_UserInitiatedConnectionService, client), + base: message.NewBaseWithClient(wsmanMessageCreator, AMTUserInitiatedConnectionService, client), } } -// Get retrieves the representation of the instance +// Get retrieves the representation of the instance. func (service Service) Get() (response Response, err error) { response = Response{ Message: &client.Message{ @@ -37,10 +37,11 @@ func (service Service) Get() (response Response, err error) { if err != nil { return } + return } -// Enumerate returns an enumeration context which is used in a subsequent Pull call +// Enumerate returns an enumeration context which is used in a subsequent Pull call. func (service Service) Enumerate() (response Response, err error) { response = Response{ Message: &client.Message{ @@ -57,6 +58,7 @@ func (service Service) Enumerate() (response Response, err error) { if err != nil { return } + return } @@ -77,6 +79,7 @@ func (service Service) Pull(enumerationContext string) (response Response, err e if err != nil { return } + return } @@ -97,11 +100,11 @@ func (service Service) Pull(enumerationContext string) (response Response, err e // // ValueMap={0, 1, 2, 3, 4, 5, 6, .., 4096, 4097, 4098, 4099, 4100..32767, 32768..65535} // -// Values={Completed with No Error, Not Supported, Unknown or Unspecified Error, Cannot complete within Timeout Period, Failed, Invalid Parameter, In Use, DMTF Reserved, Method Parameters Checked - Job Started, Invalid State Transition, Use of Timeout Parameter Not Supported, Busy, Method Reserved, Vendor Specific} +// Values={Completed with No Error, Not Supported, Unknown or Unspecified Error, Cannot complete within Timeout Period, Failed, Invalid Parameter, In Use, DMTF Reserved, Method Parameters Checked - Job Started, Invalid State Transition, Use of Timeout Parameter Not Supported, Busy, Method Reserved, Vendor Specific}. func (service Service) RequestStateChange(requestedState RequestedState) (response Response, err error) { response = Response{ Message: &client.Message{ - XMLInput: service.base.RequestStateChange(methods.RequestStateChange(AMT_UserInitiatedConnectionService), int(requestedState)), + XMLInput: service.base.RequestStateChange(methods.RequestStateChange(AMTUserInitiatedConnectionService), int(requestedState)), }, } // send the message to AMT @@ -114,6 +117,6 @@ func (service Service) RequestStateChange(requestedState RequestedState) (respon if err != nil { return } - return + return } diff --git a/pkg/wsman/amt/userinitiatedconnection/service_test.go b/pkg/wsman/amt/userinitiatedconnection/service_test.go index ed18d3d7..497da41e 100644 --- a/pkg/wsman/amt/userinitiatedconnection/service_test.go +++ b/pkg/wsman/amt/userinitiatedconnection/service_test.go @@ -10,11 +10,10 @@ import ( "fmt" "testing" - "github.com/stretchr/testify/assert" - "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/internal/message" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/common" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/wsmantesting" + "github.com/stretchr/testify/assert" ) func TestJson(t *testing.T) { @@ -23,7 +22,7 @@ func TestJson(t *testing.T) { GetResponse: UserResponse{}, }, } - expectedResult := "{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"RequestStateChange_OUTPUT\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"ReturnValue\":0},\"GetResponse\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"CreationClassName\":\"\",\"ElementName\":\"\",\"EnabledState\":0,\"Name\":\"\",\"SystemCreationClassName\":\"\",\"SystemName\":\"\"},\"EnumerateResponse\":{\"EnumerationContext\":\"\"},\"PullResponse\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"UserItems\":null}}" + expectedResult := "{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"RequestStateChangeOutput\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"ReturnValue\":0},\"GetResponse\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"CreationClassName\":\"\",\"ElementName\":\"\",\"EnabledState\":0,\"Name\":\"\",\"SystemCreationClassName\":\"\",\"SystemName\":\"\"},\"EnumerateResponse\":{\"EnumerationContext\":\"\"},\"PullResponse\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"UserItems\":null}}" result := response.JSON() assert.Equal(t, expectedResult, result) } @@ -34,19 +33,20 @@ func TestYaml(t *testing.T) { GetResponse: UserResponse{}, }, } - expectedResult := "xmlname:\n space: \"\"\n local: \"\"\nrequeststatechange_output:\n xmlname:\n space: \"\"\n local: \"\"\n returnvalue: 0\ngetresponse:\n xmlname:\n space: \"\"\n local: \"\"\n creationclassname: \"\"\n elementname: \"\"\n enabledstate: 0\n name: \"\"\n systemcreationclassname: \"\"\n systemname: \"\"\nenumerateresponse:\n enumerationcontext: \"\"\npullresponse:\n xmlname:\n space: \"\"\n local: \"\"\n useritems: []\n" + expectedResult := "xmlname:\n space: \"\"\n local: \"\"\nrequeststatechangeoutput:\n xmlname:\n space: \"\"\n local: \"\"\n returnvalue: 0\ngetresponse:\n xmlname:\n space: \"\"\n local: \"\"\n creationclassname: \"\"\n elementname: \"\"\n enabledstate: 0\n name: \"\"\n systemcreationclassname: \"\"\n systemname: \"\"\nenumerateresponse:\n enumerationcontext: \"\"\npullresponse:\n xmlname:\n space: \"\"\n local: \"\"\n useritems: []\n" result := response.YAML() assert.Equal(t, expectedResult, result) } func TestPositiveAMT_UserInitiatedConnectionService(t *testing.T) { messageID := 0 - resourceUriBase := "http://intel.com/wbem/wscim/1/amt-schema/1/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.AMTResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "amt/userinitiatedconnection", } elementUnderTest := NewUserInitiatedConnectionServiceWithClient(wsmanMessageCreator, &client) + t.Run("amt_UserInitiatedConnectionService Tests", func(t *testing.T) { tests := []struct { name string @@ -56,21 +56,22 @@ func TestPositiveAMT_UserInitiatedConnectionService(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //GETS + // GETS { "should create a valid AMT_UserInitiatedConnectionService Get wsman message", - AMT_UserInitiatedConnectionService, - wsmantesting.GET, + AMTUserInitiatedConnectionService, + wsmantesting.Get, "", func() (Response, error) { - client.CurrentMessage = "Get" + client.CurrentMessage = wsmantesting.CurrentMessageGet + return elementUnderTest.Get() }, Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, GetResponse: UserResponse{ - XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMT_UserInitiatedConnectionService), Local: AMT_UserInitiatedConnectionService}, - CreationClassName: AMT_UserInitiatedConnectionService, + XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMTUserInitiatedConnectionService), Local: AMTUserInitiatedConnectionService}, + CreationClassName: AMTUserInitiatedConnectionService, ElementName: "Intel(r) AMT User Initiated Connection Service", EnabledState: 32771, Name: "Intel(r) AMT User Initiated Connection Service", @@ -79,14 +80,15 @@ func TestPositiveAMT_UserInitiatedConnectionService(t *testing.T) { }, }, }, - //ENUMERATES + // ENUMERATES { "should create a valid AMT_UserInitiatedConnectionService Enumerate wsman message", - AMT_UserInitiatedConnectionService, - wsmantesting.ENUMERATE, - wsmantesting.ENUMERATE_BODY, + AMTUserInitiatedConnectionService, + wsmantesting.Enumerate, + wsmantesting.EnumerateBody, func() (Response, error) { - client.CurrentMessage = "Enumerate" + client.CurrentMessage = wsmantesting.CurrentMessageEnumerate + return elementUnderTest.Enumerate() }, Body{ @@ -96,14 +98,15 @@ func TestPositiveAMT_UserInitiatedConnectionService(t *testing.T) { }, }, }, - //PULLS + // PULLS { "should create a valid AMT_UserInitiatedConnectionService Pull wsman message", - AMT_UserInitiatedConnectionService, - wsmantesting.PULL, - wsmantesting.PULL_BODY, + AMTUserInitiatedConnectionService, + wsmantesting.Pull, + wsmantesting.PullBody, func() (Response, error) { - client.CurrentMessage = "Pull" + client.CurrentMessage = wsmantesting.CurrentMessagePull + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -112,8 +115,8 @@ func TestPositiveAMT_UserInitiatedConnectionService(t *testing.T) { XMLName: xml.Name{Space: message.XMLPullResponseSpace, Local: "PullResponse"}, UserItems: []UserResponse{ { - XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMT_UserInitiatedConnectionService), Local: AMT_UserInitiatedConnectionService}, - CreationClassName: AMT_UserInitiatedConnectionService, + XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMTUserInitiatedConnectionService), Local: AMTUserInitiatedConnectionService}, + CreationClassName: AMTUserInitiatedConnectionService, ElementName: "Intel(r) AMT User Initiated Connection Service", EnabledState: 32771, Name: "Intel(r) AMT User Initiated Connection Service", @@ -124,20 +127,21 @@ func TestPositiveAMT_UserInitiatedConnectionService(t *testing.T) { }, }, }, - //REQUEST STATE CHANGE + // REQUEST STATE CHANGE { "should create a valid AMT_UserInitiatedConnectionService RequestStateChange wsman message", - AMT_UserInitiatedConnectionService, - fmt.Sprintf("%s%s/%s", message.AMTSchema, AMT_UserInitiatedConnectionService, "RequestStateChange"), + AMTUserInitiatedConnectionService, + fmt.Sprintf("%s%s/%s", message.AMTSchema, AMTUserInitiatedConnectionService, "RequestStateChange"), "32771", func() (Response, error) { client.CurrentMessage = "Request" + return elementUnderTest.RequestStateChange(32771) }, Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, RequestStateChange_OUTPUT: RequestStateChange_OUTPUT{ - XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMT_UserInitiatedConnectionService), Local: "RequestStateChange_OUTPUT"}, + XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMTUserInitiatedConnectionService), Local: "RequestStateChange_OUTPUT"}, ReturnValue: 0, }, }, @@ -146,7 +150,7 @@ func TestPositiveAMT_UserInitiatedConnectionService(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, "", test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, "", test.body) messageID++ response, err := test.responseFunc() assert.NoError(t, err) @@ -156,14 +160,16 @@ func TestPositiveAMT_UserInitiatedConnectionService(t *testing.T) { } }) } + func TestNegativeAMT_UserInitiatedConnectionService(t *testing.T) { messageID := 0 - resourceUriBase := "http://intel.com/wbem/wscim/1/amt-schema/1/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.AMTResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "amt/userinitiatedconnection", } elementUnderTest := NewUserInitiatedConnectionServiceWithClient(wsmanMessageCreator, &client) + t.Run("amt_UserInitiatedConnectionService Tests", func(t *testing.T) { tests := []struct { name string @@ -173,21 +179,22 @@ func TestNegativeAMT_UserInitiatedConnectionService(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //GETS + // GETS { "should create a valid AMT_UserInitiatedConnectionService Get wsman message", - AMT_UserInitiatedConnectionService, - wsmantesting.GET, + AMTUserInitiatedConnectionService, + wsmantesting.Get, "", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Get() }, Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, GetResponse: UserResponse{ - XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMT_UserInitiatedConnectionService), Local: AMT_UserInitiatedConnectionService}, - CreationClassName: AMT_UserInitiatedConnectionService, + XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMTUserInitiatedConnectionService), Local: AMTUserInitiatedConnectionService}, + CreationClassName: AMTUserInitiatedConnectionService, ElementName: "Intel(r) AMT User Initiated Connection Service", EnabledState: 32771, Name: "Intel(r) AMT User Initiated Connection Service", @@ -196,14 +203,15 @@ func TestNegativeAMT_UserInitiatedConnectionService(t *testing.T) { }, }, }, - //ENUMERATES + // ENUMERATES { "should create a valid AMT_UserInitiatedConnectionService Enumerate wsman message", - AMT_UserInitiatedConnectionService, - wsmantesting.ENUMERATE, - wsmantesting.ENUMERATE_BODY, + AMTUserInitiatedConnectionService, + wsmantesting.Enumerate, + wsmantesting.EnumerateBody, func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Enumerate() }, Body{ @@ -213,14 +221,15 @@ func TestNegativeAMT_UserInitiatedConnectionService(t *testing.T) { }, }, }, - //PULLS + // PULLS { "should create a valid AMT_UserInitiatedConnectionService Pull wsman message", - AMT_UserInitiatedConnectionService, - wsmantesting.PULL, - wsmantesting.PULL_BODY, + AMTUserInitiatedConnectionService, + wsmantesting.Pull, + wsmantesting.PullBody, func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -229,8 +238,8 @@ func TestNegativeAMT_UserInitiatedConnectionService(t *testing.T) { XMLName: xml.Name{Space: message.XMLPullResponseSpace, Local: "PullResponse"}, UserItems: []UserResponse{ { - XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMT_UserInitiatedConnectionService), Local: AMT_UserInitiatedConnectionService}, - CreationClassName: AMT_UserInitiatedConnectionService, + XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMTUserInitiatedConnectionService), Local: AMTUserInitiatedConnectionService}, + CreationClassName: AMTUserInitiatedConnectionService, ElementName: "Intel(r) AMT User Initiated Connection Service", EnabledState: 32771, Name: "Intel(r) AMT User Initiated Connection Service", @@ -241,20 +250,21 @@ func TestNegativeAMT_UserInitiatedConnectionService(t *testing.T) { }, }, }, - //REQUEST STATE CHANGE + // REQUEST STATE CHANGE { "should create a valid AMT_UserInitiatedConnectionService RequestStateChange wsman message", - AMT_UserInitiatedConnectionService, - fmt.Sprintf("%s%s/%s", message.AMTSchema, AMT_UserInitiatedConnectionService, "RequestStateChange"), + AMTUserInitiatedConnectionService, + fmt.Sprintf("%s%s/%s", message.AMTSchema, AMTUserInitiatedConnectionService, "RequestStateChange"), "32771", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.RequestStateChange(32771) }, Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, RequestStateChange_OUTPUT: RequestStateChange_OUTPUT{ - XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMT_UserInitiatedConnectionService), Local: "RequestStateChange_OUTPUT"}, + XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMTUserInitiatedConnectionService), Local: "RequestStateChange_OUTPUT"}, ReturnValue: 0, }, }, @@ -263,7 +273,7 @@ func TestNegativeAMT_UserInitiatedConnectionService(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, "", test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, "", test.body) messageID++ response, err := test.responseFunc() assert.Error(t, err) diff --git a/pkg/wsman/amt/userinitiatedconnection/types.go b/pkg/wsman/amt/userinitiatedconnection/types.go index f44fa06e..8afc9861 100644 --- a/pkg/wsman/amt/userinitiatedconnection/types.go +++ b/pkg/wsman/amt/userinitiatedconnection/types.go @@ -21,7 +21,7 @@ type Service struct { // // ValueMap={32768, 32769, 32770, 32771} // -// Values={All Interfaces disabled, BIOS Interface enabled, OS Interface enabled, BIOS and OS Interfaces enabled} +// Values={All Interfaces disabled, BIOS Interface enabled, OS Interface enabled, BIOS and OS Interfaces enabled}. type RequestedState int // EnabledState is an integer enumeration that indicates the enabled and disabled states of an element. @@ -31,7 +31,7 @@ type EnabledState int type ReturnValue int // OUTPUTS -// Response Types +// Response Types. type ( Response struct { *client.Message diff --git a/pkg/wsman/amt/wifiportconfiguration/decoder.go b/pkg/wsman/amt/wifiportconfiguration/decoder.go index 7d3e54cd..47e4fb17 100644 --- a/pkg/wsman/amt/wifiportconfiguration/decoder.go +++ b/pkg/wsman/amt/wifiportconfiguration/decoder.go @@ -8,8 +8,9 @@ package wifiportconfiguration // INPUTS constants const ( - AMT_WiFiPortConfigurationService string = "AMT_WiFiPortConfigurationService" - AddWiFiSettings string = "AddWiFiSettings" + AMTWiFiPortConfigurationService string = "AMT_WiFiPortConfigurationService" + AddWiFiSettings string = "AddWiFiSettings" + ValueNotFound string = "Value not found in map" ) const ( @@ -18,19 +19,19 @@ const ( Reserved ) -// noHostCsmeSoftwarePolicyToString is a map of NoHostCsmeSoftwarePolicy values to their string representations +// noHostCsmeSoftwarePolicyToString is a map of NoHostCsmeSoftwarePolicy values to their string representations. var noHostCsmeSoftwarePolicyToString = map[NoHostCsmeSoftwarePolicy]string{ RelaxedPolicy: "RelaxedPolicy", AggressivePolicy: "AggressivePolicy", } -// String returns the string representation of the NoHostCsmeSoftwarePolicy value +// String returns the string representation of the NoHostCsmeSoftwarePolicy value. func (n NoHostCsmeSoftwarePolicy) String() string { if value, exists := noHostCsmeSoftwarePolicyToString[n]; exists { return value } - return "Value not found in map" + return ValueNotFound } const ( @@ -43,7 +44,7 @@ const ( HealthStateNonRecoverableError HealthState = 30 ) -// healthStateToString is a map of HealthState values to their string representations +// healthStateToString is a map of HealthState values to their string representations. var healthStateToString = map[HealthState]string{ HealthStateUnknown: "HealthStateUnknown", HealthStateOK: "HealthStateOK", @@ -54,12 +55,13 @@ var healthStateToString = map[HealthState]string{ HealthStateNonRecoverableError: "HealthStateNonRecoverableError", } -// String returns the string representation of the HealthState value +// String returns the string representation of the HealthState value. func (h HealthState) String() string { if value, exists := healthStateToString[h]; exists { return value } - return "Value not found in map" + + return ValueNotFound } const ( @@ -76,7 +78,7 @@ const ( EnabledStateStarting ) -// enabledStateToString is a map of EnabledState values to their string representations +// enabledStateToString is a map of EnabledState values to their string representations. var enabledStateToString = map[EnabledState]string{ EnabledStateUnknown: "EnabledStateUnknown", EnabledStateOther: "EnabledStateOther", @@ -91,12 +93,13 @@ var enabledStateToString = map[EnabledState]string{ EnabledStateStarting: "EnabledStateStarting", } -// String returns the string representation of the EnabledState value +// String returns the string representation of the EnabledState value. func (e EnabledState) String() string { if value, exists := enabledStateToString[e]; exists { return value } - return "Value not found in map" + + return ValueNotFound } const ( @@ -114,7 +117,7 @@ const ( RequestedStateUnknown RequestedState = 0 ) -// requestedStateToString is a map of RequestedState values to their string representations +// requestedStateToString is a map of RequestedState values to their string representations. var requestedStateToString = map[RequestedState]string{ RequestedStateEnabled: "RequestedStateEnabled", RequestedStateDisabled: "RequestedStateDisabled", @@ -130,12 +133,13 @@ var requestedStateToString = map[RequestedState]string{ RequestedStateUnknown: "RequestedStateUnknown", } -// String returns the string representation of the RequestedState value +// String returns the string representation of the RequestedState value. func (r RequestedState) String() string { if value, exists := requestedStateToString[r]; exists { return value } - return "Value not found in map" + + return ValueNotFound } const ( @@ -144,19 +148,20 @@ const ( UnrestrictedSync LocalProfileSynchronizationEnabled = 3 ) -// localProfileSynchronizationEnabledToString is a map of LocalProfileSynchronizationEnabled to string +// localProfileSynchronizationEnabledToString is a map of LocalProfileSynchronizationEnabled to string. var localProfileSynchronizationEnabledToString = map[LocalProfileSynchronizationEnabled]string{ LocalSyncDisabled: "LocalSyncDisabled", LocalUserProfileSynchronizationEnabled: "LocalUserProfileSynchronizationEnabled", UnrestrictedSync: "UnrestrictedSync", } -// String returns the string representation of the LocalProfileSynchronizationEnabled value +// String returns the string representation of the LocalProfileSynchronizationEnabled value. func (l LocalProfileSynchronizationEnabled) String() string { if value, exists := localProfileSynchronizationEnabledToString[l]; exists { return value } - return "Value not found in map" + + return ValueNotFound } const ( @@ -167,7 +172,7 @@ const ( ReturnValueInvalidReference ) -// returnValueToString is a map of ReturnValue values to their string representations +// returnValueToString is a map of ReturnValue values to their string representations. var returnValueToString = map[ReturnValue]string{ ReturnValueCompletedNoError: "ReturnValueCompletedNoError", ReturnValueNotSupported: "ReturnValueNotSupported", @@ -176,10 +181,11 @@ var returnValueToString = map[ReturnValue]string{ ReturnValueInvalidReference: "ReturnValueInvalidReference", } -// String returns the string representation of the ReturnValue value +// String returns the string representation of the ReturnValue value. func (r ReturnValue) String() string { if value, exists := returnValueToString[r]; exists { return value } - return "Value not found in map" + + return ValueNotFound } diff --git a/pkg/wsman/amt/wifiportconfiguration/marshal.go b/pkg/wsman/amt/wifiportconfiguration/marshal.go index c8d6249d..8cc9d70a 100644 --- a/pkg/wsman/amt/wifiportconfiguration/marshal.go +++ b/pkg/wsman/amt/wifiportconfiguration/marshal.go @@ -11,20 +11,22 @@ import ( "gopkg.in/yaml.v3" ) -// JSON marshals the type into JSON format +// JSON marshals the type into JSON format. func (r *Response) JSON() string { jsonOutput, err := json.Marshal(r.Body) if err != nil { return "" } + return string(jsonOutput) } -// YAML marshals the type into YAML format +// YAML marshals the type into YAML format. func (r *Response) YAML() string { yamlOutput, err := yaml.Marshal(r.Body) if err != nil { return "" } + return string(yamlOutput) } diff --git a/pkg/wsman/amt/wifiportconfiguration/service.go b/pkg/wsman/amt/wifiportconfiguration/service.go index 294a8f6d..b23c140a 100644 --- a/pkg/wsman/amt/wifiportconfiguration/service.go +++ b/pkg/wsman/amt/wifiportconfiguration/service.go @@ -18,51 +18,57 @@ import ( "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/client" ) -// NewWiFiPortConfigurationServiceWithClient instantiates a new Service +// NewWiFiPortConfigurationServiceWithClient instantiates a new Service. func NewWiFiPortConfigurationServiceWithClient(wsmanMessageCreator *message.WSManMessageCreator, client client.WSMan) Service { return Service{ - base: message.NewBaseWithClient(wsmanMessageCreator, AMT_WiFiPortConfigurationService, client), + base: message.NewBaseWithClient(wsmanMessageCreator, AMTWiFiPortConfigurationService, client), } } -// Get retrieves the representation of the instance +// Get retrieves the representation of the instance. func (service Service) Get() (response Response, err error) { response = Response{ Message: &client.Message{ XMLInput: service.base.Get(nil), }, } + // send the message to AMT err = service.base.Execute(response.Message) if err != nil { - return + return response, err } + // put the xml response into the go struct err = xml.Unmarshal([]byte(response.XMLOutput), &response) if err != nil { - return + return response, err } - return + + return response, err } -// Enumerate returns an enumeration context which is used in a subsequent Pull call +// Enumerate returns an enumeration context which is used in a subsequent Pull call. func (service Service) Enumerate() (response Response, err error) { response = Response{ Message: &client.Message{ XMLInput: service.base.Enumerate(), }, } + // send the message to AMT err = service.base.Execute(response.Message) if err != nil { - return + return response, err } + // put the xml response into the go struct err = xml.Unmarshal([]byte(response.XMLOutput), &response) if err != nil { - return + return response, err } - return + + return response, err } // Pull returns the instances of this class. An enumeration context provided by the Enumerate call is used as input. @@ -72,43 +78,49 @@ func (service Service) Pull(enumerationContext string) (response Response, err e XMLInput: service.base.Pull(enumerationContext), }, } + // send the message to AMT err = service.base.Execute(response.Message) if err != nil { - return + return response, err } + // put the xml response into the go struct err = xml.Unmarshal([]byte(response.XMLOutput), &response) if err != nil { - return + return response, err } - return + + return response, err } -// Put will change properties of the selected instance +// Put will change properties of the selected instance. func (service Service) Put(wiFiPortConfigurationService WiFiPortConfigurationServiceRequest) (response Response, err error) { - //wiFiPortConfigurationService.XMLSchema = "http://intel.com/wbem/wscim/1/amt-schema/1/AMT_WiFiPortConfigurationService" - wiFiPortConfigurationService.H = fmt.Sprintf("%s%s", message.AMTSchema, AMT_WiFiPortConfigurationService) + // wiFiPortConfigurationService.XMLSchema = "http://intel.com/wbem/wscim/1/amt-schema/1/AMT_WiFiPortConfigurationService" + wiFiPortConfigurationService.H = fmt.Sprintf("%s%s", message.AMTSchema, AMTWiFiPortConfigurationService) response = Response{ Message: &client.Message{ XMLInput: service.base.Put(wiFiPortConfigurationService, false, nil), }, } + // send the message to AMT err = service.base.Execute(response.Message) if err != nil { - return + return response, err } + // put the xml response into the go struct err = xml.Unmarshal([]byte(response.XMLOutput), &response) if err != nil { - return + return response, err } if response.Body.WiFiPortConfigurationService.LocalProfileSynchronizationEnabled == 0 { err = errors.New("failed to enable wifi local profile synchronization") } - return + + return response, err } // AddWiFiSettings atomically creates an instance of CIM_WifiEndpointSettings from the embedded instance parameter @@ -127,15 +139,15 @@ func (service Service) Put(wiFiPortConfigurationService WiFiPortConfigurationSer // // ValueMap={0, 1, 2, 3, 4, .., 32768..65535} // -// Values={Completed with No Error, Not Supported, Failed, Invalid Parameter, Invalid Reference, Method Reserved, Vendor Specific} +// Values={Completed with No Error, Not Supported, Failed, Invalid Parameter, Invalid Reference, Method Reserved, Vendor Specific}. func (service Service) AddWiFiSettings(wifiEndpointSettings wifi.WiFiEndpointSettingsRequest, ieee8021xSettingsInput models.IEEE8021xSettings, wifiEndpoint, clientCredential, caCredential string) (response Response, err error) { - header := service.base.WSManMessageCreator.CreateHeader(methods.GenerateAction(AMT_WiFiPortConfigurationService, AddWiFiSettings), AMT_WiFiPortConfigurationService, nil, "", "") + header := service.base.WSManMessageCreator.CreateHeader(methods.GenerateAction(AMTWiFiPortConfigurationService, AddWiFiSettings), AMTWiFiPortConfigurationService, nil, "", "") input := AddWiFiSettings_INPUT{ WifiEndpoint: WiFiEndpoint{ Address: "/wsman", ReferenceParameters: ReferenceParameters{ H: "http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd", - ResourceURI: fmt.Sprintf("%s%s", message.CIMSchema, wifi.CIM_WiFiEndpoint), + ResourceURI: fmt.Sprintf("%s%s", message.CIMSchema, wifi.CIMWiFiEndpoint), SelectorSet: SelectorSet{ H: "http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd", Selector: []Selector{ @@ -150,11 +162,14 @@ func (service Service) AddWiFiSettings(wifiEndpointSettings wifi.WiFiEndpointSet }, WiFiEndpointSettings: wifiEndpointSettings, } + input.WiFiEndpointSettings.H = "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_WiFiEndpointSettings" + if wifiEndpointSettings.AuthenticationMethod == wifi.AuthenticationMethodWPAIEEE8021x || wifiEndpointSettings.AuthenticationMethod == wifi.AuthenticationMethodWPA2IEEE8021x { input.IEEE8021xSettings = &ieee8021xSettingsInput input.IEEE8021xSettings.H = "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_IEEE8021xSettings" + input.CACredential = &CACredentialRequest{ H: "http://schemas.xmlsoap.org/ws/2004/08/addressing", Address: "default", @@ -173,6 +188,7 @@ func (service Service) AddWiFiSettings(wifiEndpointSettings wifi.WiFiEndpointSet }, }, } + if clientCredential != "" { input.ClientCredential = &ClientCredentialRequest{ H: "http://schemas.xmlsoap.org/ws/2004/08/addressing", @@ -195,27 +211,37 @@ func (service Service) AddWiFiSettings(wifiEndpointSettings wifi.WiFiEndpointSet } } - body := service.base.WSManMessageCreator.CreateBody(methods.GenerateInputMethod(AddWiFiSettings), AMT_WiFiPortConfigurationService, &input) + body := service.base.WSManMessageCreator.CreateBody(methods.GenerateInputMethod(AddWiFiSettings), AMTWiFiPortConfigurationService, &input) response = Response{ Message: &client.Message{ XMLInput: service.base.WSManMessageCreator.CreateXML(header, body), }, } + // send the message to AMT err = service.base.Execute(response.Message) if err != nil { - return + return response, err } + // put the xml response into the go struct err = xml.Unmarshal([]byte(response.XMLOutput), &response) if err != nil { - return + return response, err } - if response.Body.AddWiFiSettings_OUTPUT.ReturnValue != 0 { - err = fmt.Errorf("AddWiFiSettings_OUTPUT.ReturnValue: %d", response.Body.AddWiFiSettings_OUTPUT.ReturnValue) + + if response.Body.AddWiFiSettingsOutput.ReturnValue != 0 { + err = generateErrorMessage("addwifisettings", response.Body.AddWiFiSettingsOutput.ReturnValue) } - return + return response, err +} + +// generateErrorMessage returns an error message based on the return value. +func generateErrorMessage(call string, returnValue ReturnValue) error { + ErrCallFailure := errors.New(call + " failed") + + return fmt.Errorf("%w: returned %d", ErrCallFailure, returnValue) } // TODO: Add UpdateWiFiSettings diff --git a/pkg/wsman/amt/wifiportconfiguration/service_test.go b/pkg/wsman/amt/wifiportconfiguration/service_test.go index 6811a5dd..9bd65f54 100644 --- a/pkg/wsman/amt/wifiportconfiguration/service_test.go +++ b/pkg/wsman/amt/wifiportconfiguration/service_test.go @@ -10,11 +10,10 @@ import ( "fmt" "testing" - "github.com/stretchr/testify/assert" - "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/internal/message" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/common" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/wsmantesting" + "github.com/stretchr/testify/assert" ) func TestJson(t *testing.T) { @@ -23,7 +22,7 @@ func TestJson(t *testing.T) { WiFiPortConfigurationService: WiFiPortConfigurationServiceResponse{}, }, } - expectedResult := "{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"WiFiPortConfigurationService\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"RequestedState\":0,\"EnabledState\":0,\"HealthState\":0,\"ElementName\":\"\",\"SystemCreationClassName\":\"\",\"SystemName\":\"\",\"CreationClassName\":\"\",\"Name\":\"\",\"LocalProfileSynchronizationEnabled\":0,\"LastConnectedSsidUnderMeControl\":\"\",\"NoHostCsmeSoftwarePolicy\":0,\"UEFIWiFiProfileShareEnabled\":false},\"PullResponse\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"WiFiPortConfigurationItems\":null},\"EnumerateResponse\":{\"EnumerationContext\":\"\"},\"AddWiFiSettings_OUTPUT\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"ReturnValue\":0}}" + expectedResult := "{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"WiFiPortConfigurationService\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"RequestedState\":0,\"EnabledState\":0,\"HealthState\":0,\"ElementName\":\"\",\"SystemCreationClassName\":\"\",\"SystemName\":\"\",\"CreationClassName\":\"\",\"Name\":\"\",\"LocalProfileSynchronizationEnabled\":0,\"LastConnectedSsidUnderMeControl\":\"\",\"NoHostCsmeSoftwarePolicy\":0,\"UEFIWiFiProfileShareEnabled\":false},\"PullResponse\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"WiFiPortConfigurationItems\":null},\"EnumerateResponse\":{\"EnumerationContext\":\"\"},\"AddWiFiSettingsOutput\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"ReturnValue\":0}}" result := response.JSON() assert.Equal(t, expectedResult, result) } @@ -34,15 +33,15 @@ func TestYaml(t *testing.T) { WiFiPortConfigurationService: WiFiPortConfigurationServiceResponse{}, }, } - expectedResult := "xmlname:\n space: \"\"\n local: \"\"\nwifiportconfigurationservice:\n xmlname:\n space: \"\"\n local: \"\"\n requestedstate: 0\n enabledstate: 0\n healthstate: 0\n elementname: \"\"\n systemcreationclassname: \"\"\n systemname: \"\"\n creationclassname: \"\"\n name: \"\"\n localprofilesynchronizationenabled: 0\n lastconnectedssidundermecontrol: \"\"\n nohostcsmesoftwarepolicy: 0\n uefiwifiprofileshareenabled: false\npullresponse:\n xmlname:\n space: \"\"\n local: \"\"\n wifiportconfigurationitems: []\nenumerateresponse:\n enumerationcontext: \"\"\naddwifisettings_output:\n xmlname:\n space: \"\"\n local: \"\"\n returnvalue: 0\n" + expectedResult := "xmlname:\n space: \"\"\n local: \"\"\nwifiportconfigurationservice:\n xmlname:\n space: \"\"\n local: \"\"\n requestedstate: 0\n enabledstate: 0\n healthstate: 0\n elementname: \"\"\n systemcreationclassname: \"\"\n systemname: \"\"\n creationclassname: \"\"\n name: \"\"\n localprofilesynchronizationenabled: 0\n lastconnectedssidundermecontrol: \"\"\n nohostcsmesoftwarepolicy: 0\n uefiwifiprofileshareenabled: false\npullresponse:\n xmlname:\n space: \"\"\n local: \"\"\n wifiportconfigurationitems: []\nenumerateresponse:\n enumerationcontext: \"\"\naddwifisettingsoutput:\n xmlname:\n space: \"\"\n local: \"\"\n returnvalue: 0\n" result := response.YAML() assert.Equal(t, expectedResult, result) } func TestPositiveAMT_WiFiPortConfigurationService(t *testing.T) { messageID := 0 - resourceUriBase := "http://intel.com/wbem/wscim/1/amt-schema/1/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.AMTResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "amt/wifiportconfiguration", } @@ -58,21 +57,22 @@ func TestPositiveAMT_WiFiPortConfigurationService(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //GETS + // GETS { "should create a valid AMT_WiFiPortConfigurationService Get wsman message", - AMT_WiFiPortConfigurationService, - wsmantesting.GET, + AMTWiFiPortConfigurationService, + wsmantesting.Get, "", "", func() (Response, error) { - client.CurrentMessage = "Get" + client.CurrentMessage = wsmantesting.CurrentMessageGet + return elementUnderTest.Get() }, Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, WiFiPortConfigurationService: WiFiPortConfigurationServiceResponse{ - XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMT_WiFiPortConfigurationService), Local: AMT_WiFiPortConfigurationService}, + XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMTWiFiPortConfigurationService), Local: AMTWiFiPortConfigurationService}, CreationClassName: "AMT_WiFiPortConfigurationService", ElementName: "Intel(r) AMT WiFiPort Configuration Service", EnabledState: 5, @@ -87,15 +87,16 @@ func TestPositiveAMT_WiFiPortConfigurationService(t *testing.T) { }, }, }, - //ENUMERATES + // ENUMERATES { "should create a valid AMT_WiFiPortConfigurationService Enumerate wsman message", - AMT_WiFiPortConfigurationService, - wsmantesting.ENUMERATE, - wsmantesting.ENUMERATE_BODY, + AMTWiFiPortConfigurationService, + wsmantesting.Enumerate, + wsmantesting.EnumerateBody, "", func() (Response, error) { - client.CurrentMessage = "Enumerate" + client.CurrentMessage = wsmantesting.CurrentMessageEnumerate + return elementUnderTest.Enumerate() }, Body{ @@ -105,15 +106,16 @@ func TestPositiveAMT_WiFiPortConfigurationService(t *testing.T) { }, }, }, - //PULLS + // PULLS { "should create a valid AMT_WiFiPortConfigurationService Pull wsman message", - AMT_WiFiPortConfigurationService, - wsmantesting.PULL, - wsmantesting.PULL_BODY, + AMTWiFiPortConfigurationService, + wsmantesting.Pull, + wsmantesting.PullBody, "", func() (Response, error) { - client.CurrentMessage = "Pull" + client.CurrentMessage = wsmantesting.CurrentMessagePull + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -122,7 +124,7 @@ func TestPositiveAMT_WiFiPortConfigurationService(t *testing.T) { XMLName: xml.Name{Space: message.XMLPullResponseSpace, Local: "PullResponse"}, WiFiPortConfigurationItems: []WiFiPortConfigurationServiceResponse{ { - XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMT_WiFiPortConfigurationService), Local: AMT_WiFiPortConfigurationService}, + XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMTWiFiPortConfigurationService), Local: AMTWiFiPortConfigurationService}, CreationClassName: "AMT_WiFiPortConfigurationService", ElementName: "Intel(r) AMT WiFiPort Configuration Service", EnabledState: 5, @@ -142,12 +144,12 @@ func TestPositiveAMT_WiFiPortConfigurationService(t *testing.T) { // PUTS { "should create a valid AMT_WiFiPortConfigurationService Put wsman message", - AMT_WiFiPortConfigurationService, - wsmantesting.PUT, + AMTWiFiPortConfigurationService, + wsmantesting.Put, "1255Intel(r) AMT WiFiPort Configuration ServiceCIM_ComputerSystemIntel(r) AMTAMT_WiFiPortConfigurationServiceIntel(r) AMT WiFi Port Configuration Service1", "", func() (Response, error) { - client.CurrentMessage = "Put" + client.CurrentMessage = wsmantesting.CurrentMessagePut wifiConfiguration := WiFiPortConfigurationServiceRequest{ RequestedState: 12, EnabledState: 5, @@ -161,12 +163,13 @@ func TestPositiveAMT_WiFiPortConfigurationService(t *testing.T) { LastConnectedSsidUnderMeControl: "", NoHostCsmeSoftwarePolicy: 0, } + return elementUnderTest.Put(wifiConfiguration) }, Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, WiFiPortConfigurationService: WiFiPortConfigurationServiceResponse{ - XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMT_WiFiPortConfigurationService), Local: AMT_WiFiPortConfigurationService}, + XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.AMTSchema, AMTWiFiPortConfigurationService), Local: AMTWiFiPortConfigurationService}, CreationClassName: "AMT_WiFiPortConfigurationService", ElementName: "Intel(r) AMT WiFiPort Configuration Service", EnabledState: 5, @@ -202,7 +205,7 @@ func TestPositiveAMT_WiFiPortConfigurationService(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, test.extraHeader, test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, test.extraHeader, test.body) messageID++ response, err := test.responseFunc() assert.NoError(t, err) diff --git a/pkg/wsman/amt/wifiportconfiguration/types.go b/pkg/wsman/amt/wifiportconfiguration/types.go index 811ed8e6..d1547dcb 100644 --- a/pkg/wsman/amt/wifiportconfiguration/types.go +++ b/pkg/wsman/amt/wifiportconfiguration/types.go @@ -20,7 +20,7 @@ type Service struct { } // OUTPUT -// Response Types +// Response Types. type ( Response struct { *client.Message @@ -34,7 +34,7 @@ type ( WiFiPortConfigurationService WiFiPortConfigurationServiceResponse PullResponse PullResponse EnumerateResponse common.EnumerateResponse - AddWiFiSettings_OUTPUT AddWiFiSettings_OUTPUT + AddWiFiSettingsOutput AddWiFiSettings_OUTPUT } WiFiPortConfigurationServiceResponse struct { XMLName xml.Name `xml:"AMT_WiFiPortConfigurationService"` @@ -58,13 +58,13 @@ type ( // ValueMap={0, 1, 2, 3, 4, .., 32768..65535} // - // Values={Completed with No Error, Not Supported, Failed, Invalid Parameter, Invalid Reference, Method Reserved, Vendor Specific} + // Values={Completed with No Error, Not Supported, Failed, Invalid Parameter, Invalid Reference, Method Reserved, Vendor Specific}. AddWiFiSettings_OUTPUT struct { XMLName xml.Name `xml:"AddWiFiSettings_OUTPUT"` // not concerned with these entries on OUTPUT - //IEEE8021xSettings *models.IEEE8021xSettings `xml:"g:IEEE8021xSettingsInput,omitempty"` - //ClientCredential *ClientCredential `xml:"g:ClientCredential,omitempty"` - //CACredential *CACredential `xml:"g:CACredential,omitempty"` + + // ClientCredential *ClientCredential `xml:"g:ClientCredential,omitempty"` + // CACredential *CACredential `xml:"g:CACredential,omitempty"` ReturnValue ReturnValue `xml:"ReturnValue"` } ) @@ -76,13 +76,13 @@ type ( // // ValueMap={0, 1, 2, 3, 4..} // - // Values={Local synchronization disabled, Local user profile synchronization enabled, Vendor Reserved, Unrestricted synchronization, Reserved} + // Values={Local synchronization disabled, Local user profile synchronization enabled, Vendor Reserved, Unrestricted synchronization, Reserved}. LocalProfileSynchronizationEnabled int // Setting Policy regarding no HOST CSME software. // // ValueMap={0, 1, 2} // - // Values={NoHostCsmeSoftwareRelaxedPolicy, NoHostCsmeSoftwareAggressivePolicy, Reserved} + // Values={NoHostCsmeSoftwareRelaxedPolicy, NoHostCsmeSoftwareAggressivePolicy, Reserved}. NoHostCsmeSoftwarePolicy int // RequestedState is an integer enumeration that indicates the last requested or desired state for the element, irrespective of the mechanism through which it was requested. The actual state of the element is represented by EnabledState. This property is provided to compare the last requested and current enabled or disabled states. Note that when EnabledState is set to 5 ("Not Applicable"), then this property has no meaning. Refer to the EnabledState property description for explanations of the values in the RequestedState enumeration. // @@ -98,7 +98,7 @@ type ( // // ValueMap={0, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, .., 32768..65535} // - // Values={Unknown, Enabled, Disabled, Shut Down, No Change, Offline, Test, Deferred, Quiesce, Reboot, Reset, Not Applicable, DMTF Reserved, Vendor Reserved} + // Values={Unknown, Enabled, Disabled, Shut Down, No Change, Offline, Test, Deferred, Quiesce, Reboot, Reset, Not Applicable, DMTF Reserved, Vendor Reserved}. RequestedState int // EnabledState is an integer enumeration that indicates the enabled and disabled states of an element. It can also indicate the transitions between these requested states. For example, shutting down (value=4) and starting (value=10) are transient states between enabled and disabled. The following text briefly summarizes the various enabled and disabled states: // @@ -122,7 +122,7 @@ type ( // // ValueMap={0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11..32767, 32768..65535} // - // Values={Unknown, Other, Enabled, Disabled, Shutting Down, Not Applicable, Enabled but Offline, In Test, Deferred, Quiesce, Starting, DMTF Reserved, Vendor Reserved} + // Values={Unknown, Other, Enabled, Disabled, Shutting Down, Not Applicable, Enabled but Offline, In Test, Deferred, Quiesce, Starting, DMTF Reserved, Vendor Reserved}. EnabledState int // Indicates the current health of the element. This attribute expresses the health of this element but not necessarily that of its subcomponents. The possible values are 0 to 30, where 5 means the element is entirely healthy and 30 means the element is completely non-functional. The following continuum is defined: // @@ -144,14 +144,14 @@ type ( // // ValueMap={0, 5, 10, 15, 20, 25, 30, .., 32768..65535} // - // Values={Unknown, OK, Degraded/Warning, Minor failure, Major failure, Critical failure, Non-recoverable error, DMTF Reserved, Vendor Specific} + // Values={Unknown, OK, Degraded/Warning, Minor failure, Major failure, Critical failure, Non-recoverable error, DMTF Reserved, Vendor Specific}. HealthState int // ReturnValue is an integer enumeration that indicates the completion status of the method. This value shall be 0 if the method was completed successfully. A non-zero value indicates an error condition. ReturnValue int ) // INPUT -// Request Types +// Request Types. type ( AddWiFiSettings_INPUT struct { XMLName xml.Name `xml:"h:AddWiFiSettings_INPUT"` @@ -179,7 +179,7 @@ type ( UEFIWiFiProfileShareEnabled bool `xml:"h:UEFIWiFiProfileShareEnabled,omitempty"` // Enables or disables UEFI/CSME Wi-Fi Profile Sharing. The feature is available from Intel® CSME 16.0. The feature can be disabled even if the value of AMT_BootCapabilities.UEFIWiFiCoExistenceAndProfileShare is False. } - // a Reference to an AMT_PublicKeyCertificate, which represents the CA certificate + // a Reference to an AMT_PublicKeyCertificate, which represents the CA certificate. CACredentialRequest struct { XMLName xml.Name `xml:"h:CACredential,omitempty"` H string `xml:"xmlns:a,attr"` @@ -187,7 +187,7 @@ type ( ReferenceParameters ReferenceParameters `xml:"a:ReferenceParameters,omitempty"` } - // a Reference to an AMT_PublicKeyCertificate, which represents the client certificate + // a Reference to an AMT_PublicKeyCertificate, which represents the client certificate. ClientCredentialRequest struct { XMLName xml.Name `xml:"h:ClientCredential,omitempty"` H string `xml:"xmlns:a,attr"` @@ -216,7 +216,7 @@ type ( } ) -// The endpoint to associate the new settings with +// The endpoint to associate the new settings with. type WiFiEndpoint struct { XMLName xml.Name `xml:"h:WiFiEndpoint,omitempty"` Address string `xml:"a:Address,omitempty"` diff --git a/pkg/wsman/cim/bios/decoder.go b/pkg/wsman/cim/bios/decoder.go index c0ef7a36..be675b47 100644 --- a/pkg/wsman/cim/bios/decoder.go +++ b/pkg/wsman/cim/bios/decoder.go @@ -6,7 +6,8 @@ package bios const ( - CIM_BIOSElement string = "CIM_BIOSElement" + CIMBIOSElement string = "CIM_BIOSElement" + ValueNotFound string = "Value not found in map" ) const ( @@ -126,7 +127,7 @@ const ( MicrosoftWindowsServer8 ) -// targetOperatingSystemToString is a mapping of the TargetOperatingSystem value to a string +// targetOperatingSystemToString is a mapping of the TargetOperatingSystem value to a string. var targetOperatingSystemToString = map[TargetOperatingSystem]string{ Unknown: "Unknown", Other: "Other", @@ -244,12 +245,13 @@ var targetOperatingSystemToString = map[TargetOperatingSystem]string{ MicrosoftWindowsServer8: "MicrosoftWindowsServer8", } -// String returns the string representation of the TargetOperatingSystem value +// String returns the string representation of the TargetOperatingSystem value. func (t TargetOperatingSystem) String() string { if value, exists := targetOperatingSystemToString[t]; exists { return value } - return "Value not found in map" + + return ValueNotFound } const ( @@ -259,7 +261,7 @@ const ( SoftwareElementStateRunning ) -// SoftwareElementStateToString is a mapping of the SoftwareElementState value to a string +// SoftwareElementStateToString is a mapping of the SoftwareElementState value to a string. var SoftwareElementStateToString = map[SoftwareElementState]string{ SoftwareElementStateDeployable: "Deployable", SoftwareElementStateInstallable: "Installable", @@ -267,12 +269,13 @@ var SoftwareElementStateToString = map[SoftwareElementState]string{ SoftwareElementStateRunning: "Running", } -// String returns the string representation of the SoftwareElementState value +// String returns the string representation of the SoftwareElementState value. func (s SoftwareElementState) String() string { if value, exists := SoftwareElementStateToString[s]; exists { return value } - return "Value not found in map" + + return ValueNotFound } const ( @@ -298,7 +301,7 @@ const ( OperationalStatusRelocating ) -// operationalStatusToString is a mapping of the OperationalStatus value to a string +// operationalStatusToString is a mapping of the OperationalStatus value to a string. var operationalStatusToString = map[OperationalStatus]string{ OperationalStatusUnknown: "Unknown", OperationalStatusOther: "Other", @@ -322,10 +325,11 @@ var operationalStatusToString = map[OperationalStatus]string{ OperationalStatusRelocating: "Relocating", } -// String returns the string representation of the OperationalStatus value +// String returns the string representation of the OperationalStatus value. func (o OperationalStatus) String() string { if value, exists := operationalStatusToString[o]; exists { return value } - return "Value not found in map" + + return ValueNotFound } diff --git a/pkg/wsman/cim/bios/element.go b/pkg/wsman/cim/bios/element.go index 46b449bc..88903718 100644 --- a/pkg/wsman/cim/bios/element.go +++ b/pkg/wsman/cim/bios/element.go @@ -13,14 +13,14 @@ import ( "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/client" ) -// NewBIOSElementWithClient instantiates a new Element +// NewBIOSElementWithClient instantiates a new Element. func NewBIOSElementWithClient(wsmanMessageCreator *message.WSManMessageCreator, client client.WSMan) Element { return Element{ - base: message.NewBaseWithClient(wsmanMessageCreator, CIM_BIOSElement, client), + base: message.NewBaseWithClient(wsmanMessageCreator, CIMBIOSElement, client), } } -// Get retrieves the representation of the instance +// Get retrieves the representation of the instance. func (element Element) Get() (response Response, err error) { response = Response{ Message: &client.Message{ @@ -37,10 +37,11 @@ func (element Element) Get() (response Response, err error) { if err != nil { return } + return } -// Enumerate returns an enumeration context which is used in a subsequent Pull call +// Enumerate returns an enumeration context which is used in a subsequent Pull call. func (element Element) Enumerate() (response Response, err error) { response = Response{ Message: &client.Message{ @@ -57,6 +58,7 @@ func (element Element) Enumerate() (response Response, err error) { if err != nil { return } + return } @@ -67,13 +69,16 @@ func (element Element) Pull(enumerationContext string) (response Response, err e XMLInput: element.base.Pull(enumerationContext), }, } + err = element.base.Execute(response.Message) if err != nil { return } + err = xml.Unmarshal([]byte(response.XMLOutput), &response) if err != nil { return } + return } diff --git a/pkg/wsman/cim/bios/element_test.go b/pkg/wsman/cim/bios/element_test.go index 12637552..1559357c 100644 --- a/pkg/wsman/cim/bios/element_test.go +++ b/pkg/wsman/cim/bios/element_test.go @@ -9,11 +9,10 @@ import ( "encoding/xml" "testing" - "github.com/stretchr/testify/assert" - "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/internal/message" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/common" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/wsmantesting" + "github.com/stretchr/testify/assert" ) func TestJson(t *testing.T) { @@ -40,8 +39,8 @@ func TestYaml(t *testing.T) { func TestPositiveCIMBIOSElement(t *testing.T) { messageID := 0 - resourceUriBase := "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.CIMResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "cim/bios/element", } @@ -56,20 +55,21 @@ func TestPositiveCIMBIOSElement(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //GETS + // GETS { "should create and parse a valid cim_BIOSElement Get call", - CIM_BIOSElement, - wsmantesting.GET, + CIMBIOSElement, + wsmantesting.Get, "", func() (Response, error) { - client.CurrentMessage = "Get" + client.CurrentMessage = wsmantesting.CurrentMessageGet + return elementUnderTest.Get() }, Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, GetResponse: BiosElement{ - XMLName: xml.Name{Space: "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_BIOSElement", Local: CIM_BIOSElement}, + XMLName: xml.Name{Space: "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_BIOSElement", Local: CIMBIOSElement}, TargetOperatingSystem: 66, SoftwareElementID: "QNCFLX70.0054.2020.0810.2227", SoftwareElementState: 2, @@ -83,14 +83,15 @@ func TestPositiveCIMBIOSElement(t *testing.T) { }, }, }, - //ENUMERATES + // ENUMERATES { "should create and parse a valid cim_BIOSElement Enumerate call", - CIM_BIOSElement, - wsmantesting.ENUMERATE, - wsmantesting.ENUMERATE_BODY, + CIMBIOSElement, + wsmantesting.Enumerate, + wsmantesting.EnumerateBody, func() (Response, error) { - client.CurrentMessage = "Enumerate" + client.CurrentMessage = wsmantesting.CurrentMessageEnumerate + return elementUnderTest.Enumerate() }, Body{ @@ -100,14 +101,15 @@ func TestPositiveCIMBIOSElement(t *testing.T) { }, }, }, - //PULLS + // PULLS { "should create and parse a valid cim_BIOSElement Pull call", - CIM_BIOSElement, - wsmantesting.PULL, - wsmantesting.PULL_BODY, + CIMBIOSElement, + wsmantesting.Pull, + wsmantesting.PullBody, func() (Response, error) { - client.CurrentMessage = "Pull" + client.CurrentMessage = wsmantesting.CurrentMessagePull + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -116,7 +118,7 @@ func TestPositiveCIMBIOSElement(t *testing.T) { XMLName: xml.Name{Space: "http://schemas.xmlsoap.org/ws/2004/09/enumeration", Local: "PullResponse"}, BiosElementItems: []BiosElement{ { - XMLName: xml.Name{Space: "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_BIOSElement", Local: CIM_BIOSElement}, + XMLName: xml.Name{Space: "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_BIOSElement", Local: CIMBIOSElement}, TargetOperatingSystem: 66, SoftwareElementID: "QNCFLX70.0054.2020.0810.2227", SoftwareElementState: 2, @@ -136,7 +138,7 @@ func TestPositiveCIMBIOSElement(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, "", test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, "", test.body) messageID++ response, err := test.responseFunc() assert.NoError(t, err) @@ -149,8 +151,8 @@ func TestPositiveCIMBIOSElement(t *testing.T) { func TestNegativeCIMBIOSElement(t *testing.T) { messageID := 0 - resourceUriBase := "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.CIMResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "cim/bios/element", } @@ -165,20 +167,21 @@ func TestNegativeCIMBIOSElement(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //GETS + // GETS { "should create and parse a valid cim_BIOSElement Get call", - CIM_BIOSElement, - wsmantesting.GET, + CIMBIOSElement, + wsmantesting.Get, "", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Get() }, Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, GetResponse: BiosElement{ - XMLName: xml.Name{Space: "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_BIOSElement", Local: CIM_BIOSElement}, + XMLName: xml.Name{Space: "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_BIOSElement", Local: CIMBIOSElement}, TargetOperatingSystem: 66, SoftwareElementID: "QNCFLX70.0054.2020.0810.2227", SoftwareElementState: 2, @@ -192,14 +195,15 @@ func TestNegativeCIMBIOSElement(t *testing.T) { }, }, }, - //ENUMERATES + // ENUMERATES { "should create and parse a valid cim_BIOSElement Enumerate call", - CIM_BIOSElement, - wsmantesting.ENUMERATE, - wsmantesting.ENUMERATE_BODY, + CIMBIOSElement, + wsmantesting.Enumerate, + wsmantesting.EnumerateBody, func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Enumerate() }, Body{ @@ -209,14 +213,15 @@ func TestNegativeCIMBIOSElement(t *testing.T) { }, }, }, - //PULLS + // PULLS { "should create and parse a valid cim_BIOSElement Pull call", - CIM_BIOSElement, - wsmantesting.PULL, - wsmantesting.PULL_BODY, + CIMBIOSElement, + wsmantesting.Pull, + wsmantesting.PullBody, func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -225,7 +230,7 @@ func TestNegativeCIMBIOSElement(t *testing.T) { XMLName: xml.Name{Space: "http://schemas.xmlsoap.org/ws/2004/09/enumeration", Local: "PullResponse"}, BiosElementItems: []BiosElement{ { - XMLName: xml.Name{Space: "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_BIOSElement", Local: CIM_BIOSElement}, + XMLName: xml.Name{Space: "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_BIOSElement", Local: CIMBIOSElement}, TargetOperatingSystem: 66, SoftwareElementID: "QNCFLX70.0054.2020.0810.2227", SoftwareElementState: 2, @@ -245,7 +250,7 @@ func TestNegativeCIMBIOSElement(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, "", test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, "", test.body) messageID++ response, err := test.responseFunc() assert.Error(t, err) diff --git a/pkg/wsman/cim/bios/marshal.go b/pkg/wsman/cim/bios/marshal.go index 76284f41..d87aa826 100644 --- a/pkg/wsman/cim/bios/marshal.go +++ b/pkg/wsman/cim/bios/marshal.go @@ -11,20 +11,22 @@ import ( "gopkg.in/yaml.v3" ) -// JSON marshals the type into JSON format +// JSON marshals the type into JSON format. func (r *Response) JSON() string { jsonOutput, err := json.Marshal(r.Body) if err != nil { return "" } + return string(jsonOutput) } -// YAML marshals the type into YAML format +// YAML marshals the type into YAML format. func (r *Response) YAML() string { yamlOutput, err := yaml.Marshal(r.Body) if err != nil { return "" } + return string(yamlOutput) } diff --git a/pkg/wsman/cim/bios/types.go b/pkg/wsman/cim/bios/types.go index 6d38a245..98871359 100644 --- a/pkg/wsman/cim/bios/types.go +++ b/pkg/wsman/cim/bios/types.go @@ -17,7 +17,7 @@ type Element struct { base message.Base } -// Response Types +// Response Types. type ( Response struct { *client.Message diff --git a/pkg/wsman/cim/boot/configsetting.go b/pkg/wsman/cim/boot/configsetting.go index 5513031f..e163c643 100644 --- a/pkg/wsman/cim/boot/configsetting.go +++ b/pkg/wsman/cim/boot/configsetting.go @@ -31,15 +31,14 @@ import ( "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/client" ) -// NewBootConfigSettingWithClient instantiates a new ConfigSetting +// NewBootConfigSettingWithClient instantiates a new ConfigSetting. func NewBootConfigSettingWithClient(wsmanMessageCreator *message.WSManMessageCreator, client client.WSMan) ConfigSetting { return ConfigSetting{ - base: message.NewBaseWithClient(wsmanMessageCreator, CIM_BootConfigSetting, client), - client: client, + base: message.NewBaseWithClient(wsmanMessageCreator, CIMBootConfigSetting, client), } } -// Get retrieves the representation of the instance +// Get retrieves the representation of the instance. func (configSetting ConfigSetting) Get() (response Response, err error) { response = Response{ Message: &client.Message{ @@ -56,10 +55,11 @@ func (configSetting ConfigSetting) Get() (response Response, err error) { if err != nil { return } + return } -// Enumerate returns an enumeration context which is used in a subsequent Pull call +// Enumerate returns an enumeration context which is used in a subsequent Pull call. func (configSetting ConfigSetting) Enumerate() (response Response, err error) { response = Response{ Message: &client.Message{ @@ -76,6 +76,7 @@ func (configSetting ConfigSetting) Enumerate() (response Response, err error) { if err != nil { return } + return } @@ -86,14 +87,17 @@ func (configSetting ConfigSetting) Pull(enumerationContext string) (response Res XMLInput: configSetting.base.Pull(enumerationContext), }, } + err = configSetting.base.Execute(response.Message) if err != nil { return } + err = xml.Unmarshal([]byte(response.XMLOutput), &response) if err != nil { return } + return } @@ -115,13 +119,14 @@ func (configSetting ConfigSetting) Pull(enumerationContext string) (response Res // // 3) Intel AMT Release 7.0: Returns WSMAN Fault = “access denied” if user consent is required but IPS_OptInService.OptInState value is not 'Received' or 'In Session'. An exception to this rule is when the Source parameter is an empty array. func (configSetting ConfigSetting) ChangeBootOrder(source Source) (response Response, err error) { - header := configSetting.base.WSManMessageCreator.CreateHeader(methods.GenerateAction(CIM_BootConfigSetting, ChangeBootOrder), CIM_BootConfigSetting, nil, "", "") + header := configSetting.base.WSManMessageCreator.CreateHeader(methods.GenerateAction(CIMBootConfigSetting, ChangeBootOrder), CIMBootConfigSetting, nil, "", "") body := fmt.Sprintf(`
http://schemas.xmlsoap.org/ws/2004/08/addressing
http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_BootSourceSetting%s
`, source) response = Response{ Message: &client.Message{ XMLInput: configSetting.base.WSManMessageCreator.CreateXML(header, body), }, } + err = configSetting.base.Execute(response.Message) if err != nil { return @@ -131,5 +136,6 @@ func (configSetting ConfigSetting) ChangeBootOrder(source Source) (response Resp if err != nil { return } + return } diff --git a/pkg/wsman/cim/boot/configsetting_test.go b/pkg/wsman/cim/boot/configsetting_test.go index 203b272c..48d73e42 100644 --- a/pkg/wsman/cim/boot/configsetting_test.go +++ b/pkg/wsman/cim/boot/configsetting_test.go @@ -9,12 +9,11 @@ import ( "encoding/xml" "testing" - "github.com/stretchr/testify/assert" - "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/internal/message" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/cim/methods" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/common" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/wsmantesting" + "github.com/stretchr/testify/assert" ) func TestJson(t *testing.T) { @@ -23,7 +22,7 @@ func TestJson(t *testing.T) { ConfigSettingGetResponse: BootConfigSetting{}, }, } - expectedResult := "{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"ConfigSettingGetResponse\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"InstanceID\":\"\",\"ElementName\":\"\"},\"SourceSettingGetResponse\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"ElementName\":\"\",\"InstanceID\":\"\",\"StructuredBootString\":\"\",\"BIOSBootString\":\"\",\"BootString\":\"\",\"FailThroughSupported\":0},\"ServiceGetResponse\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"Name\":\"\",\"CreationClassName\":\"\",\"SystemName\":\"\",\"SystemCreationClassName\":\"\",\"ElementName\":\"\",\"OperationalStatus\":null,\"EnabledState\":0,\"RequestedState\":0},\"EnumerateResponse\":{\"EnumerationContext\":\"\"},\"PullResponse\":{\"BootSourceSettingItems\":null,\"BootConfigSettingItems\":null,\"BootServiceItems\":null},\"ChangeBootOrder_OUTPUT\":{\"ReturnValue\":0},\"SetBootConfigRole_OUTPUT\":{\"ReturnValue\":0}}" + expectedResult := "{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"ConfigSettingGetResponse\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"InstanceID\":\"\",\"ElementName\":\"\"},\"SourceSettingGetResponse\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"ElementName\":\"\",\"InstanceID\":\"\",\"StructuredBootString\":\"\",\"BIOSBootString\":\"\",\"BootString\":\"\",\"FailThroughSupported\":0},\"ServiceGetResponse\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"Name\":\"\",\"CreationClassName\":\"\",\"SystemName\":\"\",\"SystemCreationClassName\":\"\",\"ElementName\":\"\",\"OperationalStatus\":null,\"EnabledState\":0,\"RequestedState\":0},\"EnumerateResponse\":{\"EnumerationContext\":\"\"},\"PullResponse\":{\"BootSourceSettingItems\":null,\"BootConfigSettingItems\":null,\"BootServiceItems\":null},\"ChangeBootOrderOUTPUT\":{\"ReturnValue\":0},\"SetBootConfigRoleOUTPUT\":{\"ReturnValue\":0}}" result := response.JSON() assert.Equal(t, expectedResult, result) } @@ -34,15 +33,15 @@ func TestYaml(t *testing.T) { ConfigSettingGetResponse: BootConfigSetting{}, }, } - expectedResult := "xmlname:\n space: \"\"\n local: \"\"\nconfigsettinggetresponse:\n xmlname:\n space: \"\"\n local: \"\"\n instanceid: \"\"\n elementname: \"\"\nsourcesettinggetresponse:\n xmlname:\n space: \"\"\n local: \"\"\n elementname: \"\"\n instanceid: \"\"\n structuredbootstring: \"\"\n biosbootstring: \"\"\n bootstring: \"\"\n failthroughsupported: 0\nservicegetresponse:\n xmlname:\n space: \"\"\n local: \"\"\n name: \"\"\n creationclassname: \"\"\n systemname: \"\"\n systemcreationclassname: \"\"\n elementname: \"\"\n operationalstatus: []\n enabledstate: 0\n requestedstate: 0\nenumerateresponse:\n enumerationcontext: \"\"\npullresponse:\n bootsourcesettingitems: []\n bootconfigsettingitems: []\n bootserviceitems: []\nchangebootorder_output:\n returnvalue: 0\nsetbootconfigrole_output:\n returnvalue: 0\n" + expectedResult := "xmlname:\n space: \"\"\n local: \"\"\nconfigsettinggetresponse:\n xmlname:\n space: \"\"\n local: \"\"\n instanceid: \"\"\n elementname: \"\"\nsourcesettinggetresponse:\n xmlname:\n space: \"\"\n local: \"\"\n elementname: \"\"\n instanceid: \"\"\n structuredbootstring: \"\"\n biosbootstring: \"\"\n bootstring: \"\"\n failthroughsupported: 0\nservicegetresponse:\n xmlname:\n space: \"\"\n local: \"\"\n name: \"\"\n creationclassname: \"\"\n systemname: \"\"\n systemcreationclassname: \"\"\n elementname: \"\"\n operationalstatus: []\n enabledstate: 0\n requestedstate: 0\nenumerateresponse:\n enumerationcontext: \"\"\npullresponse:\n bootsourcesettingitems: []\n bootconfigsettingitems: []\n bootserviceitems: []\nchangebootorderoutput:\n returnvalue: 0\nsetbootconfigroleoutput:\n returnvalue: 0\n" result := response.YAML() assert.Equal(t, expectedResult, result) } func TestPositiveConfigSetting(t *testing.T) { messageID := 0 - resourceUriBase := "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.CIMResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "cim/boot/configsetting", } @@ -57,33 +56,35 @@ func TestPositiveConfigSetting(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //GETS + // GETS { "should create and parse a valid cim_BootConfigSetting Get call", - CIM_BootConfigSetting, - wsmantesting.GET, + CIMBootConfigSetting, + wsmantesting.Get, "", func() (Response, error) { - client.CurrentMessage = "Get" + client.CurrentMessage = wsmantesting.CurrentMessageGet + return elementUnderTest.Get() }, Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, ConfigSettingGetResponse: BootConfigSetting{ - XMLName: xml.Name{Space: "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_BootConfigSetting", Local: CIM_BootConfigSetting}, + XMLName: xml.Name{Space: "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_BootConfigSetting", Local: CIMBootConfigSetting}, InstanceID: "Intel(r) AMT: Boot Configuration 0", ElementName: "Intel(r) AMT: Boot Configuration", }, }, }, - //ENUMERATES + // ENUMERATES { "should create and parse a valid cim_BootConfigSetting Enumerate call", - CIM_BootConfigSetting, - wsmantesting.ENUMERATE, - wsmantesting.ENUMERATE_BODY, + CIMBootConfigSetting, + wsmantesting.Enumerate, + wsmantesting.EnumerateBody, func() (Response, error) { - client.CurrentMessage = "Enumerate" + client.CurrentMessage = wsmantesting.CurrentMessageEnumerate + return elementUnderTest.Enumerate() }, Body{ @@ -93,14 +94,15 @@ func TestPositiveConfigSetting(t *testing.T) { }, }, }, - //PULLS + // PULLS { "should create and parse a valid cim_BootConfigSetting Pull call", - CIM_BootConfigSetting, - wsmantesting.PULL, - wsmantesting.PULL_BODY, + CIMBootConfigSetting, + wsmantesting.Pull, + wsmantesting.PullBody, func() (Response, error) { - client.CurrentMessage = "Pull" + client.CurrentMessage = wsmantesting.CurrentMessagePull + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -108,7 +110,7 @@ func TestPositiveConfigSetting(t *testing.T) { PullResponse: PullResponse{ BootConfigSettingItems: []BootConfigSetting{ { - XMLName: xml.Name{Space: "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_BootConfigSetting", Local: CIM_BootConfigSetting}, + XMLName: xml.Name{Space: "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_BootConfigSetting", Local: CIMBootConfigSetting}, InstanceID: "Intel(r) AMT: Boot Configuration 0", ElementName: "Intel(r) AMT: Boot Configuration", }, @@ -116,14 +118,15 @@ func TestPositiveConfigSetting(t *testing.T) { }, }, }, - //Change Boot Order + // Change Boot Order { "should create and parse a valid cim_BootConfigSetting ChangeBootOrder call", - CIM_BootConfigSetting, - methods.GenerateAction(CIM_BootConfigSetting, ChangeBootOrder), + CIMBootConfigSetting, + methods.GenerateAction(CIMBootConfigSetting, ChangeBootOrder), "
http://schemas.xmlsoap.org/ws/2004/08/addressing
http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_BootSourceSettingIntel(r) AMT: Force Hard-drive Boot
", func() (Response, error) { client.CurrentMessage = "ChangeBootOrder" + return elementUnderTest.ChangeBootOrder(HardDrive) }, Body{ @@ -137,7 +140,7 @@ func TestPositiveConfigSetting(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, "", test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, "", test.body) messageID++ response, err := test.responseFunc() assert.NoError(t, err) @@ -150,8 +153,8 @@ func TestPositiveConfigSetting(t *testing.T) { func TestNegativeConfigSetting(t *testing.T) { messageID := 0 - resourceUriBase := "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.CIMResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "cim/boot/configsetting", } @@ -166,33 +169,35 @@ func TestNegativeConfigSetting(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //GETS + // GETS { "should handle error when cim_BootConfigSetting Get call", - CIM_BootConfigSetting, - wsmantesting.GET, + CIMBootConfigSetting, + wsmantesting.Get, "", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Get() }, Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, ConfigSettingGetResponse: BootConfigSetting{ - XMLName: xml.Name{Space: "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_BootConfigSetting", Local: CIM_BootConfigSetting}, + XMLName: xml.Name{Space: "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_BootConfigSetting", Local: CIMBootConfigSetting}, InstanceID: "Intel(r) AMT: Boot Configuration 0", ElementName: "Intel(r) AMT: Boot Configuration", }, }, }, - //ENUMERATES + // ENUMERATES { "should handle error when cim_BootConfigSetting Enumerate call", - CIM_BootConfigSetting, - wsmantesting.ENUMERATE, - wsmantesting.ENUMERATE_BODY, + CIMBootConfigSetting, + wsmantesting.Enumerate, + wsmantesting.EnumerateBody, func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Enumerate() }, Body{ @@ -202,14 +207,15 @@ func TestNegativeConfigSetting(t *testing.T) { }, }, }, - //PULLS + // PULLS { "should handle error when cim_BootConfigSetting Pull call", - CIM_BootConfigSetting, - wsmantesting.PULL, - wsmantesting.PULL_BODY, + CIMBootConfigSetting, + wsmantesting.Pull, + wsmantesting.PullBody, func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -217,7 +223,7 @@ func TestNegativeConfigSetting(t *testing.T) { PullResponse: PullResponse{ BootConfigSettingItems: []BootConfigSetting{ { - XMLName: xml.Name{Space: "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_BootConfigSetting", Local: CIM_BootConfigSetting}, + XMLName: xml.Name{Space: "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_BootConfigSetting", Local: CIMBootConfigSetting}, InstanceID: "Intel(r) AMT: Boot Configuration 0", ElementName: "Intel(r) AMT: Boot Configuration", }, @@ -225,14 +231,15 @@ func TestNegativeConfigSetting(t *testing.T) { }, }, }, - //Change Boot Order + // Change Boot Order { "should handle error when cim_BootConfigSetting ChangeBootOrder call", - CIM_BootConfigSetting, - methods.GenerateAction(CIM_BootConfigSetting, ChangeBootOrder), + CIMBootConfigSetting, + methods.GenerateAction(CIMBootConfigSetting, ChangeBootOrder), "
http://schemas.xmlsoap.org/ws/2004/08/addressing
http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_BootSourceSettingIntel(r) AMT: Force Hard-drive Boot
", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.ChangeBootOrder(HardDrive) }, Body{ @@ -246,7 +253,7 @@ func TestNegativeConfigSetting(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, "", test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, "", test.body) messageID++ response, err := test.responseFunc() assert.Error(t, err) diff --git a/pkg/wsman/cim/boot/decoder.go b/pkg/wsman/cim/boot/decoder.go index 4542629d..be0990dc 100644 --- a/pkg/wsman/cim/boot/decoder.go +++ b/pkg/wsman/cim/boot/decoder.go @@ -6,28 +6,29 @@ package boot const ( - CIM_BootConfigSetting string = "CIM_BootConfigSetting" - CIM_BootSourceSetting string = "CIM_BootSourceSetting" - CIM_BootService string = "CIM_BootService" - ChangeBootOrder string = "ChangeBootOrder" - SetBootConfigRole string = "SetBootConfigRole" + CIMBootConfigSetting string = "CIM_BootConfigSetting" + CIMBootSourceSetting string = "CIM_BootSourceSetting" + CIMBootService string = "CIM_BootService" + ChangeBootOrder string = "ChangeBootOrder" + ValueNotFound string = "Value not found in map" + SetBootConfigRole string = "SetBootConfigRole" ) const ( - HardDrive Source = "Intel(r) AMT: Force Hard-drive Boot" - CD Source = "Intel(r) AMT: Force CD/DVD Boot" - PXE Source = "Intel(r) AMT: Force PXE Boot" - OCR_UEFI_HTTPS Source = "Intel(r) AMT: Force OCR UEFI HTTPS Boot" - OCR_UEFI_BootOption1 Source = "Intel(r) AMT: Force OCR UEFI Boot Option 1" - OCR_UEFI_BootOption2 Source = "Intel(r) AMT: Force OCR UEFI Boot Option 2" - OCR_UEFI_BootOption3 Source = "Intel(r) AMT: Force OCR UEFI Boot Option 3" - OCR_UEFI_BootOption4 Source = "Intel(r) AMT: Force OCR UEFI Boot Option 4" - OCR_UEFI_BootOption5 Source = "Intel(r) AMT: Force OCR UEFI Boot Option 5" - OCR_UEFI_BootOption6 Source = "Intel(r) AMT: Force OCR UEFI Boot Option 6" - OCR_UEFI_BootOption7 Source = "Intel(r) AMT: Force OCR UEFI Boot Option 7" - OCR_UEFI_BootOption8 Source = "Intel(r) AMT: Force OCR UEFI Boot Option 8" - OCR_UEFI_BootOption9 Source = "Intel(r) AMT: Force OCR UEFI Boot Option 9" - OCR_UEFI_BootOption10 Source = "Intel(r) AMT: Force OCR UEFI Boot Option 10" + HardDrive Source = "Intel(r) AMT: Force Hard-drive Boot" + CD Source = "Intel(r) AMT: Force CD/DVD Boot" + PXE Source = "Intel(r) AMT: Force PXE Boot" + OCRUEFIHTTPS Source = "Intel(r) AMT: Force OCR UEFI HTTPS Boot" + OCRUEFIBootOption1 Source = "Intel(r) AMT: Force OCR UEFI Boot Option 1" + OCRUEFIBootOption2 Source = "Intel(r) AMT: Force OCR UEFI Boot Option 2" + OCRUEFIBootOption3 Source = "Intel(r) AMT: Force OCR UEFI Boot Option 3" + OCRUEFIBootOption4 Source = "Intel(r) AMT: Force OCR UEFI Boot Option 4" + OCRUEFIBootOption5 Source = "Intel(r) AMT: Force OCR UEFI Boot Option 5" + OCRUEFIBootOption6 Source = "Intel(r) AMT: Force OCR UEFI Boot Option 6" + OCRUEFIBootOption7 Source = "Intel(r) AMT: Force OCR UEFI Boot Option 7" + OCRUEFIBootOption8 Source = "Intel(r) AMT: Force OCR UEFI Boot Option 8" + OCRUEFIBootOption9 Source = "Intel(r) AMT: Force OCR UEFI Boot Option 9" + OCRUEFIBootOption10 Source = "Intel(r) AMT: Force OCR UEFI Boot Option 10" ) const ( @@ -36,20 +37,20 @@ const ( FailThroughSupportedNotSupported ) -// FailThroughSupportedToString is a mapping of the FailThroughSupported value to a string +// FailThroughSupportedToString is a mapping of the FailThroughSupported value to a string. var FailThroughSupportedToString = map[FailThroughSupported]string{ FailThroughSupportedUnknown: "Unknown", FailThroughSupportedIsSupported: "IsSupported", FailThroughSupportedNotSupported: "NotSupported", } -// String returns the string representation of the FailThroughSupported value +// String returns the string representation of the FailThroughSupported value. func (f FailThroughSupported) String() string { if value, exists := FailThroughSupportedToString[f]; exists { return value } - return "Value not found in map" + return ValueNotFound } const ( @@ -62,7 +63,7 @@ const ( ReturnValueAccessDenied ) -// ReturnValueToString is a mapping of the ReturnValue value to a string +// ReturnValueToString is a mapping of the ReturnValue value to a string. var ReturnValueToString = map[ReturnValue]string{ ReturnValueCompletedNoError: "CompletedNoError", ReturnValueNotSupported: "NotSupported", @@ -73,13 +74,13 @@ var ReturnValueToString = map[ReturnValue]string{ ReturnValueAccessDenied: "AccessDenied", } -// String returns the string representation of the ReturnValue value +// String returns the string representation of the ReturnValue value. func (r ReturnValue) String() string { if value, exists := ReturnValueToString[r]; exists { return value } - return "Value not found in map" + return ValueNotFound } const ( @@ -105,7 +106,7 @@ const ( OperationalStatusRelocating ) -// operationalStatusToString is a mapping of the OperationalStatus value to a string +// operationalStatusToString is a mapping of the OperationalStatus value to a string. var operationalStatusToString = map[OperationalStatus]string{ OperationalStatusUnknown: "Unknown", OperationalStatusOther: "Other", @@ -129,13 +130,13 @@ var operationalStatusToString = map[OperationalStatus]string{ OperationalStatusRelocating: "Relocating", } -// String returns the string representation of the OperationalStatus value +// String returns the string representation of the OperationalStatus value. func (o OperationalStatus) String() string { if value, exists := operationalStatusToString[o]; exists { return value } - return "Value not found in map" + return ValueNotFound } const ( @@ -156,7 +157,7 @@ const ( EnabledStateIntelOneClickRecoveryAndIntelRPEAreEnabledAndAllOtherBootOptionsAreEnabled EnabledState = 32771 ) -// enabledStateToString is a mapping of the EnabledState value to a string +// enabledStateToString is a mapping of the EnabledState value to a string. var enabledStateToString = map[EnabledState]string{ EnabledStateUnknown: "Unknown", EnabledStateOther: "Other", @@ -175,13 +176,13 @@ var enabledStateToString = map[EnabledState]string{ EnabledStateIntelOneClickRecoveryAndIntelRPEAreEnabledAndAllOtherBootOptionsAreEnabled: "IntelOneClickRecoveryAndIntelRPEAreEnabledAndAllOtherBootOptionsAreEnabled", } -// String returns the string representation of the EnabledState value +// String returns the string representation of the EnabledState value. func (e EnabledState) String() string { if value, exists := enabledStateToString[e]; exists { return value } - return "Value not found in map" + return ValueNotFound } const ( @@ -203,7 +204,7 @@ const ( RequestedStateEnableAllBootOptions RequestedState = 32771 ) -// requestedStateToString is a mapping of the RequestedState value to a string +// requestedStateToString is a mapping of the RequestedState value to a string. var requestedStateToString = map[RequestedState]string{ RequestedStateUnknown: "Unknown", RequestedStateEnabled: "Enabled", @@ -223,11 +224,11 @@ var requestedStateToString = map[RequestedState]string{ RequestedStateEnableAllBootOptions: "EnableAllBootOptions", } -// String returns the string representation of the RequestedState value +// String returns the string representation of the RequestedState value. func (r RequestedState) String() string { if value, exists := requestedStateToString[r]; exists { return value } - return "Value not found in map" + return ValueNotFound } diff --git a/pkg/wsman/cim/boot/marshal.go b/pkg/wsman/cim/boot/marshal.go index 8b27da02..5770d38e 100644 --- a/pkg/wsman/cim/boot/marshal.go +++ b/pkg/wsman/cim/boot/marshal.go @@ -11,20 +11,22 @@ import ( "gopkg.in/yaml.v3" ) -// JSON marshals the type into JSON format +// JSON marshals the type into JSON format. func (r *Response) JSON() string { jsonOutput, err := json.Marshal(r.Body) if err != nil { return "" } + return string(jsonOutput) } -// YAML marshals the type into YAML format +// YAML marshals the type into YAML format. func (r *Response) YAML() string { yamlOutput, err := yaml.Marshal(r.Body) if err != nil { return "" } + return string(yamlOutput) } diff --git a/pkg/wsman/cim/boot/service.go b/pkg/wsman/cim/boot/service.go index 583d4e43..63fd11ef 100644 --- a/pkg/wsman/cim/boot/service.go +++ b/pkg/wsman/cim/boot/service.go @@ -18,12 +18,11 @@ import ( // NewBootService returns a new instance of the BootService struct. func NewBootServiceWithClient(wsmanMessageCreator *message.WSManMessageCreator, client client.WSMan) Service { return Service{ - base: message.NewBaseWithClient(wsmanMessageCreator, CIM_BootService, client), - client: client, + base: message.NewBaseWithClient(wsmanMessageCreator, CIMBootService, client), } } -// Get retrieves the representation of the instance +// Get retrieves the representation of the instance. func (service Service) Get() (response Response, err error) { response = Response{ Message: &client.Message{ @@ -33,17 +32,18 @@ func (service Service) Get() (response Response, err error) { err = service.base.Execute(response.Message) if err != nil { - return + return response, err } err = xml.Unmarshal([]byte(response.XMLOutput), &response) if err != nil { - return + return response, err } - return + + return response, nil } -// Enumerate returns an enumeration context which is used in a subsequent Pull call +// Enumerate returns an enumeration context which is used in a subsequent Pull call. func (service Service) Enumerate() (response Response, err error) { response = Response{ Message: &client.Message{ @@ -53,14 +53,15 @@ func (service Service) Enumerate() (response Response, err error) { err = service.base.Execute(response.Message) if err != nil { - return + return response, err } err = xml.Unmarshal([]byte(response.XMLOutput), &response) if err != nil { - return + return response, err } - return + + return response, nil } // Pull returns the instances of this class. An enumeration context provided by the Enumerate call is used as input. @@ -70,21 +71,25 @@ func (service Service) Pull(enumerationContext string) (response Response, err e XMLInput: service.base.Pull(enumerationContext), }, } + err = service.base.Execute(response.Message) if err != nil { - return + return response, err } + err = xml.Unmarshal([]byte(response.XMLOutput), &response) if err != nil { - return + return response, err } - return + + return response, nil } func (service Service) SetBootConfigRole(instanceID string, role int) (response Response, err error) { - header := service.base.WSManMessageCreator.CreateHeader(methods.GenerateAction(CIM_BootService, SetBootConfigRole), CIM_BootService, nil, "", "") + header := service.base.WSManMessageCreator.CreateHeader(methods.GenerateAction(CIMBootService, SetBootConfigRole), CIMBootService, nil, "", "") var body strings.Builder + body.WriteString(`
http://schemas.xmlsoap.org/ws/2004/08/addressing
http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_BootConfigSetting`) @@ -100,13 +105,16 @@ func (service Service) SetBootConfigRole(instanceID string, role int) (response XMLInput: service.base.WSManMessageCreator.CreateXML(header, body.String()), }, } + err = service.base.Execute(response.Message) if err != nil { - return + return response, err } + err = xml.Unmarshal([]byte(response.XMLOutput), &response) if err != nil { - return + return response, err } - return + + return response, nil } diff --git a/pkg/wsman/cim/boot/service_test.go b/pkg/wsman/cim/boot/service_test.go index 847b5126..74674f2a 100644 --- a/pkg/wsman/cim/boot/service_test.go +++ b/pkg/wsman/cim/boot/service_test.go @@ -9,17 +9,16 @@ import ( "encoding/xml" "testing" - "github.com/stretchr/testify/assert" - "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/internal/message" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/common" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/wsmantesting" + "github.com/stretchr/testify/assert" ) func TestPositiveService(t *testing.T) { messageID := 0 - resourceUriBase := "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.CIMResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "cim/boot/service", } @@ -34,20 +33,21 @@ func TestPositiveService(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //GETS + // GETS { "should create and parse a valid cim_BootService Get call", - CIM_BootService, - wsmantesting.GET, + CIMBootService, + wsmantesting.Get, "", func() (Response, error) { - client.CurrentMessage = "Get" + client.CurrentMessage = wsmantesting.CurrentMessageGet + return elementUnderTest.Get() }, Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, ServiceGetResponse: BootService{ - XMLName: xml.Name{Space: "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_BootService", Local: CIM_BootService}, + XMLName: xml.Name{Space: "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_BootService", Local: CIMBootService}, Name: "Intel(r) AMT Boot Service", CreationClassName: "CIM_BootService", SystemName: "Intel(r) AMT", @@ -59,14 +59,15 @@ func TestPositiveService(t *testing.T) { }, }, }, - //ENUMERATES + // ENUMERATES { "should create and parse a valid cim_BootService Enumerate call", - CIM_BootService, - wsmantesting.ENUMERATE, - wsmantesting.ENUMERATE_BODY, + CIMBootService, + wsmantesting.Enumerate, + wsmantesting.EnumerateBody, func() (Response, error) { - client.CurrentMessage = "Enumerate" + client.CurrentMessage = wsmantesting.CurrentMessageEnumerate + return elementUnderTest.Enumerate() }, Body{ @@ -76,14 +77,15 @@ func TestPositiveService(t *testing.T) { }, }, }, - //PULLS + // PULLS { "should create and parse a valid cim_BootService Pull call", - CIM_BootService, - wsmantesting.PULL, - wsmantesting.PULL_BODY, + CIMBootService, + wsmantesting.Pull, + wsmantesting.PullBody, func() (Response, error) { - client.CurrentMessage = "Pull" + client.CurrentMessage = wsmantesting.CurrentMessagePull + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -91,7 +93,7 @@ func TestPositiveService(t *testing.T) { PullResponse: PullResponse{ BootServiceItems: []BootService{ { - XMLName: xml.Name{Space: "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_BootService", Local: CIM_BootService}, + XMLName: xml.Name{Space: "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_BootService", Local: CIMBootService}, Name: "Intel(r) AMT Boot Service", CreationClassName: "CIM_BootService", SystemName: "Intel(r) AMT", @@ -108,11 +110,12 @@ func TestPositiveService(t *testing.T) { // SetBootConfigRole { "should handle error when making cim_BootService SetBootConfigRole wsman message", - CIM_BootService, - wsmantesting.SET_BOOT_CONFIG_ROLE, + CIMBootService, + wsmantesting.SetBootConfigRole, `
http://schemas.xmlsoap.org/ws/2004/08/addressing
http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_BootConfigSettingInstanceID
0
`, func() (Response, error) { client.CurrentMessage = "SetBootConfigRole" + return elementUnderTest.SetBootConfigRole("InstanceID", 0) }, Body{ @@ -126,7 +129,7 @@ func TestPositiveService(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, "", test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, "", test.body) messageID++ response, err := test.responseFunc() assert.NoError(t, err) @@ -139,8 +142,8 @@ func TestPositiveService(t *testing.T) { func TestNegativeService(t *testing.T) { messageID := 0 - resourceUriBase := "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.CIMResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "cim/boot/service", } @@ -155,20 +158,21 @@ func TestNegativeService(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //GETS + // GETS { "should handle error when making cim_BootService Get call", - CIM_BootService, - wsmantesting.GET, + CIMBootService, + wsmantesting.Get, "", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Get() }, Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, ServiceGetResponse: BootService{ - XMLName: xml.Name{Space: "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_BootService", Local: CIM_BootService}, + XMLName: xml.Name{Space: "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_BootService", Local: CIMBootService}, Name: "Intel(r) AMT Boot Service", CreationClassName: "CIM_BootService", SystemName: "Intel(r) AMT", @@ -180,14 +184,15 @@ func TestNegativeService(t *testing.T) { }, }, }, - //ENUMERATES + // ENUMERATES { "should handle error when making cim_BootService Enumerate call", - CIM_BootService, - wsmantesting.ENUMERATE, - wsmantesting.ENUMERATE_BODY, + CIMBootService, + wsmantesting.Enumerate, + wsmantesting.EnumerateBody, func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Enumerate() }, Body{ @@ -197,14 +202,15 @@ func TestNegativeService(t *testing.T) { }, }, }, - //PULLS + // PULLS { "should handle error when making cim_BootService Pull wsman message", - CIM_BootService, - wsmantesting.PULL, - wsmantesting.PULL_BODY, + CIMBootService, + wsmantesting.Pull, + wsmantesting.PullBody, func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -212,7 +218,7 @@ func TestNegativeService(t *testing.T) { PullResponse: PullResponse{ BootServiceItems: []BootService{ { - XMLName: xml.Name{Space: "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_BootService", Local: CIM_BootService}, + XMLName: xml.Name{Space: "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_BootService", Local: CIMBootService}, Name: "Intel(r) AMT Boot Service", CreationClassName: "CIM_BootService", SystemName: "Intel(r) AMT", @@ -229,11 +235,12 @@ func TestNegativeService(t *testing.T) { // SetBootConfigRole { "should handle error when making cim_BootService SetBootConfigRole wsman message", - CIM_BootService, - wsmantesting.SET_BOOT_CONFIG_ROLE, + CIMBootService, + wsmantesting.SetBootConfigRole, `
http://schemas.xmlsoap.org/ws/2004/08/addressing
http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_BootConfigSettingInstanceID
0
`, func() (Response, error) { client.CurrentMessage = "Error" + return elementUnderTest.SetBootConfigRole("InstanceID", 0) }, Body{ @@ -247,7 +254,7 @@ func TestNegativeService(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, "", test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, "", test.body) messageID++ response, err := test.responseFunc() assert.Error(t, err) diff --git a/pkg/wsman/cim/boot/sourcesetting.go b/pkg/wsman/cim/boot/sourcesetting.go index d56258c2..f75da622 100644 --- a/pkg/wsman/cim/boot/sourcesetting.go +++ b/pkg/wsman/cim/boot/sourcesetting.go @@ -15,12 +15,11 @@ import ( // NewBootSourceSetting returns a new instance of the BootSourceSetting struct. func NewBootSourceSettingWithClient(wsmanMessageCreator *message.WSManMessageCreator, client client.WSMan) SourceSetting { return SourceSetting{ - base: message.NewBaseWithClient(wsmanMessageCreator, CIM_BootSourceSetting, client), - client: client, + base: message.NewBaseWithClient(wsmanMessageCreator, CIMBootSourceSetting, client), } } -// Get retrieves the representation of the instance +// Get retrieves the representation of the instance. func (sourceSetting SourceSetting) Get(instanceID string) (response Response, err error) { selector := message.Selector{ Name: "InstanceID", @@ -41,10 +40,11 @@ func (sourceSetting SourceSetting) Get(instanceID string) (response Response, er if err != nil { return } + return } -// Enumerate returns an enumeration context which is used in a subsequent Pull call +// Enumerate returns an enumeration context which is used in a subsequent Pull call. func (sourceSetting SourceSetting) Enumerate() (response Response, err error) { response = Response{ Message: &client.Message{ @@ -61,6 +61,7 @@ func (sourceSetting SourceSetting) Enumerate() (response Response, err error) { if err != nil { return } + return } @@ -71,13 +72,16 @@ func (sourceSetting SourceSetting) Pull(enumerationContext string) (response Res XMLInput: sourceSetting.base.Pull(enumerationContext), }, } + err = sourceSetting.base.Execute(response.Message) if err != nil { return } + err = xml.Unmarshal([]byte(response.XMLOutput), &response) if err != nil { return } + return } diff --git a/pkg/wsman/cim/boot/sourcesetting_test.go b/pkg/wsman/cim/boot/sourcesetting_test.go index e1d3b1d5..5bb73980 100644 --- a/pkg/wsman/cim/boot/sourcesetting_test.go +++ b/pkg/wsman/cim/boot/sourcesetting_test.go @@ -9,17 +9,16 @@ import ( "encoding/xml" "testing" - "github.com/stretchr/testify/assert" - "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/internal/message" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/common" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/wsmantesting" + "github.com/stretchr/testify/assert" ) func TestPositiveSourceSetting(t *testing.T) { messageID := 0 - resourceUriBase := "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.CIMResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "cim/boot/sourcesetting", } @@ -35,21 +34,22 @@ func TestPositiveSourceSetting(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //GETS + // GETS { "should create and parse a valid cim_BootSourceSetting Get call", - CIM_BootSourceSetting, - wsmantesting.GET, + CIMBootSourceSetting, + wsmantesting.Get, "Intel(r) AMT: Force Hard-drive Boot", "", func() (Response, error) { - client.CurrentMessage = "Get" + client.CurrentMessage = wsmantesting.CurrentMessageGet + return elementUnderTest.Get("Intel(r) AMT: Force Hard-drive Boot") }, Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, SourceSettingGetResponse: BootSourceSetting{ - XMLName: xml.Name{Space: "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_BootSourceSetting", Local: CIM_BootSourceSetting}, + XMLName: xml.Name{Space: "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_BootSourceSetting", Local: CIMBootSourceSetting}, ElementName: "Intel(r) AMT: Boot Source", InstanceID: "Intel(r) AMT: Force Hard-drive Boot", StructuredBootString: "CIM:Hard-Disk:1", @@ -57,15 +57,16 @@ func TestPositiveSourceSetting(t *testing.T) { }, }, }, - //ENUMERATES + // ENUMERATES { "should create and parse a valid cim_BootSourceSetting Enumerate call", - CIM_BootSourceSetting, - wsmantesting.ENUMERATE, + CIMBootSourceSetting, + wsmantesting.Enumerate, "", - wsmantesting.ENUMERATE_BODY, + wsmantesting.EnumerateBody, func() (Response, error) { - client.CurrentMessage = "Enumerate" + client.CurrentMessage = wsmantesting.CurrentMessageEnumerate + return elementUnderTest.Enumerate() }, Body{ @@ -75,15 +76,16 @@ func TestPositiveSourceSetting(t *testing.T) { }, }, }, - //PULLS + // PULLS { "should create and parse a valid cim_BootSourceSetting Pull call", - CIM_BootSourceSetting, - wsmantesting.PULL, + CIMBootSourceSetting, + wsmantesting.Pull, "", - wsmantesting.PULL_BODY, + wsmantesting.PullBody, func() (Response, error) { - client.CurrentMessage = "Pull" + client.CurrentMessage = wsmantesting.CurrentMessagePull + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -91,21 +93,21 @@ func TestPositiveSourceSetting(t *testing.T) { PullResponse: PullResponse{ BootSourceSettingItems: []BootSourceSetting{ { - XMLName: xml.Name{Space: "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_BootSourceSetting", Local: CIM_BootSourceSetting}, + XMLName: xml.Name{Space: "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_BootSourceSetting", Local: CIMBootSourceSetting}, InstanceID: "Intel(r) AMT: Force Hard-drive Boot", ElementName: "Intel(r) AMT: Boot Source", StructuredBootString: "CIM:Hard-Disk:1", FailThroughSupported: 2, }, { - XMLName: xml.Name{Space: "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_BootSourceSetting", Local: CIM_BootSourceSetting}, + XMLName: xml.Name{Space: "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_BootSourceSetting", Local: CIMBootSourceSetting}, InstanceID: "Intel(r) AMT: Force PXE Boot", ElementName: "Intel(r) AMT: Boot Source", StructuredBootString: "CIM:Network:1", FailThroughSupported: 2, }, { - XMLName: xml.Name{Space: "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_BootSourceSetting", Local: CIM_BootSourceSetting}, + XMLName: xml.Name{Space: "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_BootSourceSetting", Local: CIMBootSourceSetting}, InstanceID: "Intel(r) AMT: Force CD/DVD Boot", ElementName: "Intel(r) AMT: Boot Source", StructuredBootString: "CIM:CD/DVD:1", @@ -119,7 +121,7 @@ func TestPositiveSourceSetting(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedResponse := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, test.extraHeader, test.body) + expectedResponse := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, test.extraHeader, test.body) messageID++ response, err := test.responseFunc() assert.NoError(t, err) @@ -132,8 +134,8 @@ func TestPositiveSourceSetting(t *testing.T) { func TestNegativeSourceSetting(t *testing.T) { messageID := 0 - resourceUriBase := "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.CIMResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "cim/boot/sourcesetting", } @@ -149,21 +151,22 @@ func TestNegativeSourceSetting(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //GETS + // GETS { "should handle error when cim_BootSourceSetting Get call", - CIM_BootSourceSetting, - wsmantesting.GET, + CIMBootSourceSetting, + wsmantesting.Get, "Intel(r) AMT: Force Hard-drive Boot", "", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Get("Intel(r) AMT: Force Hard-drive Boot") }, Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, SourceSettingGetResponse: BootSourceSetting{ - XMLName: xml.Name{Space: "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_BootSourceSetting", Local: CIM_BootSourceSetting}, + XMLName: xml.Name{Space: "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_BootSourceSetting", Local: CIMBootSourceSetting}, ElementName: "Intel(r) AMT: Boot Source", InstanceID: "Intel(r) AMT: Force Hard-drive Boot", StructuredBootString: "CIM:Hard-Disk:1", @@ -171,15 +174,16 @@ func TestNegativeSourceSetting(t *testing.T) { }, }, }, - //ENUMERATES + // ENUMERATES { "should handle error when cim_BootSourceSetting Enumerate call", - CIM_BootSourceSetting, - wsmantesting.ENUMERATE, + CIMBootSourceSetting, + wsmantesting.Enumerate, "", - wsmantesting.ENUMERATE_BODY, + wsmantesting.EnumerateBody, func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Enumerate() }, Body{ @@ -189,15 +193,16 @@ func TestNegativeSourceSetting(t *testing.T) { }, }, }, - //PULLS + // PULLS { "should handle error when cim_BootSourceSetting Pull call", - CIM_BootSourceSetting, - wsmantesting.PULL, + CIMBootSourceSetting, + wsmantesting.Pull, "", - wsmantesting.PULL_BODY, + wsmantesting.PullBody, func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -205,21 +210,21 @@ func TestNegativeSourceSetting(t *testing.T) { PullResponse: PullResponse{ BootSourceSettingItems: []BootSourceSetting{ { - XMLName: xml.Name{Space: "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_BootSourceSetting", Local: CIM_BootSourceSetting}, + XMLName: xml.Name{Space: "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_BootSourceSetting", Local: CIMBootSourceSetting}, InstanceID: "Intel(r) AMT: Force Hard-drive Boot", ElementName: "Intel(r) AMT: Boot Source", StructuredBootString: "CIM:Hard-Disk:1", FailThroughSupported: 2, }, { - XMLName: xml.Name{Space: "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_BootSourceSetting", Local: CIM_BootSourceSetting}, + XMLName: xml.Name{Space: "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_BootSourceSetting", Local: CIMBootSourceSetting}, InstanceID: "Intel(r) AMT: Force PXE Boot", ElementName: "Intel(r) AMT: Boot Source", StructuredBootString: "CIM:Network:1", FailThroughSupported: 2, }, { - XMLName: xml.Name{Space: "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_BootSourceSetting", Local: CIM_BootSourceSetting}, + XMLName: xml.Name{Space: "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_BootSourceSetting", Local: CIMBootSourceSetting}, InstanceID: "Intel(r) AMT: Force CD/DVD Boot", ElementName: "Intel(r) AMT: Boot Source", StructuredBootString: "CIM:CD/DVD:1", @@ -233,7 +238,7 @@ func TestNegativeSourceSetting(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedResponse := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, test.extraHeader, test.body) + expectedResponse := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, test.extraHeader, test.body) messageID++ response, err := test.responseFunc() assert.Error(t, err) diff --git a/pkg/wsman/cim/boot/types.go b/pkg/wsman/cim/boot/types.go index e3d9ba5d..0458de8c 100644 --- a/pkg/wsman/cim/boot/types.go +++ b/pkg/wsman/cim/boot/types.go @@ -14,23 +14,20 @@ import ( ) type ConfigSetting struct { - base message.Base - client client.WSMan + base message.Base } type SourceSetting struct { - base message.Base - client client.WSMan + base message.Base } type Service struct { - base message.Base - client client.WSMan + base message.Base } type Source string -// Response Types +// Response Types. type ( Response struct { *client.Message diff --git a/pkg/wsman/cim/card/card.go b/pkg/wsman/cim/card/card.go index 0521461e..bdc727c1 100644 --- a/pkg/wsman/cim/card/card.go +++ b/pkg/wsman/cim/card/card.go @@ -18,12 +18,11 @@ import ( // NewCard returns a new instance of the Card struct. func NewCardWithClient(wsmanMessageCreator *message.WSManMessageCreator, client client.WSMan) Package { return Package{ - base: message.NewBaseWithClient(wsmanMessageCreator, CIM_Card, client), - client: client, + base: message.NewBaseWithClient(wsmanMessageCreator, CIMCard, client), } } -// Get retrieves the representation of the instance +// Get retrieves the representation of the instance. func (card Package) Get() (response Response, err error) { response = Response{ Message: &client.Message{ @@ -40,11 +39,11 @@ func (card Package) Get() (response Response, err error) { if err != nil { return } - return + return } -// Enumerate returns an enumeration context which is used in a subsequent Pull call +// Enumerate returns an enumeration context which is used in a subsequent Pull call. func (card Package) Enumerate() (response Response, err error) { response = Response{ Message: &client.Message{ @@ -61,8 +60,8 @@ func (card Package) Enumerate() (response Response, err error) { if err != nil { return } - return + return } // Pull returns the instances of this class. An enumeration context provided by the Enumerate call is used as input. @@ -72,13 +71,16 @@ func (card Package) Pull(enumerationContext string) (response Response, err erro XMLInput: card.base.Pull(enumerationContext), }, } + err = card.base.Execute(response.Message) if err != nil { return } + err = xml.Unmarshal([]byte(response.XMLOutput), &response) if err != nil { return } + return } diff --git a/pkg/wsman/cim/card/card_test.go b/pkg/wsman/cim/card/card_test.go index ee10d625..9044338c 100644 --- a/pkg/wsman/cim/card/card_test.go +++ b/pkg/wsman/cim/card/card_test.go @@ -39,8 +39,8 @@ func TestYaml(t *testing.T) { func TestPositiveCIMCard(t *testing.T) { messageID := 0 - resourceUriBase := "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.CIMResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "cim/card", } @@ -55,14 +55,15 @@ func TestPositiveCIMCard(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //GETS + // GETS { "should create a valid cim_Card Get wsman message", - CIM_Card, - wsmantesting.GET, + CIMCard, + wsmantesting.Get, "", func() (Response, error) { - client.CurrentMessage = "Get" + client.CurrentMessage = wsmantesting.CurrentMessageGet + return elementUnderTest.Get() }, Body{ @@ -82,14 +83,15 @@ func TestPositiveCIMCard(t *testing.T) { }, }, }, - //ENUMERATES + // ENUMERATES { "should create a valid cim_Card Enumerate wsman message", - CIM_Card, - wsmantesting.ENUMERATE, - wsmantesting.ENUMERATE_BODY, + CIMCard, + wsmantesting.Enumerate, + wsmantesting.EnumerateBody, func() (Response, error) { - client.CurrentMessage = "Enumerate" + client.CurrentMessage = wsmantesting.CurrentMessageEnumerate + return elementUnderTest.Enumerate() }, Body{ @@ -99,14 +101,15 @@ func TestPositiveCIMCard(t *testing.T) { }, }, }, - //PULLS + // PULLS { "should create a valid cim_Card Pull wsman message", - CIM_Card, - wsmantesting.PULL, - wsmantesting.PULL_BODY, + CIMCard, + wsmantesting.Pull, + wsmantesting.PullBody, func() (Response, error) { - client.CurrentMessage = "Pull" + client.CurrentMessage = wsmantesting.CurrentMessagePull + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -135,7 +138,7 @@ func TestPositiveCIMCard(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, "", test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, "", test.body) messageID++ response, err := test.responseFunc() assert.NoError(t, err) @@ -148,8 +151,8 @@ func TestPositiveCIMCard(t *testing.T) { func TestNegativeCIMCard(t *testing.T) { messageID := 0 - resourceUriBase := "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.CIMResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "cim/card", } @@ -164,14 +167,15 @@ func TestNegativeCIMCard(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //GETS + // GETS { "should create a valid cim_Card Get wsman message", - CIM_Card, - wsmantesting.GET, + CIMCard, + wsmantesting.Get, "", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Get() }, Body{ @@ -191,14 +195,15 @@ func TestNegativeCIMCard(t *testing.T) { }, }, }, - //ENUMERATES + // ENUMERATES { "should create a valid cim_Card Enumerate wsman message", - CIM_Card, - wsmantesting.ENUMERATE, - wsmantesting.ENUMERATE_BODY, + CIMCard, + wsmantesting.Enumerate, + wsmantesting.EnumerateBody, func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Enumerate() }, Body{ @@ -208,14 +213,15 @@ func TestNegativeCIMCard(t *testing.T) { }, }, }, - //PULLS + // PULLS { "should create a valid cim_Card Pull wsman message", - CIM_Card, - wsmantesting.PULL, - wsmantesting.PULL_BODY, + CIMCard, + wsmantesting.Pull, + wsmantesting.PullBody, func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -244,7 +250,7 @@ func TestNegativeCIMCard(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, "", test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, "", test.body) messageID++ response, err := test.responseFunc() assert.Error(t, err) diff --git a/pkg/wsman/cim/card/decoder.go b/pkg/wsman/cim/card/decoder.go index 8a78ef34..c6715732 100644 --- a/pkg/wsman/cim/card/decoder.go +++ b/pkg/wsman/cim/card/decoder.go @@ -5,7 +5,10 @@ package card -const CIM_Card string = "CIM_Card" +const ( + CIMCard string = "CIM_Card" + ValueNotFound string = "Value not found in map" +) const ( OperationalStatusUnknown OperationalStatus = iota @@ -30,7 +33,7 @@ const ( OperationalStatusRelocating ) -// operationalStatusMap is a map of the OperationalStatus enumeration +// operationalStatusMap is a map of the OperationalStatus enumeration. var operationalStatusMap = map[OperationalStatus]string{ OperationalStatusUnknown: "Unknown", OperationalStatusOther: "Other", @@ -54,12 +57,13 @@ var operationalStatusMap = map[OperationalStatus]string{ OperationalStatusRelocating: "Relocating", } -// String returns a human-readable string representation of the OperationalStatus enumeration +// String returns a human-readable string representation of the OperationalStatus enumeration. func (e OperationalStatus) String() string { if s, ok := operationalStatusMap[e]; ok { return s } - return "Value not found in map" + + return ValueNotFound } const ( @@ -83,7 +87,7 @@ const ( PackageTypeBladeExpansion ) -// packageTypeMap is a map of the PackageType enumeration +// packageTypeMap is a map of the PackageType enumeration. var packageTypeMap = map[PackageType]string{ PackageTypeUnknown: "Unknown", PackageTypeOther: "Other", @@ -105,10 +109,11 @@ var packageTypeMap = map[PackageType]string{ PackageTypeBladeExpansion: "BladeExpansion", } -// String returns a human-readable string representation of the PackageType enumeration +// String returns a human-readable string representation of the PackageType enumeration. func (e PackageType) String() string { if s, ok := packageTypeMap[e]; ok { return s } - return "Value not found in map" + + return ValueNotFound } diff --git a/pkg/wsman/cim/card/marshal.go b/pkg/wsman/cim/card/marshal.go index 17abd662..e423a821 100644 --- a/pkg/wsman/cim/card/marshal.go +++ b/pkg/wsman/cim/card/marshal.go @@ -11,20 +11,22 @@ import ( "gopkg.in/yaml.v3" ) -// JSON marshals the type into JSON format +// JSON marshals the type into JSON format. func (r *Response) JSON() string { jsonOutput, err := json.Marshal(r.Body) if err != nil { return "" } + return string(jsonOutput) } -// YAML marshals the type into YAML format +// YAML marshals the type into YAML format. func (r *Response) YAML() string { yamlOutput, err := yaml.Marshal(r.Body) if err != nil { return "" } + return string(yamlOutput) } diff --git a/pkg/wsman/cim/card/types.go b/pkg/wsman/cim/card/types.go index 906e1bf2..9c98ce52 100644 --- a/pkg/wsman/cim/card/types.go +++ b/pkg/wsman/cim/card/types.go @@ -14,11 +14,10 @@ import ( ) type Package struct { - base message.Base - client client.WSMan + base message.Base } -// Response Types +// Response Types. type ( Response struct { *client.Message @@ -53,8 +52,8 @@ type ( Version string `xml:"Version"` // A string that indicates the version of the PhysicalElement. } - // OperationalStatus is the current statuses of the element + // OperationalStatus is the current statuses of the element. OperationalStatus int - // PackageType is the type of the PhysicalPackage + // PackageType is the type of the PhysicalPackage. PackageType int ) diff --git a/pkg/wsman/cim/chassis/chassis.go b/pkg/wsman/cim/chassis/chassis.go index bd0ecde9..96493a37 100644 --- a/pkg/wsman/cim/chassis/chassis.go +++ b/pkg/wsman/cim/chassis/chassis.go @@ -16,12 +16,11 @@ import ( // NewChassis returns a new instance of the Chassis struct. func NewChassisWithClient(wsmanMessageCreator *message.WSManMessageCreator, client client.WSMan) Package { return Package{ - base: message.NewBaseWithClient(wsmanMessageCreator, CIM_Chassis, client), - client: client, + base: message.NewBaseWithClient(wsmanMessageCreator, CIMChassis, client), } } -// Get retrieves the representation of the instance +// Get retrieves the representation of the instance. func (chassis Package) Get() (response Response, err error) { response = Response{ Message: &client.Message{ @@ -38,11 +37,11 @@ func (chassis Package) Get() (response Response, err error) { if err != nil { return } - return + return } -// Enumerate returns an enumeration context which is used in a subsequent Pull call +// Enumerate returns an enumeration context which is used in a subsequent Pull call. func (chassis Package) Enumerate() (response Response, err error) { response = Response{ Message: &client.Message{ @@ -59,8 +58,8 @@ func (chassis Package) Enumerate() (response Response, err error) { if err != nil { return } - return + return } // Pull returns the instances of this class. An enumeration context provided by the Enumerate call is used as input. @@ -70,13 +69,16 @@ func (chassis Package) Pull(enumerationContext string) (response Response, err e XMLInput: chassis.base.Pull(enumerationContext), }, } + err = chassis.base.Execute(response.Message) if err != nil { return } + err = xml.Unmarshal([]byte(response.XMLOutput), &response) if err != nil { return } + return } diff --git a/pkg/wsman/cim/chassis/chassis_test.go b/pkg/wsman/cim/chassis/chassis_test.go index 88314f66..978a1cd1 100644 --- a/pkg/wsman/cim/chassis/chassis_test.go +++ b/pkg/wsman/cim/chassis/chassis_test.go @@ -9,11 +9,10 @@ import ( "encoding/xml" "testing" - "github.com/stretchr/testify/assert" - "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/internal/message" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/common" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/wsmantesting" + "github.com/stretchr/testify/assert" ) func TestJson(t *testing.T) { @@ -22,7 +21,7 @@ func TestJson(t *testing.T) { PullResponse: PullResponse{}, }, } - expectedResult := "{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"PullResponse\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"PackageItems\":null},\"EnumerateResponse\":{\"EnumerationContext\":\"\"},\"PackageResponse\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"Version\":\"\",\"SerialNumber\":\"\",\"Model\":\"\",\"Manufacturer\":\"\",\"ElementName\":\"\",\"CreationClassName\":\"\",\"Tag\":\"\",\"OperationalStatus\":null,\"PackageType\":0,\"ChassisPackageType\":0}}" + expectedResult := "{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"PullResponse\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"PackageItems\":null},\"EnumerateResponse\":{\"EnumerationContext\":\"\"},\"PackageResponse\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"Version\":\"\",\"SerialNumber\":\"\",\"Model\":\"\",\"Manufacturer\":\"\",\"ElementName\":\"\",\"CreationClassName\":\"\",\"Tag\":\"\",\"OperationalStatus\":null,\"PackageType\":0,\"FormFactor\":0}}" result := response.JSON() assert.Equal(t, expectedResult, result) } @@ -33,15 +32,15 @@ func TestYaml(t *testing.T) { PullResponse: PullResponse{}, }, } - expectedResult := "xmlname:\n space: \"\"\n local: \"\"\npullresponse:\n xmlname:\n space: \"\"\n local: \"\"\n packageitems: []\nenumerateresponse:\n enumerationcontext: \"\"\npackageresponse:\n xmlname:\n space: \"\"\n local: \"\"\n version: \"\"\n serialnumber: \"\"\n model: \"\"\n manufacturer: \"\"\n elementname: \"\"\n creationclassname: \"\"\n tag: \"\"\n operationalstatus: []\n packagetype: 0\n chassispackagetype: 0\n" + expectedResult := "xmlname:\n space: \"\"\n local: \"\"\npullresponse:\n xmlname:\n space: \"\"\n local: \"\"\n packageitems: []\nenumerateresponse:\n enumerationcontext: \"\"\npackageresponse:\n xmlname:\n space: \"\"\n local: \"\"\n version: \"\"\n serialnumber: \"\"\n model: \"\"\n manufacturer: \"\"\n elementname: \"\"\n creationclassname: \"\"\n tag: \"\"\n operationalstatus: []\n packagetype: 0\n formfactor: 0\n" result := response.YAML() assert.Equal(t, expectedResult, result) } func TestPositiveCIMChassis(t *testing.T) { messageID := 0 - resourceUriBase := "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.CIMResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "cim/chassis", } @@ -56,16 +55,18 @@ func TestPositiveCIMChassis(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //GETS + // GETS { "should create and parse a valid cim_Chassis Get call", - CIM_Chassis, - wsmantesting.GET, + CIMChassis, + wsmantesting.Get, "", func() (Response, error) { - client.CurrentMessage = "Get" + client.CurrentMessage = wsmantesting.CurrentMessageGet + return elementUnderTest.Get() - }, Body{ + }, + Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, PackageResponse: PackageResponse{ XMLName: xml.Name{Space: "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_Chassis", Local: "CIM_Chassis"}, @@ -82,30 +83,33 @@ func TestPositiveCIMChassis(t *testing.T) { }, }, }, - //ENUMERATES + // ENUMERATES { "should create and parse a valid cim_Chassis Enumerate call", - CIM_Chassis, - wsmantesting.ENUMERATE, - wsmantesting.ENUMERATE_BODY, + CIMChassis, + wsmantesting.Enumerate, + wsmantesting.EnumerateBody, func() (Response, error) { - client.CurrentMessage = "Enumerate" + client.CurrentMessage = wsmantesting.CurrentMessageEnumerate + return elementUnderTest.Enumerate() - }, Body{ + }, + Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, EnumerateResponse: common.EnumerateResponse{ EnumerationContext: "D1020000-0000-0000-0000-000000000000", }, }, }, - //PULLS + // PULLS { "should create and parse a valid cim_Chassis Pull call", - CIM_Chassis, - wsmantesting.PULL, - wsmantesting.PULL_BODY, + CIMChassis, + wsmantesting.Pull, + wsmantesting.PullBody, func() (Response, error) { - client.CurrentMessage = "Pull" + client.CurrentMessage = wsmantesting.CurrentMessagePull + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -134,7 +138,7 @@ func TestPositiveCIMChassis(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, "", test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, "", test.body) messageID++ response, err := test.responseFunc() assert.NoError(t, err) @@ -147,8 +151,8 @@ func TestPositiveCIMChassis(t *testing.T) { func TestNegativeCIMChassis(t *testing.T) { messageID := 0 - resourceUriBase := "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.CIMResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "cim/chassis", } @@ -163,16 +167,18 @@ func TestNegativeCIMChassis(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //GETS + // GETS { "should create and parse a valid cim_Chassis Get call", - CIM_Chassis, - wsmantesting.GET, + CIMChassis, + wsmantesting.Get, "", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Get() - }, Body{ + }, + Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, PackageResponse: PackageResponse{ XMLName: xml.Name{Space: "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_Chassis", Local: "CIM_Chassis"}, @@ -189,30 +195,33 @@ func TestNegativeCIMChassis(t *testing.T) { }, }, }, - //ENUMERATES + // ENUMERATES { "should create and parse a valid cim_Chassis Enumerate call", - CIM_Chassis, - wsmantesting.ENUMERATE, - wsmantesting.ENUMERATE_BODY, + CIMChassis, + wsmantesting.Enumerate, + wsmantesting.EnumerateBody, func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Enumerate() - }, Body{ + }, + Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, EnumerateResponse: common.EnumerateResponse{ EnumerationContext: "D1020000-0000-0000-0000-000000000000", }, }, }, - //PULLS + // PULLS { "should create and parse a valid cim_Chassis Pull call", - CIM_Chassis, - wsmantesting.PULL, - wsmantesting.PULL_BODY, + CIMChassis, + wsmantesting.Pull, + wsmantesting.PullBody, func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -241,7 +250,7 @@ func TestNegativeCIMChassis(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, "", test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, "", test.body) messageID++ response, err := test.responseFunc() assert.Error(t, err) diff --git a/pkg/wsman/cim/chassis/decoder.go b/pkg/wsman/cim/chassis/decoder.go index 9e3fb320..c3556c4b 100644 --- a/pkg/wsman/cim/chassis/decoder.go +++ b/pkg/wsman/cim/chassis/decoder.go @@ -5,9 +5,12 @@ package chassis -const CIM_Chassis string = "CIM_Chassis" +const ( + CIMChassis string = "CIM_Chassis" + ValueNotFound string = "Value not found in map" +) -// ChassisPackageType values +// ChassisPackageType values. const ( Unknown ChassisPackageType = iota Other @@ -94,7 +97,8 @@ func (c ChassisPackageType) String() string { if s, ok := chassisPackageTypeToString[c]; ok { return s } - return "Value not found in map" + + return ValueNotFound } const ( @@ -120,7 +124,7 @@ const ( OperationalStatusRelocating ) -// operationalStatusMap is a map of the OperationalStatus enumeration +// operationalStatusMap is a map of the OperationalStatus enumeration. var operationalStatusMap = map[OperationalStatus]string{ OperationalStatusUnknown: "Unknown", OperationalStatusOther: "Other", @@ -144,12 +148,13 @@ var operationalStatusMap = map[OperationalStatus]string{ OperationalStatusRelocating: "Relocating", } -// String returns a human-readable string representation of the OperationalStatus enumeration +// String returns a human-readable string representation of the OperationalStatus enumeration. func (e OperationalStatus) String() string { if s, ok := operationalStatusMap[e]; ok { return s } - return "Value not found in map" + + return ValueNotFound } const ( @@ -173,7 +178,7 @@ const ( PackageTypeBladeExpansion ) -// packageTypeMap is a map of the PackageType enumeration +// packageTypeMap is a map of the PackageType enumeration. var packageTypeMap = map[PackageType]string{ PackageTypeUnknown: "Unknown", PackageTypeOther: "Other", @@ -195,10 +200,11 @@ var packageTypeMap = map[PackageType]string{ PackageTypeBladeExpansion: "BladeExpansion", } -// String returns a human-readable string representation of the PackageType enumeration +// String returns a human-readable string representation of the PackageType enumeration. func (e PackageType) String() string { if s, ok := packageTypeMap[e]; ok { return s } - return "Value not found in map" + + return ValueNotFound } diff --git a/pkg/wsman/cim/chassis/marshal.go b/pkg/wsman/cim/chassis/marshal.go index c8655196..56c47f6d 100644 --- a/pkg/wsman/cim/chassis/marshal.go +++ b/pkg/wsman/cim/chassis/marshal.go @@ -11,20 +11,22 @@ import ( "gopkg.in/yaml.v3" ) -// JSON marshals the type into JSON format +// JSON marshals the type into JSON format. func (r *Response) JSON() string { jsonOutput, err := json.Marshal(r.Body) if err != nil { return "" } + return string(jsonOutput) } -// YAML marshals the type into YAML format +// YAML marshals the type into YAML format. func (r *Response) YAML() string { yamlOutput, err := yaml.Marshal(r.Body) if err != nil { return "" } + return string(yamlOutput) } diff --git a/pkg/wsman/cim/chassis/types.go b/pkg/wsman/cim/chassis/types.go index 5265367c..5e69b10b 100644 --- a/pkg/wsman/cim/chassis/types.go +++ b/pkg/wsman/cim/chassis/types.go @@ -14,8 +14,7 @@ import ( ) type Package struct { - base message.Base - client client.WSMan + base message.Base } type ( diff --git a/pkg/wsman/cim/chip/chip.go b/pkg/wsman/cim/chip/chip.go index eda1e75b..ceab3261 100644 --- a/pkg/wsman/cim/chip/chip.go +++ b/pkg/wsman/cim/chip/chip.go @@ -16,12 +16,11 @@ import ( // NewChip returns a new instance of the Chip struct. func NewChipWithClient(wsmanMessageCreator *message.WSManMessageCreator, client client.WSMan) Package { return Package{ - base: message.NewBaseWithClient(wsmanMessageCreator, CIM_Chip, client), - client: client, + base: message.NewBaseWithClient(wsmanMessageCreator, CIMChip, client), } } -// Get retrieves the representation of the instance +// Get retrieves the representation of the instance. func (chip Package) Get() (response Response, err error) { response = Response{ Message: &client.Message{ @@ -38,11 +37,11 @@ func (chip Package) Get() (response Response, err error) { if err != nil { return } - return + return } -// Enumerate returns an enumeration context which is used in a subsequent Pull call +// Enumerate returns an enumeration context which is used in a subsequent Pull call. func (chip Package) Enumerate() (response Response, err error) { response = Response{ Message: &client.Message{ @@ -59,8 +58,8 @@ func (chip Package) Enumerate() (response Response, err error) { if err != nil { return } - return + return } // Pull returns the instances of this class. An enumeration context provided by the Enumerate call is used as input. @@ -70,13 +69,16 @@ func (chip Package) Pull(enumerationContext string) (response Response, err erro XMLInput: chip.base.Pull(enumerationContext), }, } + err = chip.base.Execute(response.Message) if err != nil { return } + err = xml.Unmarshal([]byte(response.XMLOutput), &response) if err != nil { return } + return } diff --git a/pkg/wsman/cim/chip/chip_test.go b/pkg/wsman/cim/chip/chip_test.go index e737b42e..4ac3764b 100644 --- a/pkg/wsman/cim/chip/chip_test.go +++ b/pkg/wsman/cim/chip/chip_test.go @@ -9,11 +9,10 @@ import ( "encoding/xml" "testing" - "github.com/stretchr/testify/assert" - "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/internal/message" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/common" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/wsmantesting" + "github.com/stretchr/testify/assert" ) func TestJson(t *testing.T) { @@ -40,8 +39,8 @@ func TestYaml(t *testing.T) { func TestPositiveCIMChip(t *testing.T) { messageID := 0 - resourceUriBase := "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.CIMResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "cim/chip", } @@ -56,15 +55,17 @@ func TestPositiveCIMChip(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //GETS + // GETS { "should create and parse a valid cim_Chip Get call", - CIM_Chip, wsmantesting.GET, + CIMChip, wsmantesting.Get, "", func() (Response, error) { - client.CurrentMessage = "Get" + client.CurrentMessage = wsmantesting.CurrentMessageGet + return elementUnderTest.Get() - }, Body{ + }, + Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, PackageResponse: PackageResponse{ XMLName: xml.Name{Space: "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_Chip", Local: "CIM_Chip"}, @@ -78,28 +79,31 @@ func TestPositiveCIMChip(t *testing.T) { }, }, }, - //ENUMERATES + // ENUMERATES { "should create and parse a valid cim_Chip Enumerate call", - CIM_Chip, wsmantesting.ENUMERATE, - wsmantesting.ENUMERATE_BODY, + CIMChip, wsmantesting.Enumerate, + wsmantesting.EnumerateBody, func() (Response, error) { - client.CurrentMessage = "Enumerate" + client.CurrentMessage = wsmantesting.CurrentMessageEnumerate + return elementUnderTest.Enumerate() - }, Body{ + }, + Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, EnumerateResponse: common.EnumerateResponse{ EnumerationContext: "D3020000-0000-0000-0000-000000000000", }, }, }, - //PULLS + // PULLS { "should create and parse a valid cim_Chip Pull call", - CIM_Chip, wsmantesting.PULL, - wsmantesting.PULL_BODY, + CIMChip, wsmantesting.Pull, + wsmantesting.PullBody, func() (Response, error) { - client.CurrentMessage = "Pull" + client.CurrentMessage = wsmantesting.CurrentMessagePull + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -125,7 +129,7 @@ func TestPositiveCIMChip(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, "", test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, "", test.body) messageID++ response, err := test.responseFunc() assert.NoError(t, err) @@ -135,10 +139,11 @@ func TestPositiveCIMChip(t *testing.T) { } }) } + func TestNegativeCIMChip(t *testing.T) { messageID := 0 - resourceUriBase := "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.CIMResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "cim/chip", } @@ -153,15 +158,17 @@ func TestNegativeCIMChip(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //GETS + // GETS { "should create and parse a valid cim_Chip Get call", - CIM_Chip, wsmantesting.GET, + CIMChip, wsmantesting.Get, "", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Get() - }, Body{ + }, + Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, PackageResponse: PackageResponse{ XMLName: xml.Name{Space: "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_Chip", Local: "CIM_Chip"}, @@ -175,28 +182,31 @@ func TestNegativeCIMChip(t *testing.T) { }, }, }, - //ENUMERATES + // ENUMERATES { "should create and parse a valid cim_Chip Enumerate call", - CIM_Chip, wsmantesting.ENUMERATE, - wsmantesting.ENUMERATE_BODY, + CIMChip, wsmantesting.Enumerate, + wsmantesting.EnumerateBody, func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Enumerate() - }, Body{ + }, + Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, EnumerateResponse: common.EnumerateResponse{ EnumerationContext: "D3020000-0000-0000-0000-000000000000", }, }, }, - //PULLS + // PULLS { "should create and parse a valid cim_Chip Pull call", - CIM_Chip, wsmantesting.PULL, - wsmantesting.PULL_BODY, + CIMChip, wsmantesting.Pull, + wsmantesting.PullBody, func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -222,7 +232,7 @@ func TestNegativeCIMChip(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, "", test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, "", test.body) messageID++ response, err := test.responseFunc() assert.Error(t, err) diff --git a/pkg/wsman/cim/chip/decoder.go b/pkg/wsman/cim/chip/decoder.go index 6b006701..5274ce99 100644 --- a/pkg/wsman/cim/chip/decoder.go +++ b/pkg/wsman/cim/chip/decoder.go @@ -5,7 +5,7 @@ package chip -const CIM_Chip string = "CIM_Chip" +const CIMChip string = "CIM_Chip" const ( OperationalStatusUnknown OperationalStatus = iota @@ -30,7 +30,7 @@ const ( OperationalStatusRelocating ) -// operationalStatusMap is a map of the OperationalStatus enumeration +// operationalStatusMap is a map of the OperationalStatus enumeration. var operationalStatusMap = map[OperationalStatus]string{ OperationalStatusUnknown: "Unknown", OperationalStatusOther: "Other", @@ -54,10 +54,11 @@ var operationalStatusMap = map[OperationalStatus]string{ OperationalStatusRelocating: "Relocating", } -// String returns a human-readable string representation of the OperationalStatus enumeration +// String returns a human-readable string representation of the OperationalStatus enumeration. func (e OperationalStatus) String() string { if s, ok := operationalStatusMap[e]; ok { return s } + return "Value not found in map" } diff --git a/pkg/wsman/cim/chip/marshal.go b/pkg/wsman/cim/chip/marshal.go index 73b3c50a..95490f25 100644 --- a/pkg/wsman/cim/chip/marshal.go +++ b/pkg/wsman/cim/chip/marshal.go @@ -11,20 +11,22 @@ import ( "gopkg.in/yaml.v3" ) -// JSON marshals the type into JSON format +// JSON marshals the type into JSON format. func (r *Response) JSON() string { jsonOutput, err := json.Marshal(r.Body) if err != nil { return "" } + return string(jsonOutput) } -// YAML marshals the type into YAML format +// YAML marshals the type into YAML format. func (r *Response) YAML() string { yamlOutput, err := yaml.Marshal(r.Body) if err != nil { return "" } + return string(yamlOutput) } diff --git a/pkg/wsman/cim/chip/types.go b/pkg/wsman/cim/chip/types.go index 3218569e..a448eb23 100644 --- a/pkg/wsman/cim/chip/types.go +++ b/pkg/wsman/cim/chip/types.go @@ -14,11 +14,10 @@ import ( ) type Package struct { - base message.Base - client client.WSMan + base message.Base } -// Response Types +// Response Types. type ( Response struct { *client.Message diff --git a/pkg/wsman/cim/computer/constants.go b/pkg/wsman/cim/computer/constants.go index a8d63f64..6dcb6e2e 100644 --- a/pkg/wsman/cim/computer/constants.go +++ b/pkg/wsman/cim/computer/constants.go @@ -5,4 +5,4 @@ package computer -const CIM_ComputerSystemPackage string = "CIM_ComputerSystemPackage" +const CIMComputerSystemPackage string = "CIM_ComputerSystemPackage" diff --git a/pkg/wsman/cim/computer/marshal.go b/pkg/wsman/cim/computer/marshal.go index 14829d3e..7dbafc67 100644 --- a/pkg/wsman/cim/computer/marshal.go +++ b/pkg/wsman/cim/computer/marshal.go @@ -11,20 +11,22 @@ import ( "gopkg.in/yaml.v3" ) -// JSON marshals the type into JSON format +// JSON marshals the type into JSON format. func (r *Response) JSON() string { jsonOutput, err := json.Marshal(r.Body) if err != nil { return "" } + return string(jsonOutput) } -// YAML marshals the type into YAML format +// YAML marshals the type into YAML format. func (r *Response) YAML() string { yamlOutput, err := yaml.Marshal(r.Body) if err != nil { return "" } + return string(yamlOutput) } diff --git a/pkg/wsman/cim/computer/systempackage.go b/pkg/wsman/cim/computer/systempackage.go index b0699953..ac7fcb64 100644 --- a/pkg/wsman/cim/computer/systempackage.go +++ b/pkg/wsman/cim/computer/systempackage.go @@ -18,12 +18,11 @@ import ( // NewComputerSystemPackage returns a new instance of the ComputerSystemPackage struct. func NewComputerSystemPackageWithClient(wsmanMessageCreator *message.WSManMessageCreator, client client.WSMan) SystemPackage { return SystemPackage{ - base: message.NewBaseWithClient(wsmanMessageCreator, CIM_ComputerSystemPackage, client), - client: client, + base: message.NewBaseWithClient(wsmanMessageCreator, CIMComputerSystemPackage, client), } } -// Get retrieves the representation of the instance +// Get retrieves the representation of the instance. func (systemPackage SystemPackage) Get() (response Response, err error) { response = Response{ Message: &client.Message{ @@ -40,11 +39,11 @@ func (systemPackage SystemPackage) Get() (response Response, err error) { if err != nil { return } - return + return } -// Enumerate returns an enumeration context which is used in a subsequent Pull call +// Enumerate returns an enumeration context which is used in a subsequent Pull call. func (systemPackage SystemPackage) Enumerate() (response Response, err error) { response = Response{ Message: &client.Message{ @@ -61,8 +60,8 @@ func (systemPackage SystemPackage) Enumerate() (response Response, err error) { if err != nil { return } - return + return } // Pull returns the instances of this class. An enumeration context provided by the Enumerate call is used as input. @@ -72,13 +71,16 @@ func (systemPackage SystemPackage) Pull(enumerationContext string) (response Res XMLInput: systemPackage.base.Pull(enumerationContext), }, } + err = systemPackage.base.Execute(response.Message) if err != nil { return } + err = xml.Unmarshal([]byte(response.XMLOutput), &response) if err != nil { return } + return } diff --git a/pkg/wsman/cim/computer/systempackage_test.go b/pkg/wsman/cim/computer/systempackage_test.go index 92ee4e26..cae57a2f 100644 --- a/pkg/wsman/cim/computer/systempackage_test.go +++ b/pkg/wsman/cim/computer/systempackage_test.go @@ -9,11 +9,10 @@ import ( "encoding/xml" "testing" - "github.com/stretchr/testify/assert" - "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/internal/message" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/common" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/wsmantesting" + "github.com/stretchr/testify/assert" ) func TestJson(t *testing.T) { @@ -40,8 +39,8 @@ func TestYaml(t *testing.T) { func TestPositiveSystemPackage(t *testing.T) { messageID := 0 - resourceUriBase := "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.CIMResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "cim/computer/systempackage", } @@ -56,14 +55,15 @@ func TestPositiveSystemPackage(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //GETS + // GETS { "should create and parse a valid cim_ComputerSystemPackage Get call", - CIM_ComputerSystemPackage, - wsmantesting.GET, + CIMComputerSystemPackage, + wsmantesting.Get, "", func() (Response, error) { - client.CurrentMessage = "Get" + client.CurrentMessage = wsmantesting.CurrentMessageGet + return elementUnderTest.Get() }, Body{ @@ -119,14 +119,15 @@ func TestPositiveSystemPackage(t *testing.T) { }, }, }, - //ENUMERATES + // ENUMERATES { "should create and parse a valid cim_ComputerSystemPackage Enumerate call", - CIM_ComputerSystemPackage, - wsmantesting.ENUMERATE, - wsmantesting.ENUMERATE_BODY, + CIMComputerSystemPackage, + wsmantesting.Enumerate, + wsmantesting.EnumerateBody, func() (Response, error) { - client.CurrentMessage = "Enumerate" + client.CurrentMessage = wsmantesting.CurrentMessageEnumerate + return elementUnderTest.Enumerate() }, Body{ @@ -136,14 +137,15 @@ func TestPositiveSystemPackage(t *testing.T) { }, }, }, - //PULLS + // PULLS { "should create and parse a valid cim_ComputerSystemPackage Pull call", - CIM_ComputerSystemPackage, - wsmantesting.PULL, - wsmantesting.PULL_BODY, + CIMComputerSystemPackage, + wsmantesting.Pull, + wsmantesting.PullBody, func() (Response, error) { - client.CurrentMessage = "Pull" + client.CurrentMessage = wsmantesting.CurrentMessagePull + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -207,7 +209,7 @@ func TestPositiveSystemPackage(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, "", test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, "", test.body) messageID++ response, err := test.responseFunc() assert.NoError(t, err) @@ -220,8 +222,8 @@ func TestPositiveSystemPackage(t *testing.T) { func TestNegativeSystemPackage(t *testing.T) { messageID := 0 - resourceUriBase := "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.CIMResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "cim/computer/systempackage", } @@ -236,14 +238,15 @@ func TestNegativeSystemPackage(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //GETS + // GETS { "should handle error when cim_ComputerSystemPackage Get call", - CIM_ComputerSystemPackage, - wsmantesting.GET, + CIMComputerSystemPackage, + wsmantesting.Get, "", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Get() }, Body{ @@ -297,14 +300,15 @@ func TestNegativeSystemPackage(t *testing.T) { }, }, }, - //ENUMERATES + // ENUMERATES { "should handle error when cim_ComputerSystemPackage Enumerate call", - CIM_ComputerSystemPackage, - wsmantesting.ENUMERATE, - wsmantesting.ENUMERATE_BODY, + CIMComputerSystemPackage, + wsmantesting.Enumerate, + wsmantesting.EnumerateBody, func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Enumerate() }, Body{ @@ -314,14 +318,15 @@ func TestNegativeSystemPackage(t *testing.T) { }, }, }, - //PULLS + // PULLS { "should handle error when cim_ComputerSystemPackage Pull call", - CIM_ComputerSystemPackage, - wsmantesting.PULL, - wsmantesting.PULL_BODY, + CIMComputerSystemPackage, + wsmantesting.Pull, + wsmantesting.PullBody, func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -385,7 +390,7 @@ func TestNegativeSystemPackage(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, "", test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, "", test.body) messageID++ response, err := test.responseFunc() assert.Error(t, err) diff --git a/pkg/wsman/cim/computer/types.go b/pkg/wsman/cim/computer/types.go index 3ad31018..af3a2bbe 100644 --- a/pkg/wsman/cim/computer/types.go +++ b/pkg/wsman/cim/computer/types.go @@ -14,11 +14,10 @@ import ( ) type SystemPackage struct { - base message.Base - client client.WSMan + base message.Base } -// Response Types +// Response Types. type ( Response struct { *client.Message diff --git a/pkg/wsman/cim/concrete/constants.go b/pkg/wsman/cim/concrete/constants.go index 22ccb803..f313468c 100644 --- a/pkg/wsman/cim/concrete/constants.go +++ b/pkg/wsman/cim/concrete/constants.go @@ -5,4 +5,4 @@ package concrete -const CIM_ConcreteDependency string = "CIM_ConcreteDependency" +const CIMConcreteDependency string = "CIM_ConcreteDependency" diff --git a/pkg/wsman/cim/concrete/dependency.go b/pkg/wsman/cim/concrete/dependency.go index 86920e3c..4514bbed 100644 --- a/pkg/wsman/cim/concrete/dependency.go +++ b/pkg/wsman/cim/concrete/dependency.go @@ -21,14 +21,13 @@ import ( // should be NewDependency() because concrete is scoped already as package name. func NewDependencyWithClient(wsmanMessageCreator *message.WSManMessageCreator, client client.WSMan) Dependency { return Dependency{ - base: message.NewBaseWithClient(wsmanMessageCreator, CIM_ConcreteDependency, client), - client: client, + base: message.NewBaseWithClient(wsmanMessageCreator, CIMConcreteDependency, client), } } // TODO: Figure out how to call GET requiring resourceURIs and Selectors -// Enumerate the instances of this class +// Enumerate the instances of this class. func (dependency Dependency) Enumerate() (response Response, err error) { response = Response{ Message: &client.Message{ @@ -45,24 +44,27 @@ func (dependency Dependency) Enumerate() (response Response, err error) { if err != nil { return } - return + return } -// Pull instances of this class, following an Enumerate operation +// Pull instances of this class, following an Enumerate operation. func (dependency Dependency) Pull(enumerationContext string) (response Response, err error) { response = Response{ Message: &client.Message{ XMLInput: dependency.base.Pull(enumerationContext), }, } + err = dependency.base.Execute(response.Message) if err != nil { return } + err = xml.Unmarshal([]byte(response.XMLOutput), &response) if err != nil { return } + return } diff --git a/pkg/wsman/cim/concrete/dependency_test.go b/pkg/wsman/cim/concrete/dependency_test.go index 78993de6..d71ce524 100644 --- a/pkg/wsman/cim/concrete/dependency_test.go +++ b/pkg/wsman/cim/concrete/dependency_test.go @@ -40,8 +40,8 @@ func TestYaml(t *testing.T) { func TestPositiveCIMConcreteDependency(t *testing.T) { messageID := 0 - resourceUriBase := "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.CIMResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "cim/concrete/dependency", } @@ -57,15 +57,16 @@ func TestPositiveCIMConcreteDependency(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //ENUMERATES + // ENUMERATES { "should create and parse a valid cim_Concrete Enumerate call", - CIM_ConcreteDependency, - wsmantesting.ENUMERATE, + CIMConcreteDependency, + wsmantesting.Enumerate, "", - wsmantesting.ENUMERATE_BODY, + wsmantesting.EnumerateBody, func() (Response, error) { - client.CurrentMessage = "Enumerate" + client.CurrentMessage = wsmantesting.CurrentMessageEnumerate + return elementUnderTest.Enumerate() }, Body{ @@ -76,18 +77,20 @@ func TestPositiveCIMConcreteDependency(t *testing.T) { }, }, - //PULLS + // PULLS { "should create and parse a valid cim_Concrete Pull call", - CIM_ConcreteDependency, - wsmantesting.PULL, + CIMConcreteDependency, + wsmantesting.Pull, "", - wsmantesting.PULL_BODY, + wsmantesting.PullBody, func() (Response, error) { - client.CurrentMessage = "Pull" + client.CurrentMessage = wsmantesting.CurrentMessagePull + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, - Body{XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, + Body{ + XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, PullResponse: PullResponse{ XMLName: xml.Name{Space: "http://schemas.xmlsoap.org/ws/2004/09/enumeration", Local: "PullResponse"}, Items: []ConcreteDependency{ @@ -140,7 +143,7 @@ func TestPositiveCIMConcreteDependency(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, "", test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, "", test.body) messageID++ response, err := test.responseFunc() assert.NoError(t, err) @@ -153,8 +156,8 @@ func TestPositiveCIMConcreteDependency(t *testing.T) { func TestNegativeCIMConcreteDependency(t *testing.T) { messageID := 0 - resourceUriBase := "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.CIMResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "cim/concrete/dependency", } @@ -170,15 +173,16 @@ func TestNegativeCIMConcreteDependency(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //ENUMERATES + // ENUMERATES { "should handle error when cim_ConcreteDependency Enumerate call", - CIM_ConcreteDependency, - wsmantesting.ENUMERATE, + CIMConcreteDependency, + wsmantesting.Enumerate, "", - wsmantesting.ENUMERATE_BODY, + wsmantesting.EnumerateBody, func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Enumerate() }, Body{ @@ -189,18 +193,20 @@ func TestNegativeCIMConcreteDependency(t *testing.T) { }, }, - //PULLS + // PULLS { "should handle error when cim_ConcreteDependency Pull call", - CIM_ConcreteDependency, - wsmantesting.PULL, + CIMConcreteDependency, + wsmantesting.Pull, "", - wsmantesting.PULL_BODY, + wsmantesting.PullBody, func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, - Body{XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, + Body{ + XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, PullResponse: PullResponse{ XMLName: xml.Name{Space: "http://schemas.xmlsoap.org/ws/2004/09/enumeration", Local: "PullResponse"}, Items: []ConcreteDependency{ @@ -246,7 +252,7 @@ func TestNegativeCIMConcreteDependency(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, "", test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, "", test.body) messageID++ response, err := test.responseFunc() assert.Error(t, err) diff --git a/pkg/wsman/cim/concrete/marshal.go b/pkg/wsman/cim/concrete/marshal.go index 5d57cdb2..062fe771 100644 --- a/pkg/wsman/cim/concrete/marshal.go +++ b/pkg/wsman/cim/concrete/marshal.go @@ -11,20 +11,22 @@ import ( "gopkg.in/yaml.v3" ) -// JSON marshals the type into JSON format +// JSON marshals the type into JSON format. func (r *Response) JSON() string { jsonOutput, err := json.Marshal(r.Body) if err != nil { return "" } + return string(jsonOutput) } -// YAML marshals the type into YAML format +// YAML marshals the type into YAML format. func (r *Response) YAML() string { yamlOutput, err := yaml.Marshal(r.Body) if err != nil { return "" } + return string(yamlOutput) } diff --git a/pkg/wsman/cim/concrete/types.go b/pkg/wsman/cim/concrete/types.go index 13f9d82b..257673bb 100644 --- a/pkg/wsman/cim/concrete/types.go +++ b/pkg/wsman/cim/concrete/types.go @@ -15,11 +15,10 @@ import ( ) type Dependency struct { - base message.Base - client client.WSMan + base message.Base } -// Response Types +// Response Types. type ( Response struct { *client.Message diff --git a/pkg/wsman/cim/credential/constants.go b/pkg/wsman/cim/credential/constants.go index e07197db..fe289a73 100644 --- a/pkg/wsman/cim/credential/constants.go +++ b/pkg/wsman/cim/credential/constants.go @@ -5,4 +5,4 @@ package credential -const CIM_CredentialContext string = "CIM_CredentialContext" +const CIMCredentialContext string = "CIM_CredentialContext" diff --git a/pkg/wsman/cim/credential/context.go b/pkg/wsman/cim/credential/context.go index 9d4aaeb7..df78bf19 100644 --- a/pkg/wsman/cim/credential/context.go +++ b/pkg/wsman/cim/credential/context.go @@ -26,14 +26,13 @@ import ( // NewContext returns a new instance of the NewContext struct. func NewContextWithClient(wsmanMessageCreator *message.WSManMessageCreator, client client.WSMan) Context { return Context{ - base: message.NewBaseWithClient(wsmanMessageCreator, CIM_CredentialContext, client), - client: client, + base: message.NewBaseWithClient(wsmanMessageCreator, CIMCredentialContext, client), } } // TODO: Figure out how to call GET requiring resourceURIs and Selectors -// Enumerate the instances of this class +// Enumerate the instances of this class. func (context Context) Enumerate() (response Response, err error) { response = Response{ Message: &client.Message{ @@ -50,24 +49,27 @@ func (context Context) Enumerate() (response Response, err error) { if err != nil { return } - return + return } -// Pull instances of this class, following an Enumerate operation +// Pull instances of this class, following an Enumerate operation. func (context Context) Pull(enumerationContext string) (response Response, err error) { response = Response{ Message: &client.Message{ XMLInput: context.base.Pull(enumerationContext), }, } + err = context.base.Execute(response.Message) if err != nil { return } + err = xml.Unmarshal([]byte(response.XMLOutput), &response) if err != nil { return } + return } diff --git a/pkg/wsman/cim/credential/context_test.go b/pkg/wsman/cim/credential/context_test.go index 56d397bc..95d72ca6 100644 --- a/pkg/wsman/cim/credential/context_test.go +++ b/pkg/wsman/cim/credential/context_test.go @@ -40,8 +40,8 @@ func TestYaml(t *testing.T) { func TestPositiveCIMCredentialContext(t *testing.T) { messageID := 0 - resourceUriBase := "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.CIMResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "cim/credential/context", } @@ -56,14 +56,15 @@ func TestPositiveCIMCredentialContext(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //ENUMERATES + // ENUMERATES { "should create and parse a valid cim_IEEE8021xSettings Enumerate call", - CIM_CredentialContext, - wsmantesting.ENUMERATE, - wsmantesting.ENUMERATE_BODY, + CIMCredentialContext, + wsmantesting.Enumerate, + wsmantesting.EnumerateBody, func() (Response, error) { - client.CurrentMessage = "Enumerate" + client.CurrentMessage = wsmantesting.CurrentMessageEnumerate + return elementUnderTest.Enumerate() }, Body{ @@ -73,14 +74,15 @@ func TestPositiveCIMCredentialContext(t *testing.T) { }, }, }, - //PULLS + // PULLS { "should create and parse a valid cim_IEEE8021xSettings Pull call", - CIM_CredentialContext, - wsmantesting.PULL, - wsmantesting.PULL_BODY, + CIMCredentialContext, + wsmantesting.Pull, + wsmantesting.PullBody, func() (Response, error) { - client.CurrentMessage = "Pull" + client.CurrentMessage = wsmantesting.CurrentMessagePull + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -132,7 +134,7 @@ func TestPositiveCIMCredentialContext(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, "", test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, "", test.body) messageID++ response, err := test.responseFunc() assert.NoError(t, err) @@ -145,8 +147,8 @@ func TestPositiveCIMCredentialContext(t *testing.T) { func TestNegativeCIMCredentialContext(t *testing.T) { messageID := 0 - resourceUriBase := "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.CIMResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "cim/credential/context", } @@ -161,14 +163,15 @@ func TestNegativeCIMCredentialContext(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //ENUMERATES + // ENUMERATES { "should handle error when cim_IEEE8021xSettings Enumerate call", - CIM_CredentialContext, - wsmantesting.ENUMERATE, - wsmantesting.ENUMERATE_BODY, + CIMCredentialContext, + wsmantesting.Enumerate, + wsmantesting.EnumerateBody, func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Enumerate() }, Body{ @@ -178,14 +181,15 @@ func TestNegativeCIMCredentialContext(t *testing.T) { }, }, }, - //PULLS + // PULLS { "should handle error when cim_IEEE8021xSettings Pull call", - CIM_CredentialContext, - wsmantesting.PULL, - wsmantesting.PULL_BODY, + CIMCredentialContext, + wsmantesting.Pull, + wsmantesting.PullBody, func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -231,7 +235,7 @@ func TestNegativeCIMCredentialContext(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, "", test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, "", test.body) messageID++ response, err := test.responseFunc() assert.Error(t, err) diff --git a/pkg/wsman/cim/credential/marshal.go b/pkg/wsman/cim/credential/marshal.go index 80c9b234..c3327174 100644 --- a/pkg/wsman/cim/credential/marshal.go +++ b/pkg/wsman/cim/credential/marshal.go @@ -11,20 +11,22 @@ import ( "gopkg.in/yaml.v3" ) -// JSON marshals the type into JSON format +// JSON marshals the type into JSON format. func (r *Response) JSON() string { jsonOutput, err := json.Marshal(r.Body) if err != nil { return "" } + return string(jsonOutput) } -// YAML marshals the type into YAML format +// YAML marshals the type into YAML format. func (r *Response) YAML() string { yamlOutput, err := yaml.Marshal(r.Body) if err != nil { return "" } + return string(yamlOutput) } diff --git a/pkg/wsman/cim/credential/types.go b/pkg/wsman/cim/credential/types.go index 5c591ed8..a6a0451c 100644 --- a/pkg/wsman/cim/credential/types.go +++ b/pkg/wsman/cim/credential/types.go @@ -15,11 +15,10 @@ import ( ) type Context struct { - base message.Base - client client.WSMan + base message.Base } -// Response Types +// Response Types. type ( Response struct { *client.Message diff --git a/pkg/wsman/cim/ieee8021x/constants.go b/pkg/wsman/cim/ieee8021x/constants.go index 394a88b2..ef249f20 100644 --- a/pkg/wsman/cim/ieee8021x/constants.go +++ b/pkg/wsman/cim/ieee8021x/constants.go @@ -5,4 +5,4 @@ package ieee8021x -const CIM_IEEE8021xSettings string = "CIM_IEEE8021xSettings" +const CIMIEEE8021xSettings string = "CIM_IEEE8021xSettings" diff --git a/pkg/wsman/cim/ieee8021x/marshal.go b/pkg/wsman/cim/ieee8021x/marshal.go index e23c3e2d..0636e0f7 100644 --- a/pkg/wsman/cim/ieee8021x/marshal.go +++ b/pkg/wsman/cim/ieee8021x/marshal.go @@ -11,20 +11,22 @@ import ( "gopkg.in/yaml.v3" ) -// JSON marshals the type into JSON format +// JSON marshals the type into JSON format. func (r *Response) JSON() string { jsonOutput, err := json.Marshal(r.Body) if err != nil { return "" } + return string(jsonOutput) } -// YAML marshals the type into YAML format +// YAML marshals the type into YAML format. func (r *Response) YAML() string { yamlOutput, err := yaml.Marshal(r.Body) if err != nil { return "" } + return string(yamlOutput) } diff --git a/pkg/wsman/cim/ieee8021x/settings.go b/pkg/wsman/cim/ieee8021x/settings.go index ce650052..158e854d 100644 --- a/pkg/wsman/cim/ieee8021x/settings.go +++ b/pkg/wsman/cim/ieee8021x/settings.go @@ -16,14 +16,13 @@ import ( // NewIEEE8021xSettings returns a new instance of the IEEE8021xSettings struct. func NewIEEE8021xSettingsWithClient(wsmanMessageCreator *message.WSManMessageCreator, client client.WSMan) Settings { return Settings{ - base: message.NewBaseWithClient(wsmanMessageCreator, CIM_IEEE8021xSettings, client), - client: client, + base: message.NewBaseWithClient(wsmanMessageCreator, CIMIEEE8021xSettings, client), } } // TODO: Figure out how to call GET requiring resourceURIs and Selectors -// Enumerate returns an enumeration context which is used in a subsequent Pull call +// Enumerate returns an enumeration context which is used in a subsequent Pull call. func (settings Settings) Enumerate() (response Response, err error) { response = Response{ Message: &client.Message{ @@ -40,8 +39,8 @@ func (settings Settings) Enumerate() (response Response, err error) { if err != nil { return } - return + return } // Pull returns the instances of this class. An enumeration context provided by the Enumerate call is used as input. @@ -51,13 +50,16 @@ func (settings Settings) Pull(enumerationContext string) (response Response, err XMLInput: settings.base.Pull(enumerationContext), }, } + err = settings.base.Execute(response.Message) if err != nil { return } + err = xml.Unmarshal([]byte(response.XMLOutput), &response) if err != nil { return } + return } diff --git a/pkg/wsman/cim/ieee8021x/settings_test.go b/pkg/wsman/cim/ieee8021x/settings_test.go index a0aa73c1..464ed253 100644 --- a/pkg/wsman/cim/ieee8021x/settings_test.go +++ b/pkg/wsman/cim/ieee8021x/settings_test.go @@ -9,11 +9,10 @@ import ( "encoding/xml" "testing" - "github.com/stretchr/testify/assert" - "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/internal/message" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/common" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/wsmantesting" + "github.com/stretchr/testify/assert" ) func TestJson(t *testing.T) { @@ -40,8 +39,8 @@ func TestYaml(t *testing.T) { func TestPositiveCIMIEEE8021xSettings(t *testing.T) { messageID := 0 - resourceUriBase := "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_IEEE8021xSettings" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.CIMResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "cim/ieee8021x/settings", } @@ -56,14 +55,15 @@ func TestPositiveCIMIEEE8021xSettings(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //ENUMERATES + // ENUMERATES { "should create and parse a valid cim_IEEE8021xSettings Enumerate call", - CIM_IEEE8021xSettings, - wsmantesting.ENUMERATE, - wsmantesting.ENUMERATE_BODY, + CIMIEEE8021xSettings, + wsmantesting.Enumerate, + wsmantesting.EnumerateBody, func() (Response, error) { - client.CurrentMessage = "Enumerate" + client.CurrentMessage = wsmantesting.CurrentMessageEnumerate + return elementUnderTest.Enumerate() }, Body{ @@ -73,14 +73,15 @@ func TestPositiveCIMIEEE8021xSettings(t *testing.T) { }, }, }, - //PULLS + // PULLS { "should create and parse a valid cim_IEEE8021xSettings Pull call", - CIM_IEEE8021xSettings, - wsmantesting.PULL, - wsmantesting.PULL_BODY, + CIMIEEE8021xSettings, + wsmantesting.Pull, + wsmantesting.PullBody, func() (Response, error) { - client.CurrentMessage = "Pull" + client.CurrentMessage = wsmantesting.CurrentMessagePull + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -111,7 +112,7 @@ func TestPositiveCIMIEEE8021xSettings(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, "", test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, "", test.body) messageID++ response, err := test.responseFunc() assert.NoError(t, err) @@ -124,8 +125,8 @@ func TestPositiveCIMIEEE8021xSettings(t *testing.T) { func TestNegativeCIMIEEE8021xSettings(t *testing.T) { messageID := 0 - resourceUriBase := "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_IEEE8021xSettings" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.CIMResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "cim/ieee8021x/settings", } @@ -140,14 +141,15 @@ func TestNegativeCIMIEEE8021xSettings(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //ENUMERATES + // ENUMERATES { "should handle error when cim_IEEE8021xSettings Enumerate wsman message", - CIM_IEEE8021xSettings, - wsmantesting.ENUMERATE, - wsmantesting.ENUMERATE_BODY, + CIMIEEE8021xSettings, + wsmantesting.Enumerate, + wsmantesting.EnumerateBody, func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Enumerate() }, Body{ @@ -157,14 +159,15 @@ func TestNegativeCIMIEEE8021xSettings(t *testing.T) { }, }, }, - //PULLS + // PULLS { "should handle error when cim_IEEE8021xSettings Pull wsman message", - CIM_IEEE8021xSettings, - wsmantesting.PULL, - wsmantesting.PULL_BODY, + CIMIEEE8021xSettings, + wsmantesting.Pull, + wsmantesting.PullBody, func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -195,7 +198,7 @@ func TestNegativeCIMIEEE8021xSettings(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, "", test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, "", test.body) messageID++ response, err := test.responseFunc() assert.Error(t, err) diff --git a/pkg/wsman/cim/ieee8021x/types.go b/pkg/wsman/cim/ieee8021x/types.go index b2de5dce..232cefcb 100644 --- a/pkg/wsman/cim/ieee8021x/types.go +++ b/pkg/wsman/cim/ieee8021x/types.go @@ -14,11 +14,10 @@ import ( ) type Settings struct { - base message.Base - client client.WSMan + base message.Base } -// Response Types +// Response Types. type ( Response struct { *client.Message diff --git a/pkg/wsman/cim/kvm/decoder.go b/pkg/wsman/cim/kvm/decoder.go index 265a9cac..9a567d6a 100644 --- a/pkg/wsman/cim/kvm/decoder.go +++ b/pkg/wsman/cim/kvm/decoder.go @@ -5,14 +5,17 @@ package kvm -const CIM_KVMRedirectionSAP string = "CIM_KVMRedirectionSAP" +const ( + CIMKVMRedirectionSAP string = "CIM_KVMRedirectionSAP" + ValueNotFound string = "Value not found in map" +) const ( - RedirectionSAP_Enable KVMRedirectionSAPRequestStateChangeInput = 2 - RedirectionSAP_Disable KVMRedirectionSAPRequestStateChangeInput = 3 + RedirectionSAPEnable KVMRedirectionSAPRequestStateChangeInput = 2 + RedirectionSAPDisable KVMRedirectionSAPRequestStateChangeInput = 3 ) -// KVMProtocol constants +// KVMProtocol constants. const ( KVMProtocolUnknown KVMProtocol = iota KVMProtocolOther @@ -21,7 +24,7 @@ const ( KVMProtocolVNCRFB ) -// kvmProtocolToString is a map of KVMProtocol value to string +// kvmProtocolToString is a map of KVMProtocol value to string. var kvmProtocolToString = map[KVMProtocol]string{ KVMProtocolUnknown: "Unknown", KVMProtocolOther: "Other", @@ -30,15 +33,16 @@ var kvmProtocolToString = map[KVMProtocol]string{ KVMProtocolVNCRFB: "VNC-RFB", } -// String returns a human-readable string representation of the KVMProtocol enumeration +// String returns a human-readable string representation of the KVMProtocol enumeration. func (e KVMProtocol) String() string { if s, ok := kvmProtocolToString[e]; ok { return s } - return "Value not found in map" + + return ValueNotFound } -// ReturnValue constants +// ReturnValue constants. const ( ReturnValueCompletedNoError ReturnValue = iota ReturnValueNotSupported @@ -53,7 +57,7 @@ const ( ReturnValueBusy ReturnValue = 4099 ) -// returnValueToString is a map of ReturnValue value to string +// returnValueToString is a map of ReturnValue value to string. var returnValueToString = map[ReturnValue]string{ ReturnValueCompletedNoError: "CompletedWithNoError", ReturnValueNotSupported: "NotSupported", @@ -68,15 +72,16 @@ var returnValueToString = map[ReturnValue]string{ ReturnValueBusy: "Busy", } -// String returns a human-readable string representation of the ReturnValue enumeration +// String returns a human-readable string representation of the ReturnValue enumeration. func (e ReturnValue) String() string { if s, ok := returnValueToString[e]; ok { return s } - return "Value not found in map" + + return ValueNotFound } -// EnabledState constants +// EnabledState constants. const ( EnabledStateUnknown EnabledState = iota EnabledStateOther @@ -91,7 +96,7 @@ const ( EnabledStateStarting ) -// enabledStateToString is a map of EnabledState value to string +// enabledStateToString is a map of EnabledState value to string. var enabledStateToString = map[EnabledState]string{ EnabledStateUnknown: "Unknown", EnabledStateOther: "Other", @@ -106,15 +111,16 @@ var enabledStateToString = map[EnabledState]string{ EnabledStateStarting: "Starting", } -// String returns a human-readable string representation of the EnabledState enumeration +// String returns a human-readable string representation of the EnabledState enumeration. func (e EnabledState) String() string { if s, ok := enabledStateToString[e]; ok { return s } - return "Value not found in map" + + return ValueNotFound } -// RequestedState constants +// RequestedState constants. const ( RequestedStateUnknown RequestedState = 0 RequestedStateEnabled RequestedState = 2 @@ -130,7 +136,7 @@ const ( RequestedStateNotApplicable RequestedState = 12 ) -// requestedStateToString is a map of RequestedState value to string +// requestedStateToString is a map of RequestedState value to string. var requestedStateToString = map[RequestedState]string{ RequestedStateUnknown: "Unknown", RequestedStateEnabled: "Enabled", @@ -146,10 +152,11 @@ var requestedStateToString = map[RequestedState]string{ RequestedStateNotApplicable: "NotApplicable", } -// String returns a human-readable string representation of the RequestedState enumeration +// String returns a human-readable string representation of the RequestedState enumeration. func (e RequestedState) String() string { if s, ok := requestedStateToString[e]; ok { return s } - return "Value not found in map" + + return ValueNotFound } diff --git a/pkg/wsman/cim/kvm/marshal.go b/pkg/wsman/cim/kvm/marshal.go index 0ecb0581..a2327547 100644 --- a/pkg/wsman/cim/kvm/marshal.go +++ b/pkg/wsman/cim/kvm/marshal.go @@ -11,20 +11,22 @@ import ( "gopkg.in/yaml.v3" ) -// JSON marshals the type into JSON format +// JSON marshals the type into JSON format. func (r *Response) JSON() string { jsonOutput, err := json.Marshal(r.Body) if err != nil { return "" } + return string(jsonOutput) } -// YAML marshals the type into YAML format +// YAML marshals the type into YAML format. func (r *Response) YAML() string { yamlOutput, err := yaml.Marshal(r.Body) if err != nil { return "" } + return string(yamlOutput) } diff --git a/pkg/wsman/cim/kvm/redirectionsap.go b/pkg/wsman/cim/kvm/redirectionsap.go index f6b36e3a..c5854087 100644 --- a/pkg/wsman/cim/kvm/redirectionsap.go +++ b/pkg/wsman/cim/kvm/redirectionsap.go @@ -17,8 +17,7 @@ import ( // NewKVMRedirectionSAP returns a new instance of the KVMRedirectionSAP struct. func NewKVMRedirectionSAPWithClient(wsmanMessageCreator *message.WSManMessageCreator, client client.WSMan) RedirectionSAP { return RedirectionSAP{ - base: message.NewBaseWithClient(wsmanMessageCreator, CIM_KVMRedirectionSAP, client), - client: client, + base: message.NewBaseWithClient(wsmanMessageCreator, CIMKVMRedirectionSAP, client), } } @@ -26,7 +25,7 @@ func NewKVMRedirectionSAPWithClient(wsmanMessageCreator *message.WSManMessageCre func (redirectionSAP RedirectionSAP) RequestStateChange(requestedState KVMRedirectionSAPRequestStateChangeInput) (response Response, err error) { response = Response{ Message: &client.Message{ - XMLInput: redirectionSAP.base.RequestStateChange(methods.RequestStateChange(CIM_KVMRedirectionSAP), int(requestedState)), + XMLInput: redirectionSAP.base.RequestStateChange(methods.RequestStateChange(CIMKVMRedirectionSAP), int(requestedState)), }, } @@ -39,10 +38,11 @@ func (redirectionSAP RedirectionSAP) RequestStateChange(requestedState KVMRedire if err != nil { return } + return } -// Get retrieves the representation of the instance +// Get retrieves the representation of the instance. func (redirectionSAP RedirectionSAP) Get() (response Response, err error) { response = Response{ Message: &client.Message{ @@ -59,11 +59,11 @@ func (redirectionSAP RedirectionSAP) Get() (response Response, err error) { if err != nil { return } - return + return } -// Enumerate returns an enumeration context which is used in a subsequent Pull call +// Enumerate returns an enumeration context which is used in a subsequent Pull call. func (redirectionSAP RedirectionSAP) Enumerate() (response Response, err error) { response = Response{ Message: &client.Message{ @@ -80,8 +80,8 @@ func (redirectionSAP RedirectionSAP) Enumerate() (response Response, err error) if err != nil { return } - return + return } // Pull returns the instances of this class. An enumeration context provided by the Enumerate call is used as input. @@ -91,13 +91,16 @@ func (redirectionSAP RedirectionSAP) Pull(enumerationContext string) (response R XMLInput: redirectionSAP.base.Pull(enumerationContext), }, } + err = redirectionSAP.base.Execute(response.Message) if err != nil { return } + err = xml.Unmarshal([]byte(response.XMLOutput), &response) if err != nil { return } + return } diff --git a/pkg/wsman/cim/kvm/redirectionsap_test.go b/pkg/wsman/cim/kvm/redirectionsap_test.go index 1164c6c1..22a4d21b 100644 --- a/pkg/wsman/cim/kvm/redirectionsap_test.go +++ b/pkg/wsman/cim/kvm/redirectionsap_test.go @@ -9,11 +9,10 @@ import ( "encoding/xml" "testing" - "github.com/stretchr/testify/assert" - "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/internal/message" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/common" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/wsmantesting" + "github.com/stretchr/testify/assert" ) func TestJson(t *testing.T) { @@ -22,7 +21,7 @@ func TestJson(t *testing.T) { PullResponse: PullResponse{}, }, } - expectedResult := "{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"GetResponse\":{\"CreationClassName\":\"\",\"ElementName\":\"\",\"Name\":\"\",\"SystemCreationClassName\":\"\",\"SystemName\":\"\",\"EnabledState\":0,\"RequestedState\":0,\"KVMProtocol\":0},\"RequestStateChange_OUTPUT\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"ReturnValue\":0},\"EnumerateResponse\":{\"EnumerationContext\":\"\"},\"PullResponse\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"Items\":null}}" + expectedResult := "{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"GetResponse\":{\"CreationClassName\":\"\",\"ElementName\":\"\",\"Name\":\"\",\"SystemCreationClassName\":\"\",\"SystemName\":\"\",\"EnabledState\":0,\"RequestedState\":0,\"KVMProtocol\":0},\"RequestStateChangeOutput\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"ReturnValue\":0},\"EnumerateResponse\":{\"EnumerationContext\":\"\"},\"PullResponse\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"Items\":null}}" result := response.JSON() assert.Equal(t, expectedResult, result) } @@ -33,15 +32,15 @@ func TestYaml(t *testing.T) { PullResponse: PullResponse{}, }, } - expectedResult := "xmlname:\n space: \"\"\n local: \"\"\ngetresponse:\n creationclassname: \"\"\n elementname: \"\"\n name: \"\"\n systemcreationclassname: \"\"\n systemname: \"\"\n enabledstate: 0\n requestedstate: 0\n kvmprotocol: 0\nrequeststatechange_output:\n xmlname:\n space: \"\"\n local: \"\"\n returnvalue: 0\nenumerateresponse:\n enumerationcontext: \"\"\npullresponse:\n xmlname:\n space: \"\"\n local: \"\"\n items: []\n" + expectedResult := "xmlname:\n space: \"\"\n local: \"\"\ngetresponse:\n creationclassname: \"\"\n elementname: \"\"\n name: \"\"\n systemcreationclassname: \"\"\n systemname: \"\"\n enabledstate: 0\n requestedstate: 0\n kvmprotocol: 0\nrequeststatechangeoutput:\n xmlname:\n space: \"\"\n local: \"\"\n returnvalue: 0\nenumerateresponse:\n enumerationcontext: \"\"\npullresponse:\n xmlname:\n space: \"\"\n local: \"\"\n items: []\n" result := response.YAML() assert.Equal(t, expectedResult, result) } func TestPositiveCIMKVMRedirectionSAP(t *testing.T) { messageID := 0 - resourceUriBase := "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.CIMResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "cim/kvm", } @@ -56,16 +55,18 @@ func TestPositiveCIMKVMRedirectionSAP(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //GETS + // GETS { "should create and parse a valid cim_KVMRedirectionSAP Get call", - CIM_KVMRedirectionSAP, - wsmantesting.GET, + CIMKVMRedirectionSAP, + wsmantesting.Get, "", func() (Response, error) { - client.CurrentMessage = "Get" + client.CurrentMessage = wsmantesting.CurrentMessageGet + return elementUnderTest.Get() - }, Body{ + }, + Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, GetResponse: KVMRedirectionSAP{ CreationClassName: "CIM_KVMRedirectionSAP", @@ -79,14 +80,15 @@ func TestPositiveCIMKVMRedirectionSAP(t *testing.T) { }, }, }, - //ENUMERATES + // ENUMERATES { "should create and parse a valid cim_KVMRedirectionSAP Enumerate call", - CIM_KVMRedirectionSAP, - wsmantesting.ENUMERATE, - wsmantesting.ENUMERATE_BODY, + CIMKVMRedirectionSAP, + wsmantesting.Enumerate, + wsmantesting.EnumerateBody, func() (Response, error) { - client.CurrentMessage = "Enumerate" + client.CurrentMessage = wsmantesting.CurrentMessageEnumerate + return elementUnderTest.Enumerate() }, Body{ @@ -96,14 +98,15 @@ func TestPositiveCIMKVMRedirectionSAP(t *testing.T) { }, }, }, - //PULLS + // PULLS { "should create and parse a valid cim_KVMRedirectionSAP Pull call", - CIM_KVMRedirectionSAP, - wsmantesting.PULL, - wsmantesting.PULL_BODY, + CIMKVMRedirectionSAP, + wsmantesting.Pull, + wsmantesting.PullBody, func() (Response, error) { - client.CurrentMessage = "Pull" + client.CurrentMessage = wsmantesting.CurrentMessagePull + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -129,7 +132,7 @@ func TestPositiveCIMKVMRedirectionSAP(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, "", test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, "", test.body) messageID++ response, err := test.responseFunc() assert.NoError(t, err) @@ -142,8 +145,8 @@ func TestPositiveCIMKVMRedirectionSAP(t *testing.T) { func TestNegativeCIMKVMRedirectionSAP(t *testing.T) { messageID := 0 - resourceUriBase := "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.CIMResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "cim/kvm", } @@ -158,16 +161,18 @@ func TestNegativeCIMKVMRedirectionSAP(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //GETS + // GETS { "should handle error when cim_KVMRedirectionSAP Get call", - CIM_KVMRedirectionSAP, - wsmantesting.GET, + CIMKVMRedirectionSAP, + wsmantesting.Get, "", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Get() - }, Body{ + }, + Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, GetResponse: KVMRedirectionSAP{ CreationClassName: "CIM_KVMRedirectionSAP", @@ -181,14 +186,15 @@ func TestNegativeCIMKVMRedirectionSAP(t *testing.T) { }, }, }, - //ENUMERATES + // ENUMERATES { "should handle error when cim_KVMRedirectionSAP Enumerate call", - CIM_KVMRedirectionSAP, - wsmantesting.ENUMERATE, - wsmantesting.ENUMERATE_BODY, + CIMKVMRedirectionSAP, + wsmantesting.Enumerate, + wsmantesting.EnumerateBody, func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Enumerate() }, Body{ @@ -198,14 +204,15 @@ func TestNegativeCIMKVMRedirectionSAP(t *testing.T) { }, }, }, - //PULLS + // PULLS { "should handle error when cim_KVMRedirectionSAP Pull call", - CIM_KVMRedirectionSAP, - wsmantesting.PULL, - wsmantesting.PULL_BODY, + CIMKVMRedirectionSAP, + wsmantesting.Pull, + wsmantesting.PullBody, func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -231,7 +238,7 @@ func TestNegativeCIMKVMRedirectionSAP(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, "", test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, "", test.body) messageID++ response, err := test.responseFunc() assert.Error(t, err) diff --git a/pkg/wsman/cim/kvm/types.go b/pkg/wsman/cim/kvm/types.go index 27dda172..6472bcb5 100644 --- a/pkg/wsman/cim/kvm/types.go +++ b/pkg/wsman/cim/kvm/types.go @@ -14,11 +14,10 @@ import ( ) type RedirectionSAP struct { - base message.Base - client client.WSMan + base message.Base } -// Response Types +// Response Types. type ( Response struct { *client.Message @@ -73,7 +72,7 @@ type ( RequestedState int ) -// Request Types +// Request Types. type ( KVMRedirectionSAPRequestStateChangeInput int ) diff --git a/pkg/wsman/cim/mediaaccess/decoder.go b/pkg/wsman/cim/mediaaccess/decoder.go index eaf5c0be..48033ae6 100644 --- a/pkg/wsman/cim/mediaaccess/decoder.go +++ b/pkg/wsman/cim/mediaaccess/decoder.go @@ -5,7 +5,10 @@ package mediaaccess -const CIM_MediaAccessDevice string = "CIM_MediaAccessDevice" +const ( + CIMMediaAccessDevice string = "CIM_MediaAccessDevice" + ValueNotFound string = "Value not found in map" +) const ( Other Security = iota + 1 @@ -17,7 +20,7 @@ const ( BootBypassAndReadOnly ) -// securityToString is a map of Security values to string +// securityToString is a map of Security values to string. var securityToString = map[Security]string{ Other: "Other", Unknown: "Unknown", @@ -28,12 +31,13 @@ var securityToString = map[Security]string{ BootBypassAndReadOnly: "BootBypassandReadOnly", } -// String returns a human-readable string representation of the Security enumeration +// String returns a human-readable string representation of the Security enumeration. func (e Security) String() string { if s, ok := securityToString[e]; ok { return s } - return "Value not found in map" + + return ValueNotFound } const ( @@ -52,7 +56,7 @@ const ( PreDismountEjectNotRequired ) -// capabilitiesToString is a map of Capabilities value to string +// capabilitiesToString is a map of Capabilities value to string. var capabilitiesToString = map[Capabilities]string{ UnknownCapabilities: "Unknown", OtherCapabilities: "Other", @@ -69,12 +73,13 @@ var capabilitiesToString = map[Capabilities]string{ PreDismountEjectNotRequired: "PreDismountEjectNotRequired", } -// String returns a human-readable string representation of the Capabilities enumeration +// String returns a human-readable string representation of the Capabilities enumeration. func (e Capabilities) String() string { if s, ok := capabilitiesToString[e]; ok { return s } - return "Value not found in map" + + return ValueNotFound } const ( @@ -86,7 +91,7 @@ const ( EnabledDefaultQuiesce EnabledDefault = 9 ) -// enabledDefaultToString is a map of EnabledDefault value to string +// enabledDefaultToString is a map of EnabledDefault value to string. var enabledDefaultToString = map[EnabledDefault]string{ EnabledDefaultEnabled: "Enabled", EnabledDefaultDisabled: "Disabled", @@ -96,12 +101,13 @@ var enabledDefaultToString = map[EnabledDefault]string{ EnabledDefaultQuiesce: "Quiesce", } -// String returns a human-readable string representation of the EnabledDefault enumeration +// String returns a human-readable string representation of the EnabledDefault enumeration. func (e EnabledDefault) String() string { if s, ok := enabledDefaultToString[e]; ok { return s } - return "Value not found in map" + + return ValueNotFound } const ( @@ -118,7 +124,7 @@ const ( EnabledStateStarting ) -// enabledStateToString is a map of EnabledState value to string +// enabledStateToString is a map of EnabledState value to string. var enabledStateToString = map[EnabledState]string{ EnabledStateUnknown: "Unknown", EnabledStateOther: "Other", @@ -133,12 +139,13 @@ var enabledStateToString = map[EnabledState]string{ EnabledStateStarting: "Starting", } -// String returns a human-readable string representation of the EnabledState enumeration +// String returns a human-readable string representation of the EnabledState enumeration. func (e EnabledState) String() string { if s, ok := enabledStateToString[e]; ok { return s } - return "Value not found in map" + + return ValueNotFound } const ( @@ -156,7 +163,7 @@ const ( RequestedStateNotApplicable RequestedState = 12 ) -// requestedStateToString is a map of RequestedState value to string +// requestedStateToString is a map of RequestedState value to string. var requestedStateToString = map[RequestedState]string{ RequestedStateUnknown: "Unknown", RequestedStateEnabled: "Enabled", @@ -172,12 +179,13 @@ var requestedStateToString = map[RequestedState]string{ RequestedStateNotApplicable: "NotApplicable", } -// String returns a human-readable string representation of the RequestedState enumeration +// String returns a human-readable string representation of the RequestedState enumeration. func (e RequestedState) String() string { if s, ok := requestedStateToString[e]; ok { return s } - return "Value not found in map" + + return ValueNotFound } const ( @@ -203,7 +211,7 @@ const ( OperationalStatusRelocating ) -// operationalStatusToString is a map of OperationalStatus value to string +// operationalStatusToString is a map of OperationalStatus value to string. var operationalStatusToString = map[OperationalStatus]string{ OperationalStatusUnknown: "Unknown", OperationalStatusOther: "Other", @@ -227,10 +235,11 @@ var operationalStatusToString = map[OperationalStatus]string{ OperationalStatusRelocating: "Relocating", } -// String returns a human-readable string representation of the OperationalStatus enumeration +// String returns a human-readable string representation of the OperationalStatus enumeration. func (e OperationalStatus) String() string { if s, ok := operationalStatusToString[e]; ok { return s } - return "Value not found in map" + + return ValueNotFound } diff --git a/pkg/wsman/cim/mediaaccess/device.go b/pkg/wsman/cim/mediaaccess/device.go index 1606a5d1..20e4faa0 100644 --- a/pkg/wsman/cim/mediaaccess/device.go +++ b/pkg/wsman/cim/mediaaccess/device.go @@ -16,15 +16,14 @@ import ( // NewMediaAccessDevice returns a new instance of the MediaAccessDevice struct. func NewMediaAccessDeviceWithClient(wsmanMessageCreator *message.WSManMessageCreator, client client.WSMan) Device { return Device{ - base: message.NewBaseWithClient(wsmanMessageCreator, CIM_MediaAccessDevice, client), - client: client, + base: message.NewBaseWithClient(wsmanMessageCreator, CIMMediaAccessDevice, client), } } // TODO: Figure out how to call GET requiring resourceURIs and Selectors // Get retrieves the representation of the instance -// Enumerate returns an enumeration context which is used in a subsequent Pull call +// Enumerate returns an enumeration context which is used in a subsequent Pull call. func (device Device) Enumerate() (response Response, err error) { response = Response{ Message: &client.Message{ @@ -41,8 +40,8 @@ func (device Device) Enumerate() (response Response, err error) { if err != nil { return } - return + return } // Pull returns the instances of this class. An enumeration context provided by the Enumerate call is used as input. @@ -52,13 +51,16 @@ func (device Device) Pull(enumerationContext string) (response Response, err err XMLInput: device.base.Pull(enumerationContext), }, } + err = device.base.Execute(response.Message) if err != nil { return } + err = xml.Unmarshal([]byte(response.XMLOutput), &response) if err != nil { return } + return } diff --git a/pkg/wsman/cim/mediaaccess/device_test.go b/pkg/wsman/cim/mediaaccess/device_test.go index a6c9037b..f0d7d73f 100644 --- a/pkg/wsman/cim/mediaaccess/device_test.go +++ b/pkg/wsman/cim/mediaaccess/device_test.go @@ -9,11 +9,10 @@ import ( "encoding/xml" "testing" - "github.com/stretchr/testify/assert" - "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/internal/message" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/common" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/wsmantesting" + "github.com/stretchr/testify/assert" ) func TestJson(t *testing.T) { @@ -40,8 +39,8 @@ func TestYaml(t *testing.T) { func TestPositiveCIMMediaAccessDevice(t *testing.T) { messageID := 0 - resourceUriBase := "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.CIMResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "cim/mediaaccess", } @@ -57,33 +56,35 @@ func TestPositiveCIMMediaAccessDevice(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - - //ENUMERATES + // ENUMERATES { "should create and parse a valid cim_MediaAccessDevice Enumerate call", - CIM_MediaAccessDevice, - wsmantesting.ENUMERATE, + CIMMediaAccessDevice, + wsmantesting.Enumerate, "", - wsmantesting.ENUMERATE_BODY, + wsmantesting.EnumerateBody, func() (Response, error) { - client.CurrentMessage = "Enumerate" + client.CurrentMessage = wsmantesting.CurrentMessageEnumerate + return elementUnderTest.Enumerate() - }, Body{ + }, + Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, EnumerateResponse: common.EnumerateResponse{ EnumerationContext: "CE020000-0000-0000-0000-000000000000", }, }, }, - //PULLS + // PULLS { "should create and parse a valid cim_MediaAccessDevice Pull call", - CIM_MediaAccessDevice, - wsmantesting.PULL, + CIMMediaAccessDevice, + wsmantesting.Pull, "", - wsmantesting.PULL_BODY, + wsmantesting.PullBody, func() (Response, error) { - client.CurrentMessage = "Pull" + client.CurrentMessage = wsmantesting.CurrentMessagePull + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -127,7 +128,7 @@ func TestPositiveCIMMediaAccessDevice(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, "", test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, "", test.body) messageID++ response, err := test.responseFunc() assert.NoError(t, err) @@ -140,8 +141,8 @@ func TestPositiveCIMMediaAccessDevice(t *testing.T) { func TestNegativeCIMMediaAccessDevice(t *testing.T) { messageID := 0 - resourceUriBase := "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.CIMResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "cim/mediaaccess", } @@ -157,33 +158,35 @@ func TestNegativeCIMMediaAccessDevice(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - - //ENUMERATES + // ENUMERATES { "should handle error when cim_MediaAccessDevice Enumerate call", - CIM_MediaAccessDevice, - wsmantesting.ENUMERATE, + CIMMediaAccessDevice, + wsmantesting.Enumerate, "", - wsmantesting.ENUMERATE_BODY, + wsmantesting.EnumerateBody, func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Enumerate() - }, Body{ + }, + Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, EnumerateResponse: common.EnumerateResponse{ EnumerationContext: "CE020000-0000-0000-0000-000000000000", }, }, }, - //PULLS + // PULLS { "should handle error when cim_MediaAccessDevice Pull call", - CIM_MediaAccessDevice, - wsmantesting.PULL, + CIMMediaAccessDevice, + wsmantesting.Pull, "", - wsmantesting.PULL_BODY, + wsmantesting.PullBody, func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -227,7 +230,7 @@ func TestNegativeCIMMediaAccessDevice(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, "", test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, "", test.body) messageID++ response, err := test.responseFunc() assert.Error(t, err) diff --git a/pkg/wsman/cim/mediaaccess/marshal.go b/pkg/wsman/cim/mediaaccess/marshal.go index 0da6029d..5f14fcab 100644 --- a/pkg/wsman/cim/mediaaccess/marshal.go +++ b/pkg/wsman/cim/mediaaccess/marshal.go @@ -11,20 +11,22 @@ import ( "gopkg.in/yaml.v3" ) -// JSON marshals the type into JSON format +// JSON marshals the type into JSON format. func (r *Response) JSON() string { jsonOutput, err := json.Marshal(r.Body) if err != nil { return "" } + return string(jsonOutput) } -// YAML marshals the type into YAML format +// YAML marshals the type into YAML format. func (r *Response) YAML() string { yamlOutput, err := yaml.Marshal(r.Body) if err != nil { return "" } + return string(yamlOutput) } diff --git a/pkg/wsman/cim/mediaaccess/types.go b/pkg/wsman/cim/mediaaccess/types.go index fc753c21..784a68fe 100644 --- a/pkg/wsman/cim/mediaaccess/types.go +++ b/pkg/wsman/cim/mediaaccess/types.go @@ -14,11 +14,10 @@ import ( ) type Device struct { - base message.Base - client client.WSMan + base message.Base } -// Response Types +// Response Types. type ( Response struct { *client.Message diff --git a/pkg/wsman/cim/messages.go b/pkg/wsman/cim/messages.go index aef9af75..d1606b5e 100644 --- a/pkg/wsman/cim/messages.go +++ b/pkg/wsman/cim/messages.go @@ -2,7 +2,7 @@ * Copyright (c) Intel Corporation 2023 * SPDX-License-Identifier: Apache-2.0 **********************************************************************/ -//Package cim implements CIM classes to support communicating with Intel® AMT Devices +// Package cim implements CIM classes to support communicating with Intel® AMT Devices package cim import ( @@ -26,6 +26,7 @@ import ( "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/cim/system" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/cim/wifi" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/client" + "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/wsmantesting" ) type Messages struct { @@ -55,8 +56,8 @@ type Messages struct { } func NewMessages(client client.WSMan) Messages { - resourceUriBase := "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.CIMResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) m := Messages{ wsmanMessageCreator: wsmanMessageCreator, } @@ -82,5 +83,6 @@ func NewMessages(client client.WSMan) Messages { m.SystemPackaging = system.NewSystemPackageWithClient(wsmanMessageCreator, client) m.WiFiEndpointSettings = wifi.NewWiFiEndpointSettingsWithClient(wsmanMessageCreator, client) m.WiFiPort = wifi.NewWiFiPortWithClient(wsmanMessageCreator, client) + return m } diff --git a/pkg/wsman/cim/messages_test.go b/pkg/wsman/cim/messages_test.go index 0cfcd1df..f03b6214 100644 --- a/pkg/wsman/cim/messages_test.go +++ b/pkg/wsman/cim/messages_test.go @@ -33,72 +33,95 @@ import ( func TestNewMessages(t *testing.T) { mock := &wsmantesting.MockClient{} m := NewMessages(mock) + if m.wsmanMessageCreator == nil { t.Error("wsmanMessageCreator is not initialized") } + if reflect.DeepEqual(m.BIOSElement, bios.Element{}) { t.Error("BIOSElement is not initialized") } + if reflect.DeepEqual(m.BootConfigSetting, boot.ConfigSetting{}) { t.Error("BootConfigSetting is not initialized") } + if reflect.DeepEqual(m.BootService, boot.Service{}) { t.Error("BootService is not initialized") } + if reflect.DeepEqual(m.BootSourceSetting, boot.SourceSetting{}) { t.Error("BootSourceSetting is not initialized") } + if reflect.DeepEqual(m.Card, card.Package{}) { t.Error("Card is not initialized") } + if reflect.DeepEqual(m.Chassis, chassis.Package{}) { t.Error("Chassis is not initialized") } + if reflect.DeepEqual(m.Chip, chip.Package{}) { t.Error("Chip is not initialized") } + if reflect.DeepEqual(m.ComputerSystemPackage, computer.SystemPackage{}) { t.Error("ComputerSystemPackage is not initialized") } + if reflect.DeepEqual(m.ConcreteDependency, concrete.Dependency{}) { t.Error("Dependency is not initialized") } + if reflect.DeepEqual(m.CredentialContext, credential.Context{}) { t.Error("Context is not initialized") } + if reflect.DeepEqual(m.IEEE8021xSettings, ieee8021x.IEEE8021xSettingsRequest{}) { t.Error("IEEE8021xSettings is not initialized") } + if reflect.DeepEqual(m.KVMRedirectionSAP, kvm.RedirectionSAP{}) { t.Error("KVMRedirectionSAP is not initialized") } + if reflect.DeepEqual(m.MediaAccessDevice, mediaaccess.Device{}) { t.Error("MediaAccessDevice is not initialized") } + if reflect.DeepEqual(m.PhysicalMemory, physical.Memory{}) { t.Error("PhysicalMemory is not initialized") } + if reflect.DeepEqual(m.PhysicalPackage, physical.Package{}) { t.Error("PhysicalPackage is not initialized") } + if reflect.DeepEqual(m.PowerManagementService, power.ManagementService{}) { t.Error("PowerManagementService is not initialized") } + if reflect.DeepEqual(m.Processor, processor.Package{}) { t.Error("Processor is not initialized") } + if reflect.DeepEqual(m.ServiceAvailableToElement, service.AvailableToElement{}) { t.Error("ServiceAvailableToElement is not initialized") } + if reflect.DeepEqual(m.SoftwareIdentity, software.Identity{}) { t.Error("SoftwareIdentity is not initialized") } + if reflect.DeepEqual(m.SystemPackaging, system.Package{}) { t.Error("SystemPackaging is not initialized") } + if reflect.DeepEqual(m.WiFiEndpointSettings, wifi.EndpointSettings{}) { t.Error("WiFiEndpointSettings is not initialized") } + if reflect.DeepEqual(m.WiFiPort, wifi.Port{}) { t.Error("WiFiPort is not initialized") } diff --git a/pkg/wsman/cim/methods/methods.go b/pkg/wsman/cim/methods/methods.go index e3a5fbce..d45b0422 100644 --- a/pkg/wsman/cim/methods/methods.go +++ b/pkg/wsman/cim/methods/methods.go @@ -14,7 +14,7 @@ func RequestStateChange(className string) string { return fmt.Sprintf("http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/%s/RequestStateChange", className) } -func GenerateAction(className string, methodName string) string { +func GenerateAction(className, methodName string) string { return fmt.Sprintf("http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/%s/%s", className, methodName) } diff --git a/pkg/wsman/cim/methods/methods_test.go b/pkg/wsman/cim/methods/methods_test.go index 868ad57a..ae934824 100644 --- a/pkg/wsman/cim/methods/methods_test.go +++ b/pkg/wsman/cim/methods/methods_test.go @@ -11,23 +11,28 @@ import ( "github.com/stretchr/testify/assert" ) +const ( + TestMethod string = "TestMethod" + CIMTest string = "CIM_Test" +) + func TestMethods(t *testing.T) { t.Run("GenerateAction Test", func(t *testing.T) { expectedResult := "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_Test/TestMethod" - className := "CIM_Test" - methodName := "TestMethod" + className := CIMTest + methodName := TestMethod result := GenerateAction(className, methodName) assert.Equal(t, expectedResult, result) }) t.Run("GenerateMethod Test", func(t *testing.T) { expectedResult := "TestMethod_INPUT" - methodName := "TestMethod" + methodName := TestMethod result := GenerateInputMethod(methodName) assert.Equal(t, expectedResult, result) }) t.Run("RequestStateChange Test", func(t *testing.T) { expectedResult := "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_Test/RequestStateChange" - className := "CIM_Test" + className := CIMTest result := RequestStateChange(className) assert.Equal(t, expectedResult, result) }) diff --git a/pkg/wsman/cim/models/constants.go b/pkg/wsman/cim/models/constants.go index d113d140..ea834310 100644 --- a/pkg/wsman/cim/models/constants.go +++ b/pkg/wsman/cim/models/constants.go @@ -5,21 +5,26 @@ package models -// RoleCharacteristicsToString is a map of RoleCharacteristics value to string +const ( + ValueNotFound string = "Value not found in map" +) + +// RoleCharacteristicsToString is a map of RoleCharacteristics value to string. var RoleCharacteristicsToString = map[int]string{ 2: "Static", 3: "Opaque", } -// ConvertRoleCharacteristicsToString returns the string representation of RoleCharacteristics +// ConvertRoleCharacteristicsToString returns the string representation of RoleCharacteristics. func ConvertRoleCharacteristicsToString(value int) string { if value, exist := RoleCharacteristicsToString[value]; exist { return value } - return "Value not found in map" + + return ValueNotFound } -// UsageRestrictionToString is a map of UsageRestriction value to string +// UsageRestrictionToString is a map of UsageRestriction value to string. var UsageRestrictionToString = map[int]string{ 0: "Unknown", 1: "FrontEndOnly", @@ -27,30 +32,32 @@ var UsageRestrictionToString = map[int]string{ 3: "NotRestricted", } -// ConvertUsageRestrictionToString returns the string representation of UsageRestriction +// ConvertUsageRestrictionToString returns the string representation of UsageRestriction. func ConvertUsageRestrictionToString(value int) string { if value, exist := UsageRestrictionToString[value]; exist { return value } - return "Value not found in map" + + return ValueNotFound } -// PortTypeToString is a map of PortType value to string +// PortTypeToString is a map of PortType value to string. var PortTypeToString = map[int]string{ 0: "Unknown", 1: "Other", 2: "Not Applicable", } -// ConvertPortTypeToString returns the string representation of PortType +// ConvertPortTypeToString returns the string representation of PortType. func ConvertPortTypeToString(value int) string { if value, exist := PortTypeToString[value]; exist { return value } - return "Value not found in map" + + return ValueNotFound } -// LinkTechnologyToString is a map of LinkTechnology value to string +// LinkTechnologyToString is a map of LinkTechnology value to string. var LinkTechnologyToString = map[int]string{ 0: "Unknown", 1: "Other", @@ -66,15 +73,16 @@ var LinkTechnologyToString = map[int]string{ 11: "Wireless LAN", } -// ConvertLinkTechnologyToString returns the string representation of LinkTechnology +// ConvertLinkTechnologyToString returns the string representation of LinkTechnology. func ConvertLinkTechnologyToString(value int) string { if value, exist := LinkTechnologyToString[value]; exist { return value } - return "Value not found in map" + + return ValueNotFound } -// RemovalConditionsToString is a map of RemovalConditions value to string +// RemovalConditionsToString is a map of RemovalConditions value to string. var RemovalConditionsToString = map[int]string{ 0: "Unknown", 2: "Not Applicable", @@ -82,15 +90,16 @@ var RemovalConditionsToString = map[int]string{ 4: "Removable When On or Off", } -// ConvertRemovalConditionsToString returns the string representation of RemovalConditions +// ConvertRemovalConditionsToString returns the string representation of RemovalConditions. func ConvertRemovalConditionsToString(value int) string { if value, exist := RemovalConditionsToString[value]; exist { return value } - return "Value not found in map" + + return ValueNotFound } -// ServicePhilosophyToString is a map of ServicePhilosophy value to string +// ServicePhilosophyToString is a map of ServicePhilosophy value to string. var ServicePhilosophyToString = map[int]string{ 0: "Unknown", 1: "Other", @@ -103,15 +112,16 @@ var ServicePhilosophyToString = map[int]string{ 8: "Moveable", } -// ConvertServicePhilosophyToString returns the string representation of ServicePhilosophy +// ConvertServicePhilosophyToString returns the string representation of ServicePhilosophy. func ConvertServicePhilosophyToString(value int) string { if value, exist := ServicePhilosophyToString[value]; exist { return value } - return "Value not found in map" + + return ValueNotFound } -// SecurityBreachToString is a map of SecurityBreach value to string +// SecurityBreachToString is a map of SecurityBreach value to string. var SecurityBreachToString = map[int]string{ 1: "Other", 2: "Unknown", @@ -120,15 +130,16 @@ var SecurityBreachToString = map[int]string{ 5: "Breach Successful", } -// ConvertSecurityBreachToString returns the string representation of SecurityBreach +// ConvertSecurityBreachToString returns the string representation of SecurityBreach. func ConvertSecurityBreachToString(value int) string { if value, exist := SecurityBreachToString[value]; exist { return value } - return "Value not found in map" + + return ValueNotFound } -// ChassisPackageTypeToString is a map of ChassisPackageType value to string +// ChassisPackageTypeToString is a map of ChassisPackageType value to string. var ChassisPackageTypeToString = map[int]string{ 0: "Unknown", 1: "Other", @@ -169,15 +180,16 @@ var ChassisPackageTypeToString = map[int]string{ 36: "Stick PC", } -// ConvertChassisPackageTypeToString returns the string representation of ChassisPackageType +// ConvertChassisPackageTypeToString returns the string representation of ChassisPackageType. func ConvertChassisPackageTypeToString(value int) string { if value, exist := ChassisPackageTypeToString[value]; exist { return value } - return "Value not found in map" + + return ValueNotFound } -// SoftwareElementStateToString is a map of SoftwareElementState value to string +// SoftwareElementStateToString is a map of SoftwareElementState value to string. var SoftwareElementStateToString = map[int]string{ 0: "Deployable", 1: "Installable", @@ -185,12 +197,13 @@ var SoftwareElementStateToString = map[int]string{ 3: "Running", } -// ConvertSoftwareElementStateToString returns the string representation of SoftwareElementState +// ConvertSoftwareElementStateToString returns the string representation of SoftwareElementState. func ConvertSoftwareElementStateToString(value int) string { if value, exist := SoftwareElementStateToString[value]; exist { return value } - return "Value not found in map" + + return ValueNotFound } const ( @@ -226,6 +239,7 @@ const ( ConcreteJobState_Service ConcreteJobState_QueryPending ) + const ( CommunicationStatus_UnknownCS CommunicationStatus = iota CommunicationStatus_NotAvailableCS @@ -233,6 +247,7 @@ const ( CommunicationStatus_LostCommunication CommunicationStatus_NoContact ) + const ( DetailedStatus_NotAvailableDS DetailedStatus = iota DetailedStatus_NoAdditionalInformation @@ -241,6 +256,7 @@ const ( DetailedStatus_NonRecoverableError DetailedStatus_SupportingEntityInError ) + const ( OperatingStatus_UnknownOS OperatingStatus = iota OperatingStatus_NotAvailableOS @@ -260,12 +276,14 @@ const ( OperatingStatus_Transitioning OperatingStatus_InService ) + const ( PrimaryStatus_UnknownPS PrimaryStatus = iota PrimaryStatus_OK PrimaryStatus_Degraded PrimaryStatus_ErrorPS ) + const ( January RunMonth = iota February @@ -280,6 +298,7 @@ const ( November December ) + const ( SaturdayNegative RunDayOfWeek = iota - 7 FridayNegative @@ -297,6 +316,7 @@ const ( Friday Saturday ) + const ( RecoveryAction_UnknownRA RecoveryAction = iota RecoveryAction_Other @@ -305,10 +325,12 @@ const ( RecoveryAction_RerunJob RecoveryAction_RunRecoveryJob ) + const ( LocalTime LocalOrUtcTime = iota + 1 UTCTime ) + const ( PowerManagementCapabilities_Unknown PowerManagementCapabilitiesValues = iota PowerManagementCapabilities_NotSupported @@ -319,6 +341,7 @@ const ( PowerManagementCapabilities_PowerCyclingSupported PowerManagementCapabilities_TimedPowerOnSupported ) + const ( Availability_Other AvailabilityValues = iota + 1 Availability_Unknown @@ -342,6 +365,7 @@ const ( Availability_NotConfigured Availability_Quiesced ) + const ( StatusInfo_Other StatusInfoValues = iota + 1 StatusInfo_Unknown @@ -349,6 +373,7 @@ const ( StatusInfo_Disabled StatusInfo_NotApplicable ) + const ( AdditionalAvailability_Other AdditionalAvailabilityValues = iota + 1 AdditionalAvailability_Unknown @@ -389,6 +414,7 @@ const ( ForceOCRUEFIBootOption9 BootConfigSettingInstanceID = "Intel(r) AMT: Force OCR UEFI Boot Option 9" ForceOCRUEFIBootOption10 BootConfigSettingInstanceID = "Intel(r) AMT: Force OCR UEFI Boot Option 10" ) + const ( RemovalConditions_Unknown RemovalConditions = 0 RemovalConditions_NotApplicable RemovalConditions = 2 @@ -407,12 +433,14 @@ const ( OverwritePolicy_WrapsWhenFull OverwritePolicy = 2 OverwritePolicy_NeverOverwrites OverwritePolicy = 7 ) + const ( LogState_Unknown LogState = 0 LogState_Normal LogState = 2 LogState_Erasing LogState = 3 LogState_NotApplicable LogState = 4 ) + const ( Capabilities_Unknown CapabilitiesValues = iota Capabilities_Other @@ -426,6 +454,7 @@ const ( Capabilities_VariableFormatsForRecords Capabilities_CanFlagRecordsForOverwrite ) + const ( LastChange_Unknown LastChange = iota LastChange_Add @@ -433,6 +462,7 @@ const ( LastChange_Modify LastChange_LogCleared ) + const ( CharacterSet_Unknown CharacterSet = iota CharacterSet_Other diff --git a/pkg/wsman/cim/models/methods.go b/pkg/wsman/cim/models/methods.go index 04aa327a..6710e60f 100644 --- a/pkg/wsman/cim/models/methods.go +++ b/pkg/wsman/cim/models/methods.go @@ -6,22 +6,24 @@ // Package models provides a set of utility types, constants, and functions that are used broadly across amt, cim, and ips packages package models -// HasSelector checks the SelectorSet and returns true if the SelectorSet contains a Selector -func (rp *ReferenceParametersNoNamespace) HasSelector(name string, value string) bool { +// HasSelector checks the SelectorSet and returns true if the SelectorSet contains a Selector. +func (rp *ReferenceParametersNoNamespace) HasSelector(name, value string) bool { for _, selector := range rp.SelectorSet.Selectors { if selector.Name == name && selector.Text == value { return true } } + return false } -// GetSelectorValue returns the Value property of a selector found in a SelectorSet based on the selector name +// GetSelectorValue returns the Value property of a selector found in a SelectorSet based on the selector name. func (rp *ReferenceParametersNoNamespace) GetSelectorValue(name string) string { for _, selector := range rp.SelectorSet.Selectors { if selector.Name == name { return selector.Text } } + return "" } diff --git a/pkg/wsman/cim/models/types.go b/pkg/wsman/cim/models/types.go index 1ec6a8c6..43633cb0 100644 --- a/pkg/wsman/cim/models/types.go +++ b/pkg/wsman/cim/models/types.go @@ -121,31 +121,33 @@ type PhysicalPackage struct { } /** - * Enabled:1 | Disabled:2 | Enabled For Debug:3 + * Enabled:1 | Disabled:2 | Enabled For Debug:3. */ -type Enabled int -type PhysicalFrame struct { - PhysicalPackage - VendorCompatibilityStrings []string `xml:"VendorCompatibilityStrings,omitempty"` - OtherPackageType string `xml:"OtherPackageType,omitempty"` - Weight int `xml:"Weight,omitempty"` - Width int `xml:"Width,omitempty"` - Depth int `xml:"Depth,omitempty"` - Height int `xml:"Height,omitempty"` - RemovalConditions int `xml:"RemovalConditions,omitempty"` - Removable bool `xml:"Removable,omitempty"` - Replaceable bool `xml:"Replaceable,omitempty"` - HotSwappable bool `xml:"HotSwappable,omitempty"` - CableManagementStrategy string `xml:"CableManagementStrategy,omitempty"` - ServicePhilosophy int `xml:"ServicePhilosophy,omitempty"` - ServiceDescriptions []string `xml:"ServiceDescriptions,omitempty"` - LockPresent bool `xml:"LockPresent,omitempty"` - AudibleAlarm bool `xml:"AudibleAlarm,omitempty"` - VisibleAlarm bool `xml:"VisibleAlarm,omitempty"` - SecurityBreach int `xml:"SecurityBreach,omitempty"` - BreachDescription string `xml:"BreachDescription,omitempty"` - IsLocked bool `xml:"IsLocked,omitempty"` -} +type ( + Enabled int + PhysicalFrame struct { + PhysicalPackage + VendorCompatibilityStrings []string `xml:"VendorCompatibilityStrings,omitempty"` + OtherPackageType string `xml:"OtherPackageType,omitempty"` + Weight int `xml:"Weight,omitempty"` + Width int `xml:"Width,omitempty"` + Depth int `xml:"Depth,omitempty"` + Height int `xml:"Height,omitempty"` + RemovalConditions int `xml:"RemovalConditions,omitempty"` + Removable bool `xml:"Removable,omitempty"` + Replaceable bool `xml:"Replaceable,omitempty"` + HotSwappable bool `xml:"HotSwappable,omitempty"` + CableManagementStrategy string `xml:"CableManagementStrategy,omitempty"` + ServicePhilosophy int `xml:"ServicePhilosophy,omitempty"` + ServiceDescriptions []string `xml:"ServiceDescriptions,omitempty"` + LockPresent bool `xml:"LockPresent,omitempty"` + AudibleAlarm bool `xml:"AudibleAlarm,omitempty"` + VisibleAlarm bool `xml:"VisibleAlarm,omitempty"` + SecurityBreach int `xml:"SecurityBreach,omitempty"` + BreachDescription string `xml:"BreachDescription,omitempty"` + IsLocked bool `xml:"IsLocked,omitempty"` + } +) type Chassis struct { PhysicalFrame @@ -485,30 +487,34 @@ type ServiceAccessPoint struct { CreationClassName string `xml:"CreationClassName,omitempty"` } -type OverwritePolicy int -type LogState int -type CapabilitiesValues int -type LastChange int -type CharacterSet int -type BootConfigSettingInstanceID string -type FailThroughSupported int -type RemovalConditions int -type PackageType int -type ServicePhilosophy int -type SecurityBreach int -type ChassisPackageType int -type SoftwareElementState int -type TargetOperatingSystem int +type ( + OverwritePolicy int + LogState int + CapabilitiesValues int + LastChange int + CharacterSet int + BootConfigSettingInstanceID string + FailThroughSupported int + RemovalConditions int + PackageType int + ServicePhilosophy int + SecurityBreach int + ChassisPackageType int + SoftwareElementState int + TargetOperatingSystem int +) // ServerCertificateNameComparison represents the ServerCertificateNameComparison type for IEEE8021xProfile. type ServerCertificateNameComparison int // PowerState represents the PowerState type in the PowerManagementService namespace. -type UpgradeMethod int -type CPUStatus int -type OperationalStatus int -type HealthState int -type EnabledState int -type RequestedState int -type EnabledDefault int +type ( + UpgradeMethod int + CPUStatus int + OperationalStatus int + HealthState int + EnabledState int + RequestedState int + EnabledDefault int +) diff --git a/pkg/wsman/cim/physical/decoder.go b/pkg/wsman/cim/physical/decoder.go index 26dcfc87..a56eb973 100644 --- a/pkg/wsman/cim/physical/decoder.go +++ b/pkg/wsman/cim/physical/decoder.go @@ -6,16 +6,17 @@ package physical const ( - CIM_PhysicalMemory string = "CIM_PhysicalMemory" - CIM_PhysicalPackage string = "CIM_PhysicalPackage" + CIMPhysicalMemory string = "CIM_PhysicalMemory" + CIMPhysicalPackage string = "CIM_PhysicalPackage" + ValueNotFound string = "Value not found in map" ) const ( MemoryTypeUnknown MemoryType = iota MemoryTypeOther MemoryTypeDRAM - MemoryTypeSynchronous_DRAM - MemoryTypeCache_DRAM + MemoryTypeSynchronousDRAM + MemoryTypeCacheDRAM MemoryTypeEDO MemoryTypeEDRAM MemoryTypeVRAM @@ -50,13 +51,13 @@ const ( MemoryTypeHBM3 ) -// memoryTypeMap is a map of the MemoryType enumeration +// memoryTypeMap is a map of the MemoryType enumeration. var memoryTypeMap = map[MemoryType]string{ MemoryTypeUnknown: "Unknown", MemoryTypeOther: "Other", MemoryTypeDRAM: "DRAM", - MemoryTypeSynchronous_DRAM: "SynchronousDRAM", - MemoryTypeCache_DRAM: "CacheDRAM", + MemoryTypeSynchronousDRAM: "SynchronousDRAM", + MemoryTypeCacheDRAM: "CacheDRAM", MemoryTypeEDO: "EDO", MemoryTypeEDRAM: "EDRAM", MemoryTypeVRAM: "VRAM", @@ -91,12 +92,13 @@ var memoryTypeMap = map[MemoryType]string{ MemoryTypeHBM3: "HBM3", } -// String returns a human-readable string representation of the MemoryType enumeration +// String returns a human-readable string representation of the MemoryType enumeration. func (e MemoryType) String() string { if s, ok := memoryTypeMap[e]; ok { return s } - return "Value not found in map" + + return ValueNotFound } const ( @@ -122,7 +124,7 @@ const ( OperationalStatusRelocating ) -// operationalStatusMap is a map of the OperationalStatus enumeration +// operationalStatusMap is a map of the OperationalStatus enumeration. var operationalStatusMap = map[OperationalStatus]string{ OperationalStatusUnknown: "Unknown", OperationalStatusOther: "Other", @@ -146,10 +148,11 @@ var operationalStatusMap = map[OperationalStatus]string{ OperationalStatusRelocating: "Relocating", } -// String returns a human-readable string representation of the OperationalStatus enumeration +// String returns a human-readable string representation of the OperationalStatus enumeration. func (e OperationalStatus) String() string { if s, ok := operationalStatusMap[e]; ok { return s } - return "Value not found in map" + + return ValueNotFound } diff --git a/pkg/wsman/cim/physical/decoder_test.go b/pkg/wsman/cim/physical/decoder_test.go index 1f6d6fa2..d2773f70 100644 --- a/pkg/wsman/cim/physical/decoder_test.go +++ b/pkg/wsman/cim/physical/decoder_test.go @@ -15,8 +15,8 @@ func TestMemoryType_String(t *testing.T) { {MemoryTypeUnknown, "Unknown"}, {MemoryTypeOther, "Other"}, {MemoryTypeDRAM, "DRAM"}, - {MemoryTypeSynchronous_DRAM, "SynchronousDRAM"}, - {MemoryTypeCache_DRAM, "CacheDRAM"}, + {MemoryTypeSynchronousDRAM, "SynchronousDRAM"}, + {MemoryTypeCacheDRAM, "CacheDRAM"}, {MemoryTypeEDO, "EDO"}, {MemoryTypeEDRAM, "EDRAM"}, {MemoryTypeVRAM, "VRAM"}, diff --git a/pkg/wsman/cim/physical/marshal.go b/pkg/wsman/cim/physical/marshal.go index caea1538..35a3e954 100644 --- a/pkg/wsman/cim/physical/marshal.go +++ b/pkg/wsman/cim/physical/marshal.go @@ -11,20 +11,22 @@ import ( "gopkg.in/yaml.v3" ) -// JSON marshals the type into JSON format +// JSON marshals the type into JSON format. func (r *Response) JSON() string { jsonOutput, err := json.Marshal(r.Body) if err != nil { return "" } + return string(jsonOutput) } -// YAML marshals the type into YAML format +// YAML marshals the type into YAML format. func (r *Response) YAML() string { yamlOutput, err := yaml.Marshal(r.Body) if err != nil { return "" } + return string(yamlOutput) } diff --git a/pkg/wsman/cim/physical/memory.go b/pkg/wsman/cim/physical/memory.go index f5a8401f..4b3730f3 100644 --- a/pkg/wsman/cim/physical/memory.go +++ b/pkg/wsman/cim/physical/memory.go @@ -16,15 +16,14 @@ import ( // NewPhysicalMemory returns a new instance of the PhysicalMemory struct. func NewPhysicalMemoryWithClient(wsmanMessageCreator *message.WSManMessageCreator, client client.WSMan) Memory { return Memory{ - base: message.NewBaseWithClient(wsmanMessageCreator, CIM_PhysicalMemory, client), - client: client, + base: message.NewBaseWithClient(wsmanMessageCreator, CIMPhysicalMemory, client), } } // TODO: Figure out how to call GET requiring resourceURIs and Selectors // Get retrieves the representation of the instance -// Enumerate returns an enumeration context which is used in a subsequent Pull call +// Enumerate returns an enumeration context which is used in a subsequent Pull call. func (memory Memory) Enumerate() (response Response, err error) { response = Response{ Message: &client.Message{ @@ -41,8 +40,8 @@ func (memory Memory) Enumerate() (response Response, err error) { if err != nil { return } - return + return } // Pull returns the instances of this class. An enumeration context provided by the Enumerate call is used as input. @@ -52,13 +51,16 @@ func (memory Memory) Pull(enumerationContext string) (response Response, err err XMLInput: memory.base.Pull(enumerationContext), }, } + err = memory.base.Execute(response.Message) if err != nil { return } + err = xml.Unmarshal([]byte(response.XMLOutput), &response) if err != nil { return } + return } diff --git a/pkg/wsman/cim/physical/memory_test.go b/pkg/wsman/cim/physical/memory_test.go index 970dd9a4..b2686345 100644 --- a/pkg/wsman/cim/physical/memory_test.go +++ b/pkg/wsman/cim/physical/memory_test.go @@ -9,11 +9,10 @@ import ( "encoding/xml" "testing" - "github.com/stretchr/testify/assert" - "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/internal/message" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/common" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/wsmantesting" + "github.com/stretchr/testify/assert" ) func TestJson(t *testing.T) { @@ -40,8 +39,8 @@ func TestYaml(t *testing.T) { func TestPositiveCIMMemory(t *testing.T) { messageID := 0 - resourceUriBase := "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.CIMResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "cim/physical/memory", } @@ -56,30 +55,33 @@ func TestPositiveCIMMemory(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //ENUMERATES + // ENUMERATES { "should create and parse a valid cim_PhysicalMemory Enumerate call", "CIM_PhysicalMemory", - wsmantesting.ENUMERATE, - wsmantesting.ENUMERATE_BODY, + wsmantesting.Enumerate, + wsmantesting.EnumerateBody, func() (Response, error) { - client.CurrentMessage = "Enumerate" + client.CurrentMessage = wsmantesting.CurrentMessageEnumerate + return elementUnderTest.Enumerate() - }, Body{ + }, + Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, EnumerateResponse: common.EnumerateResponse{ EnumerationContext: "D6020000-0000-0000-0000-000000000000", }, }, }, - //PULLS + // PULLS { "should create and parse a valid cim_PhysicalMemory Pull call", "CIM_PhysicalMemory", - wsmantesting.PULL, - wsmantesting.PULL_BODY, + wsmantesting.Pull, + wsmantesting.PullBody, func() (Response, error) { - client.CurrentMessage = "Pull" + client.CurrentMessage = wsmantesting.CurrentMessagePull + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -129,7 +131,7 @@ func TestPositiveCIMMemory(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, "", test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, "", test.body) messageID++ response, err := test.responseFunc() assert.NoError(t, err) @@ -139,10 +141,11 @@ func TestPositiveCIMMemory(t *testing.T) { } }) } + func TestNegativeCIMMemory(t *testing.T) { messageID := 0 - resourceUriBase := "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.CIMResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "cim/physical/memory", } @@ -157,30 +160,33 @@ func TestNegativeCIMMemory(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //ENUMERATES + // ENUMERATES { "should create and parse a valid cim_PhysicalMemory Enumerate call", "CIM_PhysicalMemory", - wsmantesting.ENUMERATE, - wsmantesting.ENUMERATE_BODY, + wsmantesting.Enumerate, + wsmantesting.EnumerateBody, func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Enumerate() - }, Body{ + }, + Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, EnumerateResponse: common.EnumerateResponse{ EnumerationContext: "D6020000-0000-0000-0000-000000000000", }, }, }, - //PULLS + // PULLS { "should create and parse a valid cim_PhysicalMemory Pull call", "CIM_PhysicalMemory", - wsmantesting.PULL, - wsmantesting.PULL_BODY, + wsmantesting.Pull, + wsmantesting.PullBody, func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -230,7 +236,7 @@ func TestNegativeCIMMemory(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, "", test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, "", test.body) messageID++ response, err := test.responseFunc() assert.Error(t, err) diff --git a/pkg/wsman/cim/physical/package.go b/pkg/wsman/cim/physical/package.go index 924e0ed9..28990505 100644 --- a/pkg/wsman/cim/physical/package.go +++ b/pkg/wsman/cim/physical/package.go @@ -15,15 +15,14 @@ import ( // NewPhysicalPackage returns a new instance of the PhysicalPackage struct. func NewPhysicalPackageWithClient(wsmanMessageCreator *message.WSManMessageCreator, client client.WSMan) Package { return Package{ - base: message.NewBaseWithClient(wsmanMessageCreator, CIM_PhysicalPackage, client), - client: client, + base: message.NewBaseWithClient(wsmanMessageCreator, CIMPhysicalPackage, client), } } // TODO: Figure out how to call GET requiring resourceURIs and Selectors // Get retrieves the representation of the instance -// Enumerate returns an enumeration context which is used in a subsequent Pull call +// Enumerate returns an enumeration context which is used in a subsequent Pull call. func (physicalPackage Package) Enumerate() (response Response, err error) { response = Response{ Message: &client.Message{ @@ -40,8 +39,8 @@ func (physicalPackage Package) Enumerate() (response Response, err error) { if err != nil { return } - return + return } // Pull returns the instances of this class. An enumeration context provided by the Enumerate call is used as input. @@ -51,13 +50,16 @@ func (physicalPackage Package) Pull(enumerationContext string) (response Respons XMLInput: physicalPackage.base.Pull(enumerationContext), }, } + err = physicalPackage.base.Execute(response.Message) if err != nil { return } + err = xml.Unmarshal([]byte(response.XMLOutput), &response) if err != nil { return } + return } diff --git a/pkg/wsman/cim/physical/package_test.go b/pkg/wsman/cim/physical/package_test.go index ddd70df9..20d6c2d6 100644 --- a/pkg/wsman/cim/physical/package_test.go +++ b/pkg/wsman/cim/physical/package_test.go @@ -9,18 +9,17 @@ import ( "encoding/xml" "testing" - "github.com/stretchr/testify/assert" - "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/internal/message" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/cim/card" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/common" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/wsmantesting" + "github.com/stretchr/testify/assert" ) func TestPositiveCIMPackage(t *testing.T) { messageID := 0 - resourceUriBase := "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.CIMResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "cim/physical/package", } @@ -35,14 +34,15 @@ func TestPositiveCIMPackage(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //ENUMERATES + // ENUMERATES { "should create a valid cim_PhysicalPackage Enumerate wsman message", - CIM_PhysicalPackage, - wsmantesting.ENUMERATE, - wsmantesting.ENUMERATE_BODY, + CIMPhysicalPackage, + wsmantesting.Enumerate, + wsmantesting.EnumerateBody, func() (Response, error) { - client.CurrentMessage = "Enumerate" + client.CurrentMessage = wsmantesting.CurrentMessageEnumerate + return elementUnderTest.Enumerate() }, Body{ @@ -52,14 +52,15 @@ func TestPositiveCIMPackage(t *testing.T) { }, }, }, - //PULLS + // PULLS { "should create a valid cim_PhysicalPackage Pull wsman message", - CIM_PhysicalPackage, - wsmantesting.PULL, - wsmantesting.PULL_BODY, + CIMPhysicalPackage, + wsmantesting.Pull, + wsmantesting.PullBody, func() (Response, error) { - client.CurrentMessage = "Pull" + client.CurrentMessage = wsmantesting.CurrentMessagePull + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -91,7 +92,7 @@ func TestPositiveCIMPackage(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, "", test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, "", test.body) messageID++ response, err := test.responseFunc() assert.NoError(t, err) @@ -101,10 +102,11 @@ func TestPositiveCIMPackage(t *testing.T) { } }) } + func TestNegativeCIMPackage(t *testing.T) { messageID := 0 - resourceUriBase := "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.CIMResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "cim/physical/package", } @@ -119,14 +121,15 @@ func TestNegativeCIMPackage(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //ENUMERATES + // ENUMERATES { "should create a valid cim_PhysicalPackage Enumerate wsman message", - CIM_PhysicalPackage, - wsmantesting.ENUMERATE, - wsmantesting.ENUMERATE_BODY, + CIMPhysicalPackage, + wsmantesting.Enumerate, + wsmantesting.EnumerateBody, func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Enumerate() }, Body{ @@ -136,14 +139,15 @@ func TestNegativeCIMPackage(t *testing.T) { }, }, }, - //PULLS + // PULLS { "should create a valid cim_PhysicalPackage Pull wsman message", - CIM_PhysicalPackage, - wsmantesting.PULL, - wsmantesting.PULL_BODY, + CIMPhysicalPackage, + wsmantesting.Pull, + wsmantesting.PullBody, func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -175,7 +179,7 @@ func TestNegativeCIMPackage(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, "", test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, "", test.body) messageID++ response, err := test.responseFunc() assert.Error(t, err) diff --git a/pkg/wsman/cim/physical/types.go b/pkg/wsman/cim/physical/types.go index 97134e3b..0799e45b 100644 --- a/pkg/wsman/cim/physical/types.go +++ b/pkg/wsman/cim/physical/types.go @@ -15,16 +15,14 @@ import ( ) type Memory struct { - base message.Base - client client.WSMan + base message.Base } type Package struct { - base message.Base - client client.WSMan + base message.Base } -// Response Types +// Response Types. type ( Response struct { *client.Message diff --git a/pkg/wsman/cim/power/decoder.go b/pkg/wsman/cim/power/decoder.go index cf076198..b4481247 100644 --- a/pkg/wsman/cim/power/decoder.go +++ b/pkg/wsman/cim/power/decoder.go @@ -6,55 +6,56 @@ package power const ( - CIM_PowerManagementService string = "CIM_PowerManagementService" - RequestPowerStateChange string = "RequestPowerStateChange" + CIMPowerManagementService string = "CIM_PowerManagementService" + RequestPowerStateChange string = "RequestPowerStateChange" + ValueNotFound string = "Value not found in map" ) -// TODO: This list of contants needs to be scrubbed +// TODO: This list of contants needs to be scrubbed. const ( - // Power On + // Power On. PowerOn PowerState = 2 // Verified Hardware Power On - // Sleep - Light + // Sleep - Light. SleepLight PowerState = 3 // ? - // Sleep - Deep + // Sleep - Deep. SleepDeep PowerState = 4 // ? - // Power Cycle (Off Soft) + // Power Cycle (Off Soft). PowerCycleOffSoft PowerState = 6 // ? - // Power Off - Hard + // Power Off - Hard. PowerOffHard PowerState = 8 // Verfied Hardware Power Off - // Hibernate + // Hibernate. Hibernate PowerState = 7 // ? - // Power Off - Soft + // Power Off - Soft. PowerOffSoft PowerState = 9 // ? - // Power Cycle (Off Hard) + // Power Cycle (Off Hard). PowerCycleOffHard PowerState = 5 // Verified Hardware Power Cycle (off then on) - // Master Bus Reset + // Master Bus Reset. MasterBusReset PowerState = 10 // Verified Hardware Reboot - // Diagnostic Interrupt (NMI) + // Diagnostic Interrupt (NMI). DiagnosticInterruptNMI PowerState = 11 // ? - // Power Off - Soft Graceful + // Power Off - Soft Graceful. PowerOffSoftGraceful PowerState = 12 // ? - // Power Off - Hard Graceful + // Power Off - Hard Graceful. PowerOffHardGraceful PowerState = 13 // ? - // Master Bus Reset Graceful + // Master Bus Reset Graceful. MasterBusResetGraceful PowerState = 14 // ? - // Power Cycle (Off - Soft Graceful) + // Power Cycle (Off - Soft Graceful). PowerCycleOffSoftGraceful PowerState = 15 // ? - // Power Cycle (Off - Hard Graceful) + // Power Cycle (Off - Hard Graceful). PowerCycleOffHardGraceful PowerState = 16 // ? ) @@ -72,7 +73,7 @@ const ( EnabledStateStarting ) -// enabledStateMap is a map of the EnabledState enumeration +// enabledStateMap is a map of the EnabledState enumeration. var enabledStateMap = map[EnabledState]string{ EnabledStateUnknown: "Unknown", EnabledStateOther: "Other", @@ -87,12 +88,13 @@ var enabledStateMap = map[EnabledState]string{ EnabledStateStarting: "Starting", } -// String returns a human-readable string representation of the EnabledState enumeration +// String returns a human-readable string representation of the EnabledState enumeration. func (e EnabledState) String() string { if s, ok := enabledStateMap[e]; ok { return s } - return "Value not found in map" + + return ValueNotFound } const ( @@ -110,7 +112,7 @@ const ( RequestedStateNotApplicable RequestedState = 12 ) -// requestedStateMap is a map of the RequestedState enumeration +// requestedStateMap is a map of the RequestedState enumeration. var requestedStateMap = map[RequestedState]string{ RequestedStateUnknown: "Unknown", RequestedStateEnabled: "Enabled", @@ -126,12 +128,13 @@ var requestedStateMap = map[RequestedState]string{ RequestedStateNotApplicable: "NotApplicable", } -// String returns a human-readable string representation of the RequestedState enumeration +// String returns a human-readable string representation of the RequestedState enumeration. func (e RequestedState) String() string { if s, ok := requestedStateMap[e]; ok { return s } - return "Value not found in map" + + return ValueNotFound } const ( @@ -148,7 +151,7 @@ const ( ReturnValueBusy ReturnValue = 4099 ) -// returnValueMap is a map of the ReturnValue enumeration +// returnValueMap is a map of the ReturnValue enumeration. var returnValueMap = map[ReturnValue]string{ ReturnValueCompletedWithNoError: "CompletedWithNoError", ReturnValueMethodNotSupported: "MethodNotSupported", @@ -163,10 +166,11 @@ var returnValueMap = map[ReturnValue]string{ ReturnValueBusy: "Busy", } -// String returns a human-readable string representation of the ReturnValue enumeration +// String returns a human-readable string representation of the ReturnValue enumeration. func (e ReturnValue) String() string { if s, ok := returnValueMap[e]; ok { return s } - return "Value not found in map" + + return ValueNotFound } diff --git a/pkg/wsman/cim/power/managementservice.go b/pkg/wsman/cim/power/managementservice.go index bf627e41..69e9eff3 100644 --- a/pkg/wsman/cim/power/managementservice.go +++ b/pkg/wsman/cim/power/managementservice.go @@ -20,20 +20,20 @@ import ( // NewPowerManagementService returns a new instance of the PowerManagementService struct. func NewPowerManagementServiceWithClient(wsmanMessageCreator *message.WSManMessageCreator, client client.WSMan) ManagementService { return ManagementService{ - base: message.NewBaseWithClient(wsmanMessageCreator, CIM_PowerManagementService, client), - client: client, + base: message.NewBaseWithClient(wsmanMessageCreator, CIMPowerManagementService, client), } } // RequestPowerStateChange defines the desired power state of the managed element, and when the element should be put into that state. func (managementService ManagementService) RequestPowerStateChange(powerState PowerState) (response Response, err error) { - header := managementService.base.WSManMessageCreator.CreateHeader(methods.GenerateAction(CIM_PowerManagementService, RequestPowerStateChange), CIM_PowerManagementService, nil, "", "") + header := managementService.base.WSManMessageCreator.CreateHeader(methods.GenerateAction(CIMPowerManagementService, RequestPowerStateChange), CIMPowerManagementService, nil, "", "") body := fmt.Sprintf(`%d
http://schemas.xmlsoap.org/ws/2004/08/addressing
http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ComputerSystemCIM_ComputerSystemManagedSystem
`, powerState) response = Response{ Message: &client.Message{ XMLInput: managementService.base.WSManMessageCreator.CreateXML(header, body), }, } + // send the message to AMT err = managementService.base.Execute(response.Message) if err != nil { @@ -49,7 +49,7 @@ func (managementService ManagementService) RequestPowerStateChange(powerState Po return } -// Get retrieves the representation of the instance +// Get retrieves the representation of the instance. func (managementService ManagementService) Get() (response Response, err error) { response = Response{ Message: &client.Message{ @@ -66,11 +66,11 @@ func (managementService ManagementService) Get() (response Response, err error) if err != nil { return } - return + return } -// // Enumerate returns an enumeration context which is used in a subsequent Pull call +// // Enumerate returns an enumeration context which is used in a subsequent Pull call. func (managementService ManagementService) Enumerate() (response Response, err error) { response = Response{ Message: &client.Message{ @@ -87,6 +87,7 @@ func (managementService ManagementService) Enumerate() (response Response, err e if err != nil { return } + return } @@ -97,13 +98,16 @@ func (managementService ManagementService) Pull(enumerationContext string) (resp XMLInput: managementService.base.Pull(enumerationContext), }, } + err = managementService.base.Execute(response.Message) if err != nil { return } + err = xml.Unmarshal([]byte(response.XMLOutput), &response) if err != nil { return } + return } diff --git a/pkg/wsman/cim/power/managementservice_test.go b/pkg/wsman/cim/power/managementservice_test.go index 921690f4..3a325336 100644 --- a/pkg/wsman/cim/power/managementservice_test.go +++ b/pkg/wsman/cim/power/managementservice_test.go @@ -17,7 +17,7 @@ import ( ) const ( - RequestPowerStateChange_BODY = "8
http://schemas.xmlsoap.org/ws/2004/08/addressing
http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ComputerSystemCIM_ComputerSystemManagedSystem
" + RequestPowerStateChangeBODY = "8
http://schemas.xmlsoap.org/ws/2004/08/addressing
http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ComputerSystemCIM_ComputerSystemManagedSystem
" ) func TestJson(t *testing.T) { @@ -44,8 +44,8 @@ func TestYaml(t *testing.T) { func TestPositiveCIMPowerManagementService(t *testing.T) { messageID := 0 - resourceUriBase := "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.CIMResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "cim/power/managementservice", } @@ -62,12 +62,13 @@ func TestPositiveCIMPowerManagementService(t *testing.T) { }{ { "Should issue a valid cim_PowerManagementService RequestPowerStateChange call", - CIM_PowerManagementService, - methods.GenerateAction(CIM_PowerManagementService, RequestPowerStateChange), - RequestPowerStateChange_BODY, + CIMPowerManagementService, + methods.GenerateAction(CIMPowerManagementService, RequestPowerStateChange), + RequestPowerStateChangeBODY, func() (Response, error) { client.CurrentMessage = "RequestPowerStateChange" - var powerState PowerState = PowerOffHard + powerState := PowerOffHard + return elementUnderTest.RequestPowerStateChange(powerState) }, Body{ @@ -79,11 +80,12 @@ func TestPositiveCIMPowerManagementService(t *testing.T) { }, { "Should issue a valid cim_PowerManagementService Get call", - CIM_PowerManagementService, - wsmantesting.GET, + CIMPowerManagementService, + wsmantesting.Get, "", func() (Response, error) { - client.CurrentMessage = "Get" + client.CurrentMessage = wsmantesting.CurrentMessageGet + return elementUnderTest.Get() }, Body{ @@ -102,11 +104,12 @@ func TestPositiveCIMPowerManagementService(t *testing.T) { }, { "Should issue a valid cim_PowerManagementService Enumerate call", - CIM_PowerManagementService, - wsmantesting.ENUMERATE, - wsmantesting.ENUMERATE_BODY, + CIMPowerManagementService, + wsmantesting.Enumerate, + wsmantesting.EnumerateBody, func() (Response, error) { - client.CurrentMessage = "Enumerate" + client.CurrentMessage = wsmantesting.CurrentMessageEnumerate + return elementUnderTest.Enumerate() }, Body{ @@ -118,11 +121,12 @@ func TestPositiveCIMPowerManagementService(t *testing.T) { }, { "Should issue a valid cim_PowerManagementService Pull call", - CIM_PowerManagementService, - wsmantesting.PULL, - wsmantesting.PULL_BODY, + CIMPowerManagementService, + wsmantesting.Pull, + wsmantesting.PullBody, func() (Response, error) { - client.CurrentMessage = "Pull" + client.CurrentMessage = wsmantesting.CurrentMessagePull + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -148,13 +152,12 @@ func TestPositiveCIMPowerManagementService(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, "", test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, "", test.body) messageID++ response, err := test.responseFunc() assert.NoError(t, err) assert.Equal(t, expectedXMLInput, response.XMLInput) assert.Equal(t, test.expectedResponse, response.Body) - }) } }) @@ -162,8 +165,8 @@ func TestPositiveCIMPowerManagementService(t *testing.T) { func TestNegativeCIMPowerManagementService(t *testing.T) { messageID := 0 - resourceUriBase := "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.CIMResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "cim/power/managementservice", } @@ -180,12 +183,13 @@ func TestNegativeCIMPowerManagementService(t *testing.T) { }{ { "Should issue a valid cim_PowerManagementService RequestPowerStateChange call", - CIM_PowerManagementService, - methods.GenerateAction(CIM_PowerManagementService, RequestPowerStateChange), - RequestPowerStateChange_BODY, + CIMPowerManagementService, + methods.GenerateAction(CIMPowerManagementService, RequestPowerStateChange), + RequestPowerStateChangeBODY, func() (Response, error) { - client.CurrentMessage = "Error" - var powerState PowerState = PowerOffHard + client.CurrentMessage = wsmantesting.CurrentMessageError + powerState := PowerOffHard + return elementUnderTest.RequestPowerStateChange(powerState) }, Body{ @@ -197,11 +201,12 @@ func TestNegativeCIMPowerManagementService(t *testing.T) { }, { "Should issue a valid cim_PowerManagementService Get call", - CIM_PowerManagementService, - wsmantesting.GET, + CIMPowerManagementService, + wsmantesting.Get, "", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Get() }, Body{ @@ -220,11 +225,12 @@ func TestNegativeCIMPowerManagementService(t *testing.T) { }, { "Should issue a valid cim_PowerManagementService Enumerate call", - CIM_PowerManagementService, - wsmantesting.ENUMERATE, - wsmantesting.ENUMERATE_BODY, + CIMPowerManagementService, + wsmantesting.Enumerate, + wsmantesting.EnumerateBody, func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Enumerate() }, Body{ @@ -236,11 +242,12 @@ func TestNegativeCIMPowerManagementService(t *testing.T) { }, { "Should issue a valid cim_PowerManagementService Pull call", - CIM_PowerManagementService, - wsmantesting.PULL, - wsmantesting.PULL_BODY, + CIMPowerManagementService, + wsmantesting.Pull, + wsmantesting.PullBody, func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -266,13 +273,12 @@ func TestNegativeCIMPowerManagementService(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, "", test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, "", test.body) messageID++ response, err := test.responseFunc() assert.Error(t, err) assert.Equal(t, expectedXMLInput, response.XMLInput) assert.NotEqual(t, test.expectedResponse, response.Body) - }) } }) diff --git a/pkg/wsman/cim/power/marshal.go b/pkg/wsman/cim/power/marshal.go index 0a771f96..6b12a61c 100644 --- a/pkg/wsman/cim/power/marshal.go +++ b/pkg/wsman/cim/power/marshal.go @@ -11,20 +11,22 @@ import ( "gopkg.in/yaml.v3" ) -// JSON marshals the type into JSON format +// JSON marshals the type into JSON format. func (r *Response) JSON() string { jsonOutput, err := json.Marshal(r.Body) if err != nil { return "" } + return string(jsonOutput) } -// YAML marshals the type into YAML format +// YAML marshals the type into YAML format. func (r *Response) YAML() string { yamlOutput, err := yaml.Marshal(r.Body) if err != nil { return "" } + return string(yamlOutput) } diff --git a/pkg/wsman/cim/power/types.go b/pkg/wsman/cim/power/types.go index aa803068..39adf77e 100644 --- a/pkg/wsman/cim/power/types.go +++ b/pkg/wsman/cim/power/types.go @@ -14,13 +14,12 @@ import ( ) type ManagementService struct { - base message.Base - client client.WSMan + base message.Base } type PowerState int -// Response Types +// Response Types. type ( Response struct { *client.Message diff --git a/pkg/wsman/cim/processor/decoder.go b/pkg/wsman/cim/processor/decoder.go index 5b1d9180..5212e071 100644 --- a/pkg/wsman/cim/processor/decoder.go +++ b/pkg/wsman/cim/processor/decoder.go @@ -5,7 +5,10 @@ package processor -const CIM_Processor string = "CIM_Processor" +const ( + CIMProcessor string = "CIM_Processor" + ValueNotFound string = "Value not found in map" +) const ( OperationalStatusUnknown OperationalStatus = iota @@ -30,7 +33,7 @@ const ( OperationalStatusRelocating ) -// operationalStatusMap is a map of the OperationalStatus enumeration +// operationalStatusMap is a map of the OperationalStatus enumeration. var operationalStatusMap = map[OperationalStatus]string{ OperationalStatusUnknown: "Unknown", OperationalStatusOther: "Other", @@ -54,12 +57,13 @@ var operationalStatusMap = map[OperationalStatus]string{ OperationalStatusRelocating: "Relocating", } -// String returns a human-readable string representation of the OperationalStatus enumeration +// String returns a human-readable string representation of the OperationalStatus enumeration. func (e OperationalStatus) String() string { if s, ok := operationalStatusMap[e]; ok { return s } - return "Value not found in map" + + return ValueNotFound } const ( @@ -72,7 +76,7 @@ const ( HealthStateNonRecoverableError HealthState = 30 ) -// healthStateMap is a map of the HealthState enumeration +// healthStateMap is a map of the HealthState enumeration. var healthStateMap = map[HealthState]string{ HealthStateUnknown: "Unknown", HealthStateOK: "OK", @@ -83,12 +87,13 @@ var healthStateMap = map[HealthState]string{ HealthStateNonRecoverableError: "NonRecoverableError", } -// String returns a human-readable string representation of the HealthState enumeration +// String returns a human-readable string representation of the HealthState enumeration. func (e HealthState) String() string { if s, ok := healthStateMap[e]; ok { return s } - return "Value not found in map" + + return ValueNotFound } const ( @@ -105,7 +110,7 @@ const ( EnabledStateStarting ) -// enabledStateMap is a map of the EnabledState enumeration +// enabledStateMap is a map of the EnabledState enumeration. var enabledStateMap = map[EnabledState]string{ EnabledStateDisabled: "Disabled", EnabledStateShuttingDown: "ShuttingDown", @@ -117,12 +122,13 @@ var enabledStateMap = map[EnabledState]string{ EnabledStateStarting: "Starting", } -// String returns a human-readable string representation of the EnabledState enumeration +// String returns a human-readable string representation of the EnabledState enumeration. func (e EnabledState) String() string { if s, ok := enabledStateMap[e]; ok { return s } - return "Value not found in map" + + return ValueNotFound } const ( @@ -140,7 +146,7 @@ const ( RequestedStateNotApplicable ) -// requestedStateMap is a map of the RequestedState enumeration +// requestedStateMap is a map of the RequestedState enumeration. var requestedStateMap = map[RequestedState]string{ RequestedStateEnabled: "Enabled", RequestedStateDisabled: "Disabled", @@ -155,12 +161,13 @@ var requestedStateMap = map[RequestedState]string{ RequestedStateNotApplicable: "NotApplicable", } -// String returns a human-readable string representation of the RequestedState enumeration +// String returns a human-readable string representation of the RequestedState enumeration. func (e RequestedState) String() string { if s, ok := requestedStateMap[e]; ok { return s } - return "Value not found in map" + + return ValueNotFound } const ( @@ -251,7 +258,7 @@ const ( UpgradeMethodSocketBGA2833 ) -// upgradeMethodMap is a map of the UpgradeMethod enumeration +// upgradeMethodMap is a map of the UpgradeMethod enumeration. var upgradeMethodMap = map[UpgradeMethod]string{ UpgradeMethodOther: "Other", UpgradeMethodUnknown: "Unknown", @@ -340,12 +347,13 @@ var upgradeMethodMap = map[UpgradeMethod]string{ UpgradeMethodSocketBGA2833: "SocketBGA2833", } -// String returns a human-readable string representation of the UpgradeMethod enumeration +// String returns a human-readable string representation of the UpgradeMethod enumeration. func (e UpgradeMethod) String() string { if s, ok := upgradeMethodMap[e]; ok { return s } - return "Value not found in map" + + return ValueNotFound } const ( @@ -357,7 +365,7 @@ const ( CPUStatusOther ) -// cpuStatusMap is a map of the CPUStatus enumeration +// cpuStatusMap is a map of the CPUStatus enumeration. var cpuStatusMap = map[CPUStatus]string{ CPUStatusUnknown: "Unknown", CPUStatusCPUEnabled: "CPUEnabled", @@ -367,10 +375,11 @@ var cpuStatusMap = map[CPUStatus]string{ CPUStatusOther: "Other", } -// String returns a human-readable string representation of the CPUStatus enumeration +// String returns a human-readable string representation of the CPUStatus enumeration. func (e CPUStatus) String() string { if s, ok := cpuStatusMap[e]; ok { return s } - return "Value not found in map" + + return ValueNotFound } diff --git a/pkg/wsman/cim/processor/marshal.go b/pkg/wsman/cim/processor/marshal.go index ab6c506b..e0c62ac5 100644 --- a/pkg/wsman/cim/processor/marshal.go +++ b/pkg/wsman/cim/processor/marshal.go @@ -11,20 +11,22 @@ import ( "gopkg.in/yaml.v3" ) -// JSON marshals the type into JSON format +// JSON marshals the type into JSON format. func (r *Response) JSON() string { jsonOutput, err := json.Marshal(r.Body) if err != nil { return "" } + return string(jsonOutput) } -// YAML marshals the type into YAML format +// YAML marshals the type into YAML format. func (r *Response) YAML() string { yamlOutput, err := yaml.Marshal(r.Body) if err != nil { return "" } + return string(yamlOutput) } diff --git a/pkg/wsman/cim/processor/processor.go b/pkg/wsman/cim/processor/processor.go index 9a2c0b6b..dcc8f324 100644 --- a/pkg/wsman/cim/processor/processor.go +++ b/pkg/wsman/cim/processor/processor.go @@ -16,12 +16,11 @@ import ( // NewProcessor returns a new instance of the Processor struct. func NewProcessorWithClient(wsmanMessageCreator *message.WSManMessageCreator, client client.WSMan) Package { return Package{ - base: message.NewBaseWithClient(wsmanMessageCreator, CIM_Processor, client), - client: client, + base: message.NewBaseWithClient(wsmanMessageCreator, CIMProcessor, client), } } -// Get retrieves the representation of the instance +// Get retrieves the representation of the instance. func (processor Package) Get() (response Response, err error) { response = Response{ Message: &client.Message{ @@ -38,11 +37,11 @@ func (processor Package) Get() (response Response, err error) { if err != nil { return } - return + return } -// Enumerate returns an enumeration context which is used in a subsequent Pull call +// Enumerate returns an enumeration context which is used in a subsequent Pull call. func (processor Package) Enumerate() (response Response, err error) { response = Response{ Message: &client.Message{ @@ -59,8 +58,8 @@ func (processor Package) Enumerate() (response Response, err error) { if err != nil { return } - return + return } // Pull returns the instances of this class. An enumeration context provided by the Enumerate call is used as input. @@ -70,13 +69,16 @@ func (processor Package) Pull(enumerationContext string) (response Response, err XMLInput: processor.base.Pull(enumerationContext), }, } + err = processor.base.Execute(response.Message) if err != nil { return } + err = xml.Unmarshal([]byte(response.XMLOutput), &response) if err != nil { return } + return } diff --git a/pkg/wsman/cim/processor/processor_test.go b/pkg/wsman/cim/processor/processor_test.go index 7585a2b3..dc1f5b4e 100644 --- a/pkg/wsman/cim/processor/processor_test.go +++ b/pkg/wsman/cim/processor/processor_test.go @@ -9,11 +9,10 @@ import ( "encoding/xml" "testing" - "github.com/stretchr/testify/assert" - "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/internal/message" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/common" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/wsmantesting" + "github.com/stretchr/testify/assert" ) func TestJson(t *testing.T) { @@ -40,8 +39,8 @@ func TestYaml(t *testing.T) { func TestPositiveCIMProcessor(t *testing.T) { messageID := 0 - resourceUriBase := "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.CIMResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "cim/physical/processor", } @@ -56,16 +55,18 @@ func TestPositiveCIMProcessor(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //GETS + // GETS { "should create and parse a valid cim_Processor Get wsman call", - CIM_Processor, - wsmantesting.GET, + CIMProcessor, + wsmantesting.Get, "", func() (Response, error) { - client.CurrentMessage = "Get" + client.CurrentMessage = wsmantesting.CurrentMessageGet + return elementUnderTest.Get() - }, Body{ + }, + Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, PackageResponse: PackageResponse{ XMLName: xml.Name{Space: "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_Processor", Local: "CIM_Processor"}, @@ -90,30 +91,33 @@ func TestPositiveCIMProcessor(t *testing.T) { }, }, }, - //ENUMERATES + // ENUMERATES { "should create and parse a valid cim_Processor Enumerate wsman call", - CIM_Processor, - wsmantesting.ENUMERATE, - wsmantesting.ENUMERATE_BODY, + CIMProcessor, + wsmantesting.Enumerate, + wsmantesting.EnumerateBody, func() (Response, error) { - client.CurrentMessage = "Enumerate" + client.CurrentMessage = wsmantesting.CurrentMessageEnumerate + return elementUnderTest.Enumerate() - }, Body{ + }, + Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, EnumerateResponse: common.EnumerateResponse{ EnumerationContext: "D9020000-0000-0000-0000-000000000000", }, }, }, - //PULLS + // PULLS { "should create and parse a valid cim_Processor Pull wsman call", - CIM_Processor, - wsmantesting.PULL, - wsmantesting.PULL_BODY, + CIMProcessor, + wsmantesting.Pull, + wsmantesting.PullBody, func() (Response, error) { - client.CurrentMessage = "Pull" + client.CurrentMessage = wsmantesting.CurrentMessagePull + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -150,7 +154,7 @@ func TestPositiveCIMProcessor(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, "", test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, "", test.body) messageID++ response, err := test.responseFunc() assert.NoError(t, err) @@ -160,10 +164,11 @@ func TestPositiveCIMProcessor(t *testing.T) { } }) } + func TestNegativeCIMProcessor(t *testing.T) { messageID := 0 - resourceUriBase := "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.CIMResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "cim/physical/processor", } @@ -178,16 +183,18 @@ func TestNegativeCIMProcessor(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //GETS + // GETS { "should create and parse a valid cim_Processor Get wsman call", - CIM_Processor, - wsmantesting.GET, + CIMProcessor, + wsmantesting.Get, "", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Get() - }, Body{ + }, + Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, PackageResponse: PackageResponse{ XMLName: xml.Name{Space: "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_Processor", Local: "CIM_Processor"}, @@ -212,30 +219,33 @@ func TestNegativeCIMProcessor(t *testing.T) { }, }, }, - //ENUMERATES + // ENUMERATES { "should create and parse a valid cim_Processor Enumerate wsman call", - CIM_Processor, - wsmantesting.ENUMERATE, - wsmantesting.ENUMERATE_BODY, + CIMProcessor, + wsmantesting.Enumerate, + wsmantesting.EnumerateBody, func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Enumerate() - }, Body{ + }, + Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, EnumerateResponse: common.EnumerateResponse{ EnumerationContext: "D9020000-0000-0000-0000-000000000000", }, }, }, - //PULLS + // PULLS { "should create and parse a valid cim_Processor Pull wsman call", - CIM_Processor, - wsmantesting.PULL, - wsmantesting.PULL_BODY, + CIMProcessor, + wsmantesting.Pull, + wsmantesting.PullBody, func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -272,7 +282,7 @@ func TestNegativeCIMProcessor(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, "", test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, "", test.body) messageID++ response, err := test.responseFunc() assert.Error(t, err) diff --git a/pkg/wsman/cim/processor/types.go b/pkg/wsman/cim/processor/types.go index 6420b335..0daa6f1d 100644 --- a/pkg/wsman/cim/processor/types.go +++ b/pkg/wsman/cim/processor/types.go @@ -14,8 +14,7 @@ import ( ) type Package struct { - base message.Base - client client.WSMan + base message.Base } type ( diff --git a/pkg/wsman/cim/service/availabletoelement.go b/pkg/wsman/cim/service/availabletoelement.go index c56ee73a..307ff1e7 100644 --- a/pkg/wsman/cim/service/availabletoelement.go +++ b/pkg/wsman/cim/service/availabletoelement.go @@ -22,15 +22,14 @@ import ( // NewServiceAvailableToElement returns a new instance of the ServiceAvailableToElement struct. func NewServiceAvailableToElementWithClient(wsmanMessageCreator *message.WSManMessageCreator, client client.WSMan) AvailableToElement { return AvailableToElement{ - base: message.NewBaseWithClient(wsmanMessageCreator, CIM_ServiceAvailableToElement, client), - client: client, + base: message.NewBaseWithClient(wsmanMessageCreator, CIMServiceAvailableToElement, client), } } // TODO Figure out how to call GET requiring resourceURIs and Selectors // Get retrieves the representation of the instance. No route -// Enumerate returns an enumeration context which is used in a subsequent Pull call +// Enumerate returns an enumeration context which is used in a subsequent Pull call. func (availableToElement AvailableToElement) Enumerate() (response Response, err error) { response = Response{ Message: &client.Message{ @@ -47,8 +46,8 @@ func (availableToElement AvailableToElement) Enumerate() (response Response, err if err != nil { return } - return + return } // Pull returns the instances of this class. An enumeration context provided by the Enumerate call is used as input. @@ -58,13 +57,16 @@ func (availableToElement AvailableToElement) Pull(enumerationContext string) (re XMLInput: availableToElement.base.Pull(enumerationContext), }, } + err = availableToElement.base.Execute(response.Message) if err != nil { return } + err = xml.Unmarshal([]byte(response.XMLOutput), &response) if err != nil { return } + return } diff --git a/pkg/wsman/cim/service/availabletoelement_test.go b/pkg/wsman/cim/service/availabletoelement_test.go index 9d0a74bb..a160784d 100644 --- a/pkg/wsman/cim/service/availabletoelement_test.go +++ b/pkg/wsman/cim/service/availabletoelement_test.go @@ -9,11 +9,10 @@ import ( "encoding/xml" "testing" - "github.com/stretchr/testify/assert" - "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/internal/message" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/common" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/wsmantesting" + "github.com/stretchr/testify/assert" ) func TestJson(t *testing.T) { @@ -40,8 +39,8 @@ func TestYaml(t *testing.T) { func TestNegativeAvailableToElement(t *testing.T) { messageID := 0 - resourceUriBase := "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.CIMResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "cim/service/availabletoelement", } @@ -56,14 +55,15 @@ func TestNegativeAvailableToElement(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //ENUMERATES + // ENUMERATES { "should handle error making cim_ServiceAvailableToElement Enumerate call", - CIM_ServiceAvailableToElement, - wsmantesting.ENUMERATE, - wsmantesting.ENUMERATE_BODY, + CIMServiceAvailableToElement, + wsmantesting.Enumerate, + wsmantesting.EnumerateBody, func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Enumerate() }, Body{ @@ -73,14 +73,15 @@ func TestNegativeAvailableToElement(t *testing.T) { }, }, }, - //PULLS + // PULLS { "should handle error making cim_ServiceAvailableToElement Pull call", - CIM_ServiceAvailableToElement, - wsmantesting.PULL, - wsmantesting.PULL_BODY, + CIMServiceAvailableToElement, + wsmantesting.Pull, + wsmantesting.PullBody, func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -114,7 +115,7 @@ func TestNegativeAvailableToElement(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, "", test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, "", test.body) messageID++ response, err := test.responseFunc() assert.Error(t, err) diff --git a/pkg/wsman/cim/service/decoder.go b/pkg/wsman/cim/service/decoder.go index 189ef07b..fc8ec9d7 100644 --- a/pkg/wsman/cim/service/decoder.go +++ b/pkg/wsman/cim/service/decoder.go @@ -5,7 +5,10 @@ package service -const CIM_ServiceAvailableToElement string = "CIM_ServiceAvailableToElement" +const ( + CIMServiceAvailableToElement string = "CIM_ServiceAvailableToElement" + ValueNotFound string = "Value not found in map" +) const ( AvailableRequestedPowerStatesOther AvailableRequestedPowerStates = iota + 1 @@ -26,7 +29,7 @@ const ( AvailableRequestedPowerStatesPowerCycleHardGraceful ) -// availableRequestedPowerStatesMap is a map of the AvailableRequestedPowerStates enumeration +// availableRequestedPowerStatesMap is a map of the AvailableRequestedPowerStates enumeration. var availableRequestedPowerStatesMap = map[AvailableRequestedPowerStates]string{ AvailableRequestedPowerStatesOther: "Other", AvailableRequestedPowerStatesOn: "On", @@ -46,12 +49,13 @@ var availableRequestedPowerStatesMap = map[AvailableRequestedPowerStates]string{ AvailableRequestedPowerStatesPowerCycleHardGraceful: "PowerCycleHardGraceful", } -// String returns a human-readable string representation of the AvailableRequestedPowerStates enumeration +// String returns a human-readable string representation of the AvailableRequestedPowerStates enumeration. func (e AvailableRequestedPowerStates) String() string { if s, ok := availableRequestedPowerStatesMap[e]; ok { return s } - return "Value not found in map" + + return ValueNotFound } const ( @@ -74,7 +78,7 @@ const ( PowerStateDiagnosticInterruptINIT ) -// powerStateMap is a map of the PowerState enumeration +// powerStateMap is a map of the PowerState enumeration. var powerStateMap = map[PowerState]string{ PowerStateOther: "Other", PowerStateOn: "On", @@ -95,10 +99,11 @@ var powerStateMap = map[PowerState]string{ PowerStateDiagnosticInterruptINIT: "DiagnosticInterruptINIT", } -// String returns a human-readable string representation of the PowerState enumeration +// String returns a human-readable string representation of the PowerState enumeration. func (e PowerState) String() string { if s, ok := powerStateMap[e]; ok { return s } - return "Value not found in map" + + return ValueNotFound } diff --git a/pkg/wsman/cim/service/marshal.go b/pkg/wsman/cim/service/marshal.go index 52d049e0..a9d9f760 100644 --- a/pkg/wsman/cim/service/marshal.go +++ b/pkg/wsman/cim/service/marshal.go @@ -11,20 +11,22 @@ import ( "gopkg.in/yaml.v3" ) -// JSON marshals the type into JSON format +// JSON marshals the type into JSON format. func (r *Response) JSON() string { jsonOutput, err := json.Marshal(r.Body) if err != nil { return "" } + return string(jsonOutput) } -// YAML marshals the type into YAML format +// YAML marshals the type into YAML format. func (r *Response) YAML() string { yamlOutput, err := yaml.Marshal(r.Body) if err != nil { return "" } + return string(yamlOutput) } diff --git a/pkg/wsman/cim/service/types.go b/pkg/wsman/cim/service/types.go index 90ca198c..bb67ba6c 100644 --- a/pkg/wsman/cim/service/types.go +++ b/pkg/wsman/cim/service/types.go @@ -14,11 +14,10 @@ import ( ) type AvailableToElement struct { - base message.Base - client client.WSMan + base message.Base } -// Response Types +// Response Types. type ( Response struct { *client.Message diff --git a/pkg/wsman/cim/software/constants.go b/pkg/wsman/cim/software/constants.go index 0a492d9a..0ac0bf67 100644 --- a/pkg/wsman/cim/software/constants.go +++ b/pkg/wsman/cim/software/constants.go @@ -5,4 +5,4 @@ package software -const CIM_SoftwareIdentity = "CIM_SoftwareIdentity" +const CIMSoftwareIdentity = "CIM_SoftwareIdentity" diff --git a/pkg/wsman/cim/software/identity.go b/pkg/wsman/cim/software/identity.go index d833eda0..5e185150 100644 --- a/pkg/wsman/cim/software/identity.go +++ b/pkg/wsman/cim/software/identity.go @@ -20,12 +20,11 @@ import ( // NewSoftwareIdentity returns a new instance of the SoftwareIdentity struct. func NewSoftwareIdentityWithClient(wsmanMessageCreator *message.WSManMessageCreator, client client.WSMan) Identity { return Identity{ - base: message.NewBaseWithClient(wsmanMessageCreator, CIM_SoftwareIdentity, client), - client: client, + base: message.NewBaseWithClient(wsmanMessageCreator, CIMSoftwareIdentity, client), } } -// Get retrieves the representation of the instance +// Get retrieves the representation of the instance. func (identity Identity) Get(instanceID string) (response Response, err error) { selector := message.Selector{ Name: "InstanceID", @@ -33,24 +32,24 @@ func (identity Identity) Get(instanceID string) (response Response, err error) { } response = Response{ Message: &client.Message{ - XMLInput: identity.base.Get((*message.Selector)(&selector)), + XMLInput: identity.base.Get(&selector), }, } err = identity.base.Execute(response.Message) if err != nil { - return + return response, err } err = xml.Unmarshal([]byte(response.XMLOutput), &response) if err != nil { - return + return response, err } - return + return response, nil } -// Enumerate returns an enumeration context which is used in a subsequent Pull call +// Enumerate returns an enumeration context which is used in a subsequent Pull call. func (identity Identity) Enumerate() (response Response, err error) { response = Response{ Message: &client.Message{ @@ -60,15 +59,15 @@ func (identity Identity) Enumerate() (response Response, err error) { err = identity.base.Execute(response.Message) if err != nil { - return + return response, err } err = xml.Unmarshal([]byte(response.XMLOutput), &response) if err != nil { - return + return response, err } - return + return response, nil } // Pull returns the instances of this class. An enumeration context provided by the Enumerate call is used as input. @@ -78,13 +77,16 @@ func (identity Identity) Pull(enumerationContext string) (response Response, err XMLInput: identity.base.Pull(enumerationContext), }, } + err = identity.base.Execute(response.Message) if err != nil { - return + return response, err } + err = xml.Unmarshal([]byte(response.XMLOutput), &response) if err != nil { - return + return response, err } - return + + return response, nil } diff --git a/pkg/wsman/cim/software/identity_test.go b/pkg/wsman/cim/software/identity_test.go index 28503276..5881298c 100644 --- a/pkg/wsman/cim/software/identity_test.go +++ b/pkg/wsman/cim/software/identity_test.go @@ -9,11 +9,10 @@ import ( "encoding/xml" "testing" - "github.com/stretchr/testify/assert" - "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/internal/message" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/common" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/wsmantesting" + "github.com/stretchr/testify/assert" ) func TestJson(t *testing.T) { @@ -40,8 +39,8 @@ func TestYaml(t *testing.T) { func TestPositiveCIMSoftwareIdentity(t *testing.T) { messageID := 0 - resourceUriBase := "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.CIMResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "cim/software/identity", } @@ -57,15 +56,16 @@ func TestPositiveCIMSoftwareIdentity(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //GETS + // GETS { "should create and parse a valid cim_SoftwareIdentity Get call", - CIM_SoftwareIdentity, - wsmantesting.GET, + CIMSoftwareIdentity, + wsmantesting.Get, "AMTApps", "", func() (Response, error) { - client.CurrentMessage = "Get" + client.CurrentMessage = wsmantesting.CurrentMessageGet + return elementUnderTest.Get("AMTApps") }, Body{ @@ -78,15 +78,16 @@ func TestPositiveCIMSoftwareIdentity(t *testing.T) { }, }, }, - //ENUMERATES + // ENUMERATES { "should create and parse a valid cim_SoftwareIdentity Enumerate call", - CIM_SoftwareIdentity, - wsmantesting.ENUMERATE, + CIMSoftwareIdentity, + wsmantesting.Enumerate, "", - wsmantesting.ENUMERATE_BODY, + wsmantesting.EnumerateBody, func() (Response, error) { - client.CurrentMessage = "Enumerate" + client.CurrentMessage = wsmantesting.CurrentMessageEnumerate + return elementUnderTest.Enumerate() }, Body{ @@ -96,15 +97,16 @@ func TestPositiveCIMSoftwareIdentity(t *testing.T) { }, }, }, - //PULLS + // PULLS { "should create and parse a valid cim_SoftwareIdentity Pull call", - CIM_SoftwareIdentity, - wsmantesting.PULL, + CIMSoftwareIdentity, + wsmantesting.Pull, "", - wsmantesting.PULL_BODY, + wsmantesting.PullBody, func() (Response, error) { - client.CurrentMessage = "Pull" + client.CurrentMessage = wsmantesting.CurrentMessagePull + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -186,7 +188,7 @@ func TestPositiveCIMSoftwareIdentity(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, test.extraHeaders, test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, test.extraHeaders, test.body) messageID++ response, err := test.responseFunc() assert.NoError(t, err) @@ -196,10 +198,11 @@ func TestPositiveCIMSoftwareIdentity(t *testing.T) { } }) } + func TestNegativeCIMSoftwareIdentity(t *testing.T) { messageID := 0 - resourceUriBase := "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.CIMResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "cim/software/identity", } @@ -215,15 +218,16 @@ func TestNegativeCIMSoftwareIdentity(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //GETS + // GETS { "should create and parse a valid cim_SoftwareIdentity Get call", - CIM_SoftwareIdentity, - wsmantesting.GET, + CIMSoftwareIdentity, + wsmantesting.Get, "AMTApps", "", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Get("AMTApps") }, Body{ @@ -236,15 +240,16 @@ func TestNegativeCIMSoftwareIdentity(t *testing.T) { }, }, }, - //ENUMERATES + // ENUMERATES { "should create and parse a valid cim_SoftwareIdentity Enumerate call", - CIM_SoftwareIdentity, - wsmantesting.ENUMERATE, + CIMSoftwareIdentity, + wsmantesting.Enumerate, "", - wsmantesting.ENUMERATE_BODY, + wsmantesting.EnumerateBody, func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Enumerate() }, Body{ @@ -254,15 +259,16 @@ func TestNegativeCIMSoftwareIdentity(t *testing.T) { }, }, }, - //PULLS + // PULLS { "should create and parse a valid cim_SoftwareIdentity Pull call", - CIM_SoftwareIdentity, - wsmantesting.PULL, + CIMSoftwareIdentity, + wsmantesting.Pull, "", - wsmantesting.PULL_BODY, + wsmantesting.PullBody, func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -344,7 +350,7 @@ func TestNegativeCIMSoftwareIdentity(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, test.extraHeaders, test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, test.extraHeaders, test.body) messageID++ response, err := test.responseFunc() assert.Error(t, err) diff --git a/pkg/wsman/cim/software/marshal.go b/pkg/wsman/cim/software/marshal.go index 8769dbc1..8a707a4b 100644 --- a/pkg/wsman/cim/software/marshal.go +++ b/pkg/wsman/cim/software/marshal.go @@ -11,20 +11,22 @@ import ( "gopkg.in/yaml.v3" ) -// JSON marshals the type into JSON format +// JSON marshals the type into JSON format. func (r *Response) JSON() string { jsonOutput, err := json.Marshal(r.Body) if err != nil { return "" } + return string(jsonOutput) } -// YAML marshals the type into YAML format +// YAML marshals the type into YAML format. func (r *Response) YAML() string { yamlOutput, err := yaml.Marshal(r.Body) if err != nil { return "" } + return string(yamlOutput) } diff --git a/pkg/wsman/cim/software/types.go b/pkg/wsman/cim/software/types.go index 0c8a95fe..64da338b 100644 --- a/pkg/wsman/cim/software/types.go +++ b/pkg/wsman/cim/software/types.go @@ -14,11 +14,10 @@ import ( ) type Identity struct { - base message.Base - client client.WSMan + base message.Base } -// Response Types +// Response Types. type ( Response struct { *client.Message diff --git a/pkg/wsman/cim/system/constants.go b/pkg/wsman/cim/system/constants.go index 87ca6d73..9c5c5403 100644 --- a/pkg/wsman/cim/system/constants.go +++ b/pkg/wsman/cim/system/constants.go @@ -5,4 +5,4 @@ package system -const CIM_SystemPackaging string = "CIM_SystemPackaging" +const CIMSystemPackaging string = "CIM_SystemPackaging" diff --git a/pkg/wsman/cim/system/marshal.go b/pkg/wsman/cim/system/marshal.go index 0e35b31b..706067a3 100644 --- a/pkg/wsman/cim/system/marshal.go +++ b/pkg/wsman/cim/system/marshal.go @@ -11,20 +11,22 @@ import ( "gopkg.in/yaml.v3" ) -// JSON marshals the type into JSON format +// JSON marshals the type into JSON format. func (r *Response) JSON() string { jsonOutput, err := json.Marshal(r.Body) if err != nil { return "" } + return string(jsonOutput) } -// YAML marshals the type into YAML format +// YAML marshals the type into YAML format. func (r *Response) YAML() string { yamlOutput, err := yaml.Marshal(r.Body) if err != nil { return "" } + return string(yamlOutput) } diff --git a/pkg/wsman/cim/system/packaging.go b/pkg/wsman/cim/system/packaging.go index 5e9bc7dd..66a9f6df 100644 --- a/pkg/wsman/cim/system/packaging.go +++ b/pkg/wsman/cim/system/packaging.go @@ -18,14 +18,14 @@ import ( // NewSystemPackaging returns a new instance of the SystemPackaging struct. func NewSystemPackageWithClient(wsmanMessageCreator *message.WSManMessageCreator, client client.WSMan) Package { return Package{ - base: message.NewBaseWithClient(wsmanMessageCreator, CIM_SystemPackaging, client), + base: message.NewBaseWithClient(wsmanMessageCreator, CIMSystemPackaging, client), } } // TODO: Figure out how to call GET requiring resourceURIs and Selectors // Get retrieves the representation of the instance. No Route -// Enumerate returns an enumeration context which is used in a subsequent Pull call +// Enumerate returns an enumeration context which is used in a subsequent Pull call. func (packaging Package) Enumerate() (response Response, err error) { response = Response{ Message: &client.Message{ @@ -35,15 +35,15 @@ func (packaging Package) Enumerate() (response Response, err error) { err = packaging.base.Execute(response.Message) if err != nil { - return + return response, err } err = xml.Unmarshal([]byte(response.XMLOutput), &response) if err != nil { - return + return response, err } - return + return response, nil } // Pull returns the instances of this class. An enumeration context provided by the Enumerate call is used as input. @@ -53,13 +53,16 @@ func (packaging Package) Pull(enumerationContext string) (response Response, err XMLInput: packaging.base.Pull(enumerationContext), }, } + err = packaging.base.Execute(response.Message) if err != nil { - return + return response, err } + err = xml.Unmarshal([]byte(response.XMLOutput), &response) if err != nil { - return + return response, err } - return + + return response, nil } diff --git a/pkg/wsman/cim/system/packaging_test.go b/pkg/wsman/cim/system/packaging_test.go index f0d043ee..84bf0016 100644 --- a/pkg/wsman/cim/system/packaging_test.go +++ b/pkg/wsman/cim/system/packaging_test.go @@ -9,11 +9,10 @@ import ( "encoding/xml" "testing" - "github.com/stretchr/testify/assert" - "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/internal/message" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/common" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/wsmantesting" + "github.com/stretchr/testify/assert" ) func TestJson(t *testing.T) { @@ -40,8 +39,8 @@ func TestYaml(t *testing.T) { func TestPositiveCIMComputerSystemPackage(t *testing.T) { messageID := 0 - resourceUriBase := "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.CIMResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "cim/system/packaging", } @@ -56,14 +55,15 @@ func TestPositiveCIMComputerSystemPackage(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //ENUMERATES + // ENUMERATES { "should create and parse a valid cim_SystemPackaging Enumerate call", - CIM_SystemPackaging, - wsmantesting.ENUMERATE, - wsmantesting.ENUMERATE_BODY, + CIMSystemPackaging, + wsmantesting.Enumerate, + wsmantesting.EnumerateBody, func() (Response, error) { - client.CurrentMessage = "Enumerate" + client.CurrentMessage = wsmantesting.CurrentMessageEnumerate + return elementUnderTest.Enumerate() }, Body{ @@ -73,14 +73,15 @@ func TestPositiveCIMComputerSystemPackage(t *testing.T) { }, }, }, - //PULLS + // PULLS { "should create and parse a valid cim_SystemPackaging Pull call", - CIM_SystemPackaging, - wsmantesting.PULL, - wsmantesting.PULL_BODY, + CIMSystemPackaging, + wsmantesting.Pull, + wsmantesting.PullBody, func() (Response, error) { - client.CurrentMessage = "Pull" + client.CurrentMessage = wsmantesting.CurrentMessagePull + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -145,7 +146,7 @@ func TestPositiveCIMComputerSystemPackage(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, "", test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, "", test.body) messageID++ response, err := test.responseFunc() assert.NoError(t, err) @@ -155,10 +156,11 @@ func TestPositiveCIMComputerSystemPackage(t *testing.T) { } }) } + func TestNegativeCIMComputerSystemPackage(t *testing.T) { messageID := 0 - resourceUriBase := "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.CIMResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "cim/system/packaging", } @@ -173,14 +175,15 @@ func TestNegativeCIMComputerSystemPackage(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //ENUMERATES + // ENUMERATES { "should create and parse a valid cim_SystemPackaging Enumerate call", - CIM_SystemPackaging, - wsmantesting.ENUMERATE, - wsmantesting.ENUMERATE_BODY, + CIMSystemPackaging, + wsmantesting.Enumerate, + wsmantesting.EnumerateBody, func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Enumerate() }, Body{ @@ -190,14 +193,15 @@ func TestNegativeCIMComputerSystemPackage(t *testing.T) { }, }, }, - //PULLS + // PULLS { "should create and parse a valid cim_SystemPackaging Pull call", - CIM_SystemPackaging, - wsmantesting.PULL, - wsmantesting.PULL_BODY, + CIMSystemPackaging, + wsmantesting.Pull, + wsmantesting.PullBody, func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -260,7 +264,7 @@ func TestNegativeCIMComputerSystemPackage(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, "", test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, "", test.body) messageID++ response, err := test.responseFunc() assert.Error(t, err) diff --git a/pkg/wsman/cim/system/types.go b/pkg/wsman/cim/system/types.go index b6f5785e..599168e3 100644 --- a/pkg/wsman/cim/system/types.go +++ b/pkg/wsman/cim/system/types.go @@ -17,7 +17,7 @@ type Package struct { base message.Base } -// Response Types +// Response Types. type ( Response struct { *client.Message diff --git a/pkg/wsman/cim/wifi/decoder.go b/pkg/wsman/cim/wifi/decoder.go index 65b473da..ef560d72 100644 --- a/pkg/wsman/cim/wifi/decoder.go +++ b/pkg/wsman/cim/wifi/decoder.go @@ -6,9 +6,10 @@ package wifi const ( - CIM_WiFiEndpoint string = "CIM_WiFiEndpoint" - CIM_WiFiEndpointSettings string = "CIM_WiFiEndpointSettings" - CIM_WiFiPort string = "CIM_WiFiPort" + CIMWiFiEndpoint string = "CIM_WiFiEndpoint" + CIMWiFiEndpointSettings string = "CIM_WiFiEndpointSettings" + CIMWiFiPort string = "CIM_WiFiPort" + ValueNotFound string = "Value not found in map" ) const ( @@ -23,7 +24,7 @@ const ( AuthenticationMethodWPA3OWE AuthenticationMethod = 32769 ) -// authenticationMethodMap is a map of the AuthenticationMethod enumeration +// authenticationMethodMap is a map of the AuthenticationMethod enumeration. var authenticationMethodMap = map[AuthenticationMethod]string{ AuthenticationMethodOther: "Other", AuthenticationMethodOpenSystem: "OpenSystem", @@ -36,33 +37,35 @@ var authenticationMethodMap = map[AuthenticationMethod]string{ AuthenticationMethodWPA3OWE: "WPA3OWE", } -// String returns a human-readable string representation of the AuthenticationMethod enumeration +// String returns a human-readable string representation of the AuthenticationMethod enumeration. func (e AuthenticationMethod) String() string { if s, ok := authenticationMethodMap[e]; ok { return s } - return "Value not found in map" + + return ValueNotFound } const ( - BSSType_Unknown BSSType = 0 - BSSType_Independent BSSType = 2 - BSSType_Infrastructure BSSType = 3 + BSSTypeUnknown BSSType = 0 + BSSTypeIndependent BSSType = 2 + BSSTypeInfrastructure BSSType = 3 ) -// bssTypeMap is a map of the BSSType enumeration +// bssTypeMap is a map of the BSSType enumeration. var bssTypeMap = map[BSSType]string{ - BSSType_Unknown: "Unknown", - BSSType_Independent: "Independent", - BSSType_Infrastructure: "Infrastructure", + BSSTypeUnknown: "Unknown", + BSSTypeIndependent: "Independent", + BSSTypeInfrastructure: "Infrastructure", } -// String returns a human-readable string representation of the BSSType enumeration +// String returns a human-readable string representation of the BSSType enumeration. func (e BSSType) String() string { if s, ok := bssTypeMap[e]; ok { return s } - return "Value not found in map" + + return ValueNotFound } const ( @@ -71,19 +74,20 @@ const ( EnabledStateWifiEnabledS0SxAC EnabledState = 32769 ) -// enabledStateMap is a map of the EnabledState enumeration +// enabledStateMap is a map of the EnabledState enumeration. var enabledStateMap = map[EnabledState]string{ EnabledStateWifiDisabled: "WifiDisabled", EnabledStateWifiEnabledS0: "WifiEnabledS0", EnabledStateWifiEnabledS0SxAC: "WifiEnabledS0SxAC", } -// String returns a human-readable string representation of the EnabledState enumeration +// String returns a human-readable string representation of the EnabledState enumeration. func (e EnabledState) String() string { if s, ok := enabledStateMap[e]; ok { return s } - return "Value not found in map" + + return ValueNotFound } const ( @@ -94,7 +98,7 @@ const ( EncryptionMethod_None ) -// encryptionMethodMap is a map of the EncryptionMethod enumeration +// encryptionMethodMap is a map of the EncryptionMethod enumeration. var encryptionMethodMap = map[EncryptionMethod]string{ EncryptionMethod_Other: "Other", EncryptionMethod_WEP: "WEP", @@ -103,12 +107,13 @@ var encryptionMethodMap = map[EncryptionMethod]string{ EncryptionMethod_None: "None", } -// String returns a human-readable string representation of the EncryptionMethod enumeration +// String returns a human-readable string representation of the EncryptionMethod enumeration. func (e EncryptionMethod) String() string { if s, ok := encryptionMethodMap[e]; ok { return s } - return "Value not found in map" + + return ValueNotFound } const ( @@ -121,7 +126,7 @@ const ( HealthStateNonRecoverableError HealthState = 30 ) -// healthStateMap is a map of the HealthState enumeration +// healthStateMap is a map of the HealthState enumeration. var healthStateMap = map[HealthState]string{ HealthStateOK: "OK", HealthStateDegraded: "Degraded", @@ -131,12 +136,13 @@ var healthStateMap = map[HealthState]string{ HealthStateNonRecoverableError: "NonRecoverableError", } -// String returns a human-readable string representation of the HealthState enumeration +// String returns a human-readable string representation of the HealthState enumeration. func (e HealthState) String() string { if s, ok := healthStateMap[e]; ok { return s } - return "Value not found in map" + + return ValueNotFound } const ( @@ -154,7 +160,7 @@ const ( LinkTechnologyWirelessLAN ) -// linkTechnologyMap is a map of the LinkTechnology enumeration +// linkTechnologyMap is a map of the LinkTechnology enumeration. var linkTechnologyMap = map[LinkTechnology]string{ LinkTechnologyUnknown: "Unknown", LinkTechnologyOther: "Other", @@ -170,12 +176,13 @@ var linkTechnologyMap = map[LinkTechnology]string{ LinkTechnologyWirelessLAN: "WirelessLAN", } -// String returns a human-readable string representation of the LinkTechnology enumeration +// String returns a human-readable string representation of the LinkTechnology enumeration. func (e LinkTechnology) String() string { if s, ok := linkTechnologyMap[e]; ok { return s } - return "Value not found in map" + + return ValueNotFound } const ( @@ -184,19 +191,20 @@ const ( RequestedStateWifiEnabledS0SxAC RequestedState = 32769 ) -// requestedStateMap is a map of the RequestedState enumeration +// requestedStateMap is a map of the RequestedState enumeration. var requestedStateMap = map[RequestedState]string{ RequestedStateWifiDisabled: "WifiDisabled", RequestedStateWifiEnabledS0: "WifiEnabledS0", RequestedStateWifiEnabledS0SxAC: "WifiEnabledS0SxAC", } -// String returns a human-readable string representation of the RequestedState enumeration +// String returns a human-readable string representation of the RequestedState enumeration. func (e RequestedState) String() string { if s, ok := requestedStateMap[e]; ok { return s } - return "Value not found in map" + + return ValueNotFound } const ( @@ -213,7 +221,7 @@ const ( Busy ReturnValue = 4099 ) -// returnValueMap is a map of the ReturnValue enumeration +// returnValueMap is a map of the ReturnValue enumeration. var returnValueMap = map[ReturnValue]string{ CompletedWithNoError: "CompletedWithNoError", NotSupported: "NotSupported", @@ -228,12 +236,13 @@ var returnValueMap = map[ReturnValue]string{ Busy: "Busy", } -// String returns a human-readable string representation of the ReturnValue enumeration +// String returns a human-readable string representation of the ReturnValue enumeration. func (e ReturnValue) String() string { if s, ok := returnValueMap[e]; ok { return s } - return "Value not found in map" + + return ValueNotFound } const ( @@ -245,7 +254,7 @@ const ( PortType80211n PortType = 73 ) -// portTypeMap is a map of the PortType enumeration +// portTypeMap is a map of the PortType enumeration. var portTypeMap = map[PortType]string{ PortTypeUnknown: "Unknown", PortTypeOther: "Other", @@ -255,10 +264,11 @@ var portTypeMap = map[PortType]string{ PortType80211n: "802.11n", } -// String returns a human-readable string representation of the PortType enumeration +// String returns a human-readable string representation of the PortType enumeration. func (e PortType) String() string { if s, ok := portTypeMap[e]; ok { return s } - return "Value not found in map" + + return ValueNotFound } diff --git a/pkg/wsman/cim/wifi/decoder_test.go b/pkg/wsman/cim/wifi/decoder_test.go index 89349e66..0811b7b0 100644 --- a/pkg/wsman/cim/wifi/decoder_test.go +++ b/pkg/wsman/cim/wifi/decoder_test.go @@ -37,9 +37,9 @@ func TestBSSType_String(t *testing.T) { state BSSType expected string }{ - {BSSType_Unknown, "Unknown"}, - {BSSType_Independent, "Independent"}, - {BSSType_Infrastructure, "Infrastructure"}, + {BSSTypeUnknown, "Unknown"}, + {BSSTypeIndependent, "Independent"}, + {BSSTypeInfrastructure, "Infrastructure"}, {BSSType(999), "Value not found in map"}, } diff --git a/pkg/wsman/cim/wifi/endpointsettings.go b/pkg/wsman/cim/wifi/endpointsettings.go index 4fcd8d27..e5d0d0d2 100644 --- a/pkg/wsman/cim/wifi/endpointsettings.go +++ b/pkg/wsman/cim/wifi/endpointsettings.go @@ -23,14 +23,14 @@ import ( // NewWiFiEndpointSettings returns a new instance of the WiFiEndpointSettings struct. func NewWiFiEndpointSettingsWithClient(wsmanMessageCreator *message.WSManMessageCreator, client client.WSMan) EndpointSettings { return EndpointSettings{ - base: message.NewBaseWithClient(wsmanMessageCreator, CIM_WiFiEndpointSettings, client), + base: message.NewBaseWithClient(wsmanMessageCreator, CIMWiFiEndpointSettings, client), } } // TODO: Figure out how to call GET requiring resourceURIs and Selectors // Get retrieves the representation of the instance -// Enumerate returns an enumeration context which is used in a subsequent Pull call +// Enumerate returns an enumeration context which is used in a subsequent Pull call. func (endpointSettings EndpointSettings) Enumerate() (response Response, err error) { response = Response{ Message: &client.Message{ @@ -47,8 +47,8 @@ func (endpointSettings EndpointSettings) Enumerate() (response Response, err err if err != nil { return } - return + return } // Pull returns the instances of this class. An enumeration context provided by the Enumerate call is used as input. @@ -58,18 +58,21 @@ func (endpointSettings EndpointSettings) Pull(enumerationContext string) (respon XMLInput: endpointSettings.base.Pull(enumerationContext), }, } + err = endpointSettings.base.Execute(response.Message) if err != nil { return } + err = xml.Unmarshal([]byte(response.XMLOutput), &response) if err != nil { return } + return } -// Delete removes a the specified instance +// Delete removes a the specified instance. func (endpointSettings EndpointSettings) Delete(handle string) (response Response, err error) { selector := message.Selector{Name: "InstanceID", Value: handle} response = Response{ @@ -87,5 +90,6 @@ func (endpointSettings EndpointSettings) Delete(handle string) (response Respons if err != nil { return } + return } diff --git a/pkg/wsman/cim/wifi/endpointsettings_test.go b/pkg/wsman/cim/wifi/endpointsettings_test.go index aab18266..e47163df 100644 --- a/pkg/wsman/cim/wifi/endpointsettings_test.go +++ b/pkg/wsman/cim/wifi/endpointsettings_test.go @@ -9,11 +9,10 @@ import ( "encoding/xml" "testing" - "github.com/stretchr/testify/assert" - "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/internal/message" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/common" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/wsmantesting" + "github.com/stretchr/testify/assert" ) func TestJson(t *testing.T) { @@ -22,7 +21,7 @@ func TestJson(t *testing.T) { PullResponse: PullResponse{}, }, } - expectedResult := "{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"WiFiPortGetResponse\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"LinkTechnology\":0,\"DeviceID\":\"\",\"CreationClassName\":\"\",\"SystemName\":\"\",\"SystemCreationClassName\":\"\",\"ElementName\":\"\",\"HealthState\":0,\"EnabledState\":0,\"RequestedState\":0,\"PortType\":0,\"PermanentAddress\":\"\"},\"EnumerateResponse\":{\"EnumerationContext\":\"\"},\"PullResponse\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"EndpointSettingsItems\":null,\"WiFiPortItems\":null},\"RequestStateChange_OUTPUT\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"ReturnValue\":0,\"ReturnValueStr\":\"\"}}" + expectedResult := "{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"WiFiPortGetResponse\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"LinkTechnology\":0,\"DeviceID\":\"\",\"CreationClassName\":\"\",\"SystemName\":\"\",\"SystemCreationClassName\":\"\",\"ElementName\":\"\",\"HealthState\":0,\"EnabledState\":0,\"RequestedState\":0,\"PortType\":0,\"PermanentAddress\":\"\"},\"EnumerateResponse\":{\"EnumerationContext\":\"\"},\"PullResponse\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"EndpointSettingsItems\":null,\"WiFiPortItems\":null},\"RequestStateChangeOutput\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"ReturnValue\":0,\"ReturnValueStr\":\"\"}}" result := response.JSON() assert.Equal(t, expectedResult, result) } @@ -33,15 +32,15 @@ func TestYaml(t *testing.T) { PullResponse: PullResponse{}, }, } - expectedResult := "xmlname:\n space: \"\"\n local: \"\"\nwifiportgetresponse:\n xmlname:\n space: \"\"\n local: \"\"\n linktechnology: 0\n deviceid: \"\"\n creationclassname: \"\"\n systemname: \"\"\n systemcreationclassname: \"\"\n elementname: \"\"\n healthstate: 0\n enabledstate: 0\n requestedstate: 0\n porttype: 0\n permanentaddress: \"\"\nenumerateresponse:\n enumerationcontext: \"\"\npullresponse:\n xmlname:\n space: \"\"\n local: \"\"\n endpointsettingsitems: []\n wifiportitems: []\nrequeststatechange_output:\n xmlname:\n space: \"\"\n local: \"\"\n returnvalue: 0\n returnvaluestr: \"\"\n" + expectedResult := "xmlname:\n space: \"\"\n local: \"\"\nwifiportgetresponse:\n xmlname:\n space: \"\"\n local: \"\"\n linktechnology: 0\n deviceid: \"\"\n creationclassname: \"\"\n systemname: \"\"\n systemcreationclassname: \"\"\n elementname: \"\"\n healthstate: 0\n enabledstate: 0\n requestedstate: 0\n porttype: 0\n permanentaddress: \"\"\nenumerateresponse:\n enumerationcontext: \"\"\npullresponse:\n xmlname:\n space: \"\"\n local: \"\"\n endpointsettingsitems: []\n wifiportitems: []\nrequeststatechangeoutput:\n xmlname:\n space: \"\"\n local: \"\"\n returnvalue: 0\n returnvaluestr: \"\"\n" result := response.YAML() assert.Equal(t, expectedResult, result) } func TestPositiveCIMWifiEndpointSettings(t *testing.T) { messageID := 0 - resourceUriBase := "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.CIMResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "cim/wifi/endpointsettings", } @@ -57,32 +56,35 @@ func TestPositiveCIMWifiEndpointSettings(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //ENUMERATES + // ENUMERATES { "should create and parse a valid cim_WiFiEndpointSettings Enumerate call", - CIM_WiFiEndpointSettings, - wsmantesting.ENUMERATE, + CIMWiFiEndpointSettings, + wsmantesting.Enumerate, "", - wsmantesting.ENUMERATE_BODY, + wsmantesting.EnumerateBody, func() (Response, error) { - client.CurrentMessage = "Enumerate" + client.CurrentMessage = wsmantesting.CurrentMessageEnumerate + return elementUnderTest.Enumerate() - }, Body{ + }, + Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, EnumerateResponse: common.EnumerateResponse{ EnumerationContext: "95040000-0000-0000-0000-000000000000", }, }, }, - //PULLS + // PULLS { "should create and parse a valid cim_WiFiEndpointSettings Pull call", - CIM_WiFiEndpointSettings, - wsmantesting.PULL, + CIMWiFiEndpointSettings, + wsmantesting.Pull, "", - wsmantesting.PULL_BODY, + wsmantesting.PullBody, func() (Response, error) { - client.CurrentMessage = "Pull" + client.CurrentMessage = wsmantesting.CurrentMessagePull + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -104,15 +106,16 @@ func TestPositiveCIMWifiEndpointSettings(t *testing.T) { }, }, }, - //DELETE + // DELETE { "should create and parse a valid cim_WiFiEndpointSettings Delete call", - CIM_WiFiEndpointSettings, - wsmantesting.DELETE, + CIMWiFiEndpointSettings, + wsmantesting.Delete, "instanceID123", "", func() (Response, error) { - client.CurrentMessage = "Delete" + client.CurrentMessage = wsmantesting.CurrentMessageDelete + return elementUnderTest.Delete("instanceID123") }, Body{ @@ -126,7 +129,7 @@ func TestPositiveCIMWifiEndpointSettings(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, test.extraHeader, test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, test.extraHeader, test.body) messageID++ response, err := test.responseFunc() assert.NoError(t, err) @@ -136,10 +139,11 @@ func TestPositiveCIMWifiEndpointSettings(t *testing.T) { } }) } + func TestNegativeCIMWifiEndpointSettings(t *testing.T) { messageID := 0 - resourceUriBase := "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.CIMResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "cim/wifi/endpointsettings", } @@ -155,32 +159,35 @@ func TestNegativeCIMWifiEndpointSettings(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //ENUMERATES + // ENUMERATES { "should handle error when cim_WiFiEndpointSettings Enumerate call", - CIM_WiFiEndpointSettings, - wsmantesting.ENUMERATE, + CIMWiFiEndpointSettings, + wsmantesting.Enumerate, "", - wsmantesting.ENUMERATE_BODY, + wsmantesting.EnumerateBody, func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Enumerate() - }, Body{ + }, + Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, EnumerateResponse: common.EnumerateResponse{ EnumerationContext: "95040000-0000-0000-0000-000000000000", }, }, }, - //PULLS + // PULLS { "should handle error when cim_WiFiEndpointSettings Pull call", - CIM_WiFiEndpointSettings, - wsmantesting.PULL, + CIMWiFiEndpointSettings, + wsmantesting.Pull, "", - wsmantesting.PULL_BODY, + wsmantesting.PullBody, func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -202,15 +209,16 @@ func TestNegativeCIMWifiEndpointSettings(t *testing.T) { }, }, }, - //DELETE + // DELETE { "should handle error when cim_WiFiEndpointSettings Delete call", - CIM_WiFiEndpointSettings, - wsmantesting.DELETE, + CIMWiFiEndpointSettings, + wsmantesting.Delete, "instanceID123", "", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Delete("instanceID123") }, Body{ @@ -224,7 +232,7 @@ func TestNegativeCIMWifiEndpointSettings(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, test.extraHeader, test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, test.extraHeader, test.body) messageID++ response, err := test.responseFunc() assert.Error(t, err) diff --git a/pkg/wsman/cim/wifi/marshal.go b/pkg/wsman/cim/wifi/marshal.go index 14ab4e18..a2f66f68 100644 --- a/pkg/wsman/cim/wifi/marshal.go +++ b/pkg/wsman/cim/wifi/marshal.go @@ -11,20 +11,22 @@ import ( "gopkg.in/yaml.v3" ) -// JSON marshals the type into JSON format +// JSON marshals the type into JSON format. func (r *Response) JSON() string { jsonOutput, err := json.Marshal(r.Body) if err != nil { return "" } + return string(jsonOutput) } -// YAML marshals the type into YAML format +// YAML marshals the type into YAML format. func (r *Response) YAML() string { yamlOutput, err := yaml.Marshal(r.Body) if err != nil { return "" } + return string(yamlOutput) } diff --git a/pkg/wsman/cim/wifi/port.go b/pkg/wsman/cim/wifi/port.go index 2eb1c199..78b57679 100644 --- a/pkg/wsman/cim/wifi/port.go +++ b/pkg/wsman/cim/wifi/port.go @@ -18,8 +18,7 @@ import ( // NewWiFiPort returns a new instance of the WiFiPort struct. func NewWiFiPortWithClient(wsmanMessageCreator *message.WSManMessageCreator, client client.WSMan) Port { return Port{ - base: message.NewBaseWithClient(wsmanMessageCreator, CIM_WiFiPort, client), - client: client, + base: message.NewBaseWithClient(wsmanMessageCreator, CIMWiFiPort, client), } } @@ -27,26 +26,28 @@ func NewWiFiPortWithClient(wsmanMessageCreator *message.WSManMessageCreator, cli func (port Port) RequestStateChange(requestedState int) (response Response, err error) { response = Response{ Message: &client.Message{ - XMLInput: port.base.RequestStateChange(methods.GenerateAction(CIM_WiFiPort, "RequestStateChange"), requestedState), + XMLInput: port.base.RequestStateChange(methods.GenerateAction(CIMWiFiPort, "RequestStateChange"), requestedState), }, } err = port.base.Execute(response.Message) if err != nil { - return + return response, err } err = xml.Unmarshal([]byte(response.XMLOutput), &response) if err != nil { - return + return response, err } + if response.Body.RequestStateChange_OUTPUT.ReturnValue != 0 { err = errors.New("RequestStateChange failed with return code " + strconv.Itoa(response.Body.RequestStateChange_OUTPUT.ReturnValue)) } - return + + return response, err } -// Get retrieves the representation of the instance +// Get retrieves the representation of the instance. func (port Port) Get() (response Response, err error) { response = Response{ Message: &client.Message{ @@ -56,18 +57,18 @@ func (port Port) Get() (response Response, err error) { err = port.base.Execute(response.Message) if err != nil { - return + return response, err } err = xml.Unmarshal([]byte(response.XMLOutput), &response) if err != nil { - return + return response, err } - return + return response, err } -// Enumerate returns an enumeration context which is used in a subsequent Pull call +// Enumerate returns an enumeration context which is used in a subsequent Pull call. func (port Port) Enumerate() (response Response, err error) { response = Response{ Message: &client.Message{ @@ -77,15 +78,15 @@ func (port Port) Enumerate() (response Response, err error) { err = port.base.Execute(response.Message) if err != nil { - return + return response, err } err = xml.Unmarshal([]byte(response.XMLOutput), &response) if err != nil { - return + return response, err } - return + return response, err } // Pull returns the instances of this class. An enumeration context provided by the Enumerate call is used as input. @@ -95,13 +96,16 @@ func (port Port) Pull(enumerationContext string) (response Response, err error) XMLInput: port.base.Pull(enumerationContext), }, } + err = port.base.Execute(response.Message) if err != nil { - return + return response, err } + err = xml.Unmarshal([]byte(response.XMLOutput), &response) if err != nil { - return + return response, err } - return + + return response, err } diff --git a/pkg/wsman/cim/wifi/port_test.go b/pkg/wsman/cim/wifi/port_test.go index 154209fe..ee3c0484 100644 --- a/pkg/wsman/cim/wifi/port_test.go +++ b/pkg/wsman/cim/wifi/port_test.go @@ -9,18 +9,17 @@ import ( "encoding/xml" "testing" - "github.com/stretchr/testify/assert" - "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/internal/message" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/cim/methods" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/common" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/wsmantesting" + "github.com/stretchr/testify/assert" ) func TestPositiveCIMWifiPort(t *testing.T) { messageID := 0 - resourceUriBase := "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.CIMResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "cim/wifi/port", } @@ -35,13 +34,14 @@ func TestPositiveCIMWifiPort(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //GETS + // GETS { "should create and parse a valid cim_WiFiPort Get call", - CIM_WiFiPort, - wsmantesting.GET, + CIMWiFiPort, + wsmantesting.Get, "", func() (Response, error) { - client.CurrentMessage = "Get" + client.CurrentMessage = wsmantesting.CurrentMessageGet + return elementUnderTest.Get() }, Body{ @@ -62,14 +62,15 @@ func TestPositiveCIMWifiPort(t *testing.T) { }, }, }, - //ENUMERATES + // ENUMERATES { "should create and parse a valid cim_WiFiPort Enumerate call", - CIM_WiFiPort, - wsmantesting.ENUMERATE, - wsmantesting.ENUMERATE_BODY, + CIMWiFiPort, + wsmantesting.Enumerate, + wsmantesting.EnumerateBody, func() (Response, error) { - client.CurrentMessage = "Enumerate" + client.CurrentMessage = wsmantesting.CurrentMessageEnumerate + return elementUnderTest.Enumerate() }, Body{ @@ -79,14 +80,15 @@ func TestPositiveCIMWifiPort(t *testing.T) { }, }, }, - //PULLS + // PULLS { "should create and parse a valid cim_WiFiPort Pull call", - CIM_WiFiPort, - wsmantesting.PULL, - wsmantesting.PULL_BODY, + CIMWiFiPort, + wsmantesting.Pull, + wsmantesting.PullBody, func() (Response, error) { - client.CurrentMessage = "Pull" + client.CurrentMessage = wsmantesting.CurrentMessagePull + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -114,11 +116,12 @@ func TestPositiveCIMWifiPort(t *testing.T) { }, { "should create and parse a valid cim_WiFiPort Request State Change call", - CIM_WiFiPort, - methods.RequestStateChange(CIM_WiFiPort), + CIMWiFiPort, + methods.RequestStateChange(CIMWiFiPort), "3", func() (Response, error) { client.CurrentMessage = "RequestStateChange" + return elementUnderTest.RequestStateChange(3) }, Body{ @@ -133,7 +136,7 @@ func TestPositiveCIMWifiPort(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, "", test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, "", test.body) messageID++ response, err := test.responseFunc() assert.NoError(t, err) @@ -143,10 +146,11 @@ func TestPositiveCIMWifiPort(t *testing.T) { } }) } + func TestNegativeCIMWifiPort(t *testing.T) { messageID := 0 - resourceUriBase := "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.CIMResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "cim/wifi/port", } @@ -161,13 +165,14 @@ func TestNegativeCIMWifiPort(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //GETS + // GETS { "should create and parse a valid cim_WiFiPort Get call", - CIM_WiFiPort, - wsmantesting.GET, + CIMWiFiPort, + wsmantesting.Get, "", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Get() }, Body{ @@ -188,14 +193,15 @@ func TestNegativeCIMWifiPort(t *testing.T) { }, }, }, - //ENUMERATES + // ENUMERATES { "should create and parse a valid cim_WiFiPort Enumerate call", - CIM_WiFiPort, - wsmantesting.ENUMERATE, - wsmantesting.ENUMERATE_BODY, + CIMWiFiPort, + wsmantesting.Enumerate, + wsmantesting.EnumerateBody, func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Enumerate() }, Body{ @@ -205,14 +211,15 @@ func TestNegativeCIMWifiPort(t *testing.T) { }, }, }, - //PULLS + // PULLS { "should create and parse a valid cim_WiFiPort Pull call", - CIM_WiFiPort, - wsmantesting.PULL, - wsmantesting.PULL_BODY, + CIMWiFiPort, + wsmantesting.Pull, + wsmantesting.PullBody, func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -240,11 +247,12 @@ func TestNegativeCIMWifiPort(t *testing.T) { }, { "should create and parse a valid cim_WiFiPort Request State Change call", - CIM_WiFiPort, - methods.RequestStateChange(CIM_WiFiPort), + CIMWiFiPort, + methods.RequestStateChange(CIMWiFiPort), "3", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.RequestStateChange(3) }, Body{ @@ -259,7 +267,7 @@ func TestNegativeCIMWifiPort(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, "", test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, "", test.body) messageID++ response, err := test.responseFunc() assert.Error(t, err) diff --git a/pkg/wsman/cim/wifi/types.go b/pkg/wsman/cim/wifi/types.go index 75e671e8..7185645b 100644 --- a/pkg/wsman/cim/wifi/types.go +++ b/pkg/wsman/cim/wifi/types.go @@ -14,8 +14,7 @@ import ( ) type Port struct { - base message.Base - client client.WSMan + base message.Base } type EndpointSettings struct { @@ -23,7 +22,7 @@ type EndpointSettings struct { } // OUTPUT -// Response Types +// Response Types. type ( Response struct { *client.Message @@ -74,7 +73,7 @@ type ( ) // INPUT -// Request Types +// Request Types. type ( WiFiEndpointSettings_INPUT struct { XMLName xml.Name `xml:"CIM_WiFiEndpointSettings"` diff --git a/pkg/wsman/client/hash.go b/pkg/wsman/client/hash.go index 14a8a038..b9f696b1 100644 --- a/pkg/wsman/client/hash.go +++ b/pkg/wsman/client/hash.go @@ -8,6 +8,7 @@ package client import ( "crypto/md5" "crypto/rand" + "errors" "fmt" "io" "log" @@ -31,10 +32,12 @@ type AuthChallenge struct { func hashWithMD5(data string) string { md5Hash := md5.New() + _, err := io.WriteString(md5Hash, data) if err != nil { log.Println("failed to write string to md5 hash") } + return fmt.Sprintf("%x", md5Hash.Sum(nil)) } @@ -49,14 +52,18 @@ func (c *AuthChallenge) HashCredentials() string { func (c *AuthChallenge) hashURI(method, uri string) string { return hashWithMD5(fmt.Sprintf("%s:%s", method, uri)) } + func (c *AuthChallenge) GetFormattedNonceData(nonceData string) string { nonceData = fmt.Sprintf("%s:%08x:%s:%s", nonceData, c.NonceCount, c.CNonce, c.Qop) + return nonceData } + func (c *AuthChallenge) ComputeDigestHash(method, uri, nonceData string) string { hashedCredentials := c.HashCredentials() hashedURI := c.hashURI(method, uri) response := hashWithHash(hashedCredentials, fmt.Sprintf("%s:%s", nonceData, hashedURI)) + return response } @@ -65,16 +72,21 @@ func (c *AuthChallenge) response(method, uri, cnonce string) (string, error) { if strings.Contains(c.Qop, "auth") || c.Qop == "" { nonceData := c.Nonce + if strings.Contains(c.Qop, "auth") { if cnonce != "" { c.CNonce = cnonce } else { b := make([]byte, 8) if _, err := io.ReadFull(rand.Reader, b); err != nil { - return "", fmt.Errorf("failed to generate random bytes: %v", err) + errRandRead := errors.New("failed to generate random bytes") + + return "", fmt.Errorf("%w: %w", errRandRead, err) } + c.CNonce = fmt.Sprintf("%x", b)[:16] } + c.Qop = "auth" nonceData = c.GetFormattedNonceData(nonceData) } @@ -82,20 +94,25 @@ func (c *AuthChallenge) response(method, uri, cnonce string) (string, error) { return c.ComputeDigestHash(method, uri, nonceData), nil } - return "", fmt.Errorf("not implemented") + errNotImplemented := errors.New("not implemented") + + return "", fmt.Errorf("%w", errNotImplemented) } func (c *AuthChallenge) authorize(method, uri string) (string, error) { - if !strings.Contains(c.Qop, "auth") && c.Qop != "" { - return "", fmt.Errorf("qop not implemented") + errQopNotImplemented := errors.New("qop not implemented") + + return "", fmt.Errorf("%w", errQopNotImplemented) } + response, err := c.response(method, uri, "") if err != nil { return "", err } var sb strings.Builder + sb.WriteString(`Digest username="`) sb.WriteString(c.Username) sb.WriteString(`", realm="`) @@ -113,11 +130,13 @@ func (c *AuthChallenge) authorize(method, uri string) (string, error) { sb.WriteString(c.Algorithm) sb.WriteString(`"`) } + if c.Opaque != "" { sb.WriteString(`, opaque="`) sb.WriteString(c.Opaque) sb.WriteString(`"`) } + if c.Qop != "" { sb.WriteString(`, qop="`) sb.WriteString(c.Qop) @@ -132,23 +151,33 @@ func (c *AuthChallenge) authorize(method, uri string) (string, error) { } func (c *AuthChallenge) parseChallenge(input string) error { + errBadChallenge := errors.New("bad challenge") + const ws = " \n\r\t" + const qs = "\"" + s := strings.Trim(input, ws) if !strings.HasPrefix(s, "Digest ") { - return fmt.Errorf("challenge is bad, missing digest prefix: %s", input) + return fmt.Errorf("%w, missing digest prefix: %s", errBadChallenge, input) } + s = strings.Trim(s[7:], ws) sl := strings.Split(s, "\",") c.Algorithm = "MD5" + var r []string + for _, elem := range sl { r = strings.SplitN(elem, "=", 2) if len(r) != 2 { - return fmt.Errorf("challenge is bad, malformed token: %s", elem) + return fmt.Errorf("%w, malformed token: %s", errBadChallenge, elem) } + key := strings.TrimSpace(r[0]) + value := strings.Trim(strings.TrimSpace(r[1]), qs) + switch key { case "realm": c.Realm = value @@ -165,8 +194,9 @@ func (c *AuthChallenge) parseChallenge(input string) error { case "qop": c.Qop = value default: - return fmt.Errorf("challenge is bad, unexpected token: %s", sl) + return fmt.Errorf("%w, unexpected token: %s", errBadChallenge, sl) } } + return nil } diff --git a/pkg/wsman/client/hash_test.go b/pkg/wsman/client/hash_test.go index 9c296922..fee0eed1 100644 --- a/pkg/wsman/client/hash_test.go +++ b/pkg/wsman/client/hash_test.go @@ -83,7 +83,8 @@ func TestResponse(t *testing.T) { } for _, tc := range testCases { - actual, _ := c.response(tc.method, tc.uri, tc.cnonce) + actual, err := c.response(tc.method, tc.uri, tc.cnonce) + assert.Nil(t, err) assert.Equal(t, tc.expected, actual) } } @@ -101,7 +102,8 @@ func TestResponse_Qop(t *testing.T) { for _, tc := range testCases { c.Qop = "auth,auth-int, auth" - actual, _ := c.response(tc.method, tc.uri, tc.cnonce) + actual, err := c.response(tc.method, tc.uri, tc.cnonce) + assert.Nil(t, err) assert.Equal(t, tc.expected, actual) } } @@ -117,7 +119,8 @@ func TestAuthorize(t *testing.T) { } for _, tc := range testCases { - actual, _ := c.authorize(tc.method, tc.uri) + actual, err := c.authorize(tc.method, tc.uri) + assert.Nil(t, err) assert.Equal(t, tc.expected, actual) } } @@ -136,7 +139,8 @@ func TestAuthorize_Full(t *testing.T) { c.Username = "admin" c.Realm = "test" c.Nonce = "00000001" - actual, _ := c.authorize(tc.method, tc.uri) + actual, err := c.authorize(tc.method, tc.uri) + assert.Nil(t, err) assert.Equal(t, tc.expected, actual) } } diff --git a/pkg/wsman/client/relay.go b/pkg/wsman/client/relay.go index 11731627..6a9d0c57 100644 --- a/pkg/wsman/client/relay.go +++ b/pkg/wsman/client/relay.go @@ -14,14 +14,13 @@ import ( "net/http/httputil" "net/url" "strconv" - "strings" "sync" "time" "github.com/gorilla/websocket" ) -// WsTransport is an implementation of http.Transport which uses websocket relay +// WsTransport is an implementation of http.Transport which uses websocket relay. type WsTransport struct { wsurl string protocol int @@ -34,7 +33,7 @@ type WsTransport struct { token string conn *websocket.Conn tlsconfig *tls.Config - buf_mutex sync.Mutex + bufMutex sync.Mutex messages []byte } @@ -51,24 +50,30 @@ func NewWsTransport(wsurl string, protocol int, host, username, password string, tls1only: tls1only, token: token, tlsconfig: tlsconfig, - buf_mutex: sync.Mutex{}, + bufMutex: sync.Mutex{}, } + return t } func (t *WsTransport) timedReadMessage(ms int) (b []byte) { timer := time.NewTimer(time.Duration(ms) * time.Millisecond) <-timer.C - t.buf_mutex.Lock() + t.bufMutex.Lock() b = append(b, t.messages...) t.messages = []byte{} - t.buf_mutex.Unlock() + t.bufMutex.Unlock() + return b } -func (t *WsTransport) buildUrl() string { +func (t *WsTransport) buildURL() string { // Use net/url to construct the URL - u, _ := url.Parse(t.wsurl) + u, err := url.Parse(t.wsurl) + if err != nil { + return "" + } + // Prepare query parameters q := u.Query() q.Set("p", strconv.Itoa(t.protocol)) @@ -80,36 +85,47 @@ func (t *WsTransport) buildUrl() string { q.Set("tls1only", strconv.FormatBool(t.tls1only)) // Set query string to URL u.RawQuery = q.Encode() + return u.String() } func (t *WsTransport) connectWebsocket() (conn *websocket.Conn, err error) { - url := t.buildUrl() + url := t.buildURL() + // Attempt to establish websocket connection - var hdr = http.Header{} + hdr := http.Header{} if t.token != "" { hdr.Set("Sec-Websocket-Protocol", t.token) } + wsdialer := websocket.Dialer{} wsdialer.TLSClientConfig = t.tlsconfig + conn, _, err = wsdialer.Dial(url, hdr) if err != nil { return nil, err - } else { - t.conn = conn - go func() { - for { - //Trying to read. - _, p, err := t.conn.ReadMessage() - if err != nil { - return - } - t.buf_mutex.Lock() - t.messages = append(t.messages, p...) - t.buf_mutex.Unlock() - } - }() } + + t.conn = conn + + go func() { + for { + // Trying to read. + var p []byte + + _, p, err = t.conn.ReadMessage() + if err != nil { + return + } + + t.bufMutex.Lock() + + t.messages = append(t.messages, p...) + + t.bufMutex.Unlock() + } + }() + return conn, err } @@ -120,58 +136,82 @@ func (t *WsTransport) disconnectWebsocket() { } } -// RoundTrip makes a low level text exchange over websocket. This is supposed to be used by high level round tripper +// RoundTrip makes a low level text exchange over websocket. This is supposed to be used by high level round tripper. func (t *WsTransport) RoundTrip(r *http.Request) (resp *http.Response, err error) { // Sanity check if t.wsurl == "" || t.protocol == 0 || t.host == "" || t.username == "" || t.password == "" || t.port == 0 { return nil, errors.New("invalid transport data") } + // Check if we had already established websocket for this transport object, if not create if t.conn == nil || t.conn.UnderlyingConn() == nil { - _, err := t.connectWebsocket() + _, err = t.connectWebsocket() if err != nil { return nil, err } } + // t.conn should be established // be careful when working with request Body.. make a copy - buf, _ := io.ReadAll(r.Body) + buf, err := io.ReadAll(r.Body) + if err != nil { + return nil, err + } + bd1 := io.NopCloser(bytes.NewBuffer(buf)) bd2 := io.NopCloser(bytes.NewBuffer(buf)) - l, _ := io.Copy(io.Discard, bd1) + + l, err := io.Copy(io.Discard, bd1) + if err != nil { + return nil, err + } + r.Body = bd2 r.Header.Add("Content-Length", strconv.FormatInt(l, 10)) - bytes_to_send, _ := httputil.DumpRequest(r, true) + bytesToSend, err := httputil.DumpRequest(r, true) + if err != nil { + return nil, err + } + // write and ignore error status, proper error handling is at read go routine - _ = t.conn.WriteMessage(websocket.TextMessage, bytes_to_send) + err = t.conn.WriteMessage(websocket.TextMessage, bytesToSend) + if err != nil { + return nil, err + } b := t.timedReadMessage(100) bf := []byte{} - bf = append(bf, b[:]...) + bf = append(bf, b...) // this is to check if we finished reading the whole body, otherwise read again // this will try to read data 10 times with 300 ms delay (3 seconds) if previous read yields empty data - max_count := 10 + maxCount := 10 count := 0 + for { b = t.timedReadMessage(300) // how many zero read if len(b) == 0 { - count = count + 1 - if count >= max_count { + count++ + if count >= maxCount { break } } - bf = append(bf, b[:]...) - if strings.Index(string(bf), "
") > 0 { + + bf = append(bf, b...) + if bytes.Index(bf, []byte("
")) > 0 { break } - if strings.Index(string(bf), "") > 0 { + + if bytes.Index(bf, []byte("")) > 0 { t.disconnectWebsocket() + break } } - read_buffer := bytes.NewReader(bf) - resp, err = http.ReadResponse(bufio.NewReader(read_buffer), r) + + readBuffer := bytes.NewReader(bf) + resp, err = http.ReadResponse(bufio.NewReader(readBuffer), r) + return resp, err } diff --git a/pkg/wsman/client/relay_test.go b/pkg/wsman/client/relay_test.go index c12ca63f..6a975548 100644 --- a/pkg/wsman/client/relay_test.go +++ b/pkg/wsman/client/relay_test.go @@ -26,20 +26,24 @@ func TestNewWsTransport(t *testing.T) { func TestNewWsTransportBuildUrl(t *testing.T) { baseurl := "wss://localhost/mps/ws/relay/webrelay.ashx" + trans := NewWsTransport(baseurl, 1, "9b3ee6a0-c1dc-5546-f7f3-54b2039edfb9", "user", "pass", 16992, false, false, "token", tlsconfig) if trans == nil { t.Error("NewWSTransporter constructor fails") } - url := trans.buildUrl() + + url := trans.buildURL() if url == "" { t.Error("Failed to build url") } + // second path trans = NewWsTransport(baseurl, 1, "9b3ee6a0-c1dc-5546-f7f3-54b2039edfb9", "user", "pass", 16992, true, true, "token", tlsconfig) if trans == nil { t.Error("NewWSTransporter constructor fails") } - url = trans.buildUrl() + + url = trans.buildURL() if url == "" { t.Error("Failed to build url") } @@ -47,58 +51,76 @@ func TestNewWsTransportBuildUrl(t *testing.T) { var upgrader = websocket.Upgrader{} -func relay_tester(w http.ResponseWriter, r *http.Request) { +func relayTester(w http.ResponseWriter, r *http.Request) { if strings.HasSuffix(r.RequestURI, "simulate_fail") { - _, _ = w.Write([]byte("Hello")) + _, err := w.Write([]byte("Hello")) + if err != nil { + return + } + return } + c, err := upgrader.Upgrade(w, r, nil) if err != nil { return } + if strings.Contains(r.RequestURI, "simulate_close") { // wait for few ms before close timer := time.NewTimer(time.Duration(100) * time.Millisecond) <-timer.C c.Close() + return } - simulate_delay := false + + simulateDelay := false + if strings.Contains(r.RequestURI, "simulate_delay") { - simulate_delay = true + simulateDelay = true } + defer c.Close() + for { mt, message, err := c.ReadMessage() if err != nil { break } - if simulate_delay { - ok_http_response := "HTTP/1.1 200 OK\r\nServer: dummy\r\n\r\nasdf" - err = c.WriteMessage(mt, []byte(ok_http_response)) + + if simulateDelay { + okHTTPResponse := "HTTP/1.1 200 OK\r\nServer: dummy\r\n\r\nasdf" + + err = c.WriteMessage(mt, []byte(okHTTPResponse)) if err != nil { break } + timer := time.NewTimer(time.Duration(1000) * time.Millisecond) <-timer.C + err = c.WriteMessage(mt, []byte("asdf\r\n\r\n")) if err != nil { break } + break } if strings.HasPrefix(string(message), "GET") { - //It is a GET request - ok_http_response := "HTTP/1.1 200 OK\r\nServer: dummy\r\n\r\n\r\n\r\n" - err = c.WriteMessage(mt, []byte(ok_http_response)) + // It is a GET request + okHTTPResponse := "HTTP/1.1 200 OK\r\nServer: dummy\r\n\r\n\r\n\r\n" + + err = c.WriteMessage(mt, []byte(okHTTPResponse)) if err != nil { break } } else if strings.HasPrefix(string(message), "POST") { - //It is a POST request - ok_http_response := "HTTP/1.1 200 OK\r\nServer: dummy\r\n\r\n\r\n\r\n" - err = c.WriteMessage(mt, []byte(ok_http_response)) + // It is a POST request + okHTTPResponse := "HTTP/1.1 200 OK\r\nServer: dummy\r\n\r\n\r\n\r\n" + + err = c.WriteMessage(mt, []byte(okHTTPResponse)) if err != nil { break } @@ -113,7 +135,7 @@ func relay_tester(w http.ResponseWriter, r *http.Request) { func TestNewWsTransportRoundtripBadParam(t *testing.T) { // Create test server with the echo handler. - s := httptest.NewServer(http.HandlerFunc(relay_tester)) + s := httptest.NewServer(http.HandlerFunc(relayTester)) defer s.Close() // Convert http://127.0.0.1 to ws://127.0.0. @@ -124,17 +146,22 @@ func TestNewWsTransportRoundtripBadParam(t *testing.T) { if trans == nil { t.Error("NewWSTransporter constructor fails") } - req := httptest.NewRequest("GET", "http://localhost", nil) + + defer trans.disconnectWebsocket() + + req := httptest.NewRequest("GET", "http://localhost", http.NoBody) + + defer req.Body.Close() + _, err := trans.RoundTrip(req) if err == nil { t.Error("Roundtripper should failed") } - defer trans.disconnectWebsocket() } func TestNewWsTransportRoundtripBadUrl(t *testing.T) { // Create test server with the echo handler. - s := httptest.NewServer(http.HandlerFunc(relay_tester)) + s := httptest.NewServer(http.HandlerFunc(relayTester)) defer s.Close() // bad url @@ -145,17 +172,22 @@ func TestNewWsTransportRoundtripBadUrl(t *testing.T) { if trans == nil { t.Error("NewWSTransporter constructor fails") } - req := httptest.NewRequest("GET", "http://localhost", nil) + + defer trans.disconnectWebsocket() + + req := httptest.NewRequest("GET", "http://localhost", http.NoBody) + + defer req.Body.Close() + _, err := trans.RoundTrip(req) if err == nil { t.Error("Roundtripper should failed") } - defer trans.disconnectWebsocket() } func TestNewWsTransportRoundtripGet(t *testing.T) { // Create test server with the echo handler. - s := httptest.NewServer(http.HandlerFunc(relay_tester)) + s := httptest.NewServer(http.HandlerFunc(relayTester)) defer s.Close() // Convert http://127.0.0.1 to ws://127.0.0. @@ -166,20 +198,24 @@ func TestNewWsTransportRoundtripGet(t *testing.T) { if trans == nil { t.Error("NewWSTransporter constructor fails") } - req := httptest.NewRequest("GET", "http://localhost", nil) + + defer trans.disconnectWebsocket() + + req := httptest.NewRequest("GET", "http://localhost", http.NoBody) + resp, err := trans.RoundTrip(req) if err != nil { t.Error("Roundtripper failed") } + if resp.StatusCode != 200 { t.Error("Dummy Get request failed") } - defer trans.disconnectWebsocket() } func TestNewWsTransportRoundtripPost(t *testing.T) { // Create test server with the echo handler. - s := httptest.NewServer(http.HandlerFunc(relay_tester)) + s := httptest.NewServer(http.HandlerFunc(relayTester)) defer s.Close() // Convert http://127.0.0.1 to ws://127.0.0. @@ -190,20 +226,24 @@ func TestNewWsTransportRoundtripPost(t *testing.T) { if trans == nil { t.Error("NewWSTransporter constructor fails") } - req := httptest.NewRequest("POST", "http://localhost", nil) + + defer trans.disconnectWebsocket() + + req := httptest.NewRequest("POST", "http://localhost", http.NoBody) + resp, err := trans.RoundTrip(req) if err != nil { t.Error("Roundtripper failed") } + if resp.StatusCode != 200 { t.Error("Dummy POST request failed") } - defer trans.disconnectWebsocket() } func TestNewWsTransportFailedConnection(t *testing.T) { // Create test server with the echo handler. - s := httptest.NewServer(http.HandlerFunc(relay_tester)) + s := httptest.NewServer(http.HandlerFunc(relayTester)) defer s.Close() // Convert http://127.0.0.1 to ws://127.0.0. @@ -214,17 +254,20 @@ func TestNewWsTransportFailedConnection(t *testing.T) { if trans == nil { t.Error("NewWSTransporter constructor fails") } - req := httptest.NewRequest("POST", "http://localhost", nil) + + defer trans.disconnectWebsocket() + + req := httptest.NewRequest("POST", "http://localhost", http.NoBody) + _, err := trans.RoundTrip(req) if err != nil { t.Error("Roundtripper should not fail") } - defer trans.disconnectWebsocket() } func TestNewWsTransportCloseConnection(t *testing.T) { // Create test server with the echo handler. - s := httptest.NewServer(http.HandlerFunc(relay_tester)) + s := httptest.NewServer(http.HandlerFunc(relayTester)) defer s.Close() // Convert http://127.0.0.1 to ws://127.0.0. @@ -235,17 +278,20 @@ func TestNewWsTransportCloseConnection(t *testing.T) { if trans == nil { t.Error("NewWSTransporter constructor fails") } - req := httptest.NewRequest("POST", "http://localhost", nil) + + defer trans.disconnectWebsocket() + + req := httptest.NewRequest("POST", "http://localhost", http.NoBody) + _, err := trans.RoundTrip(req) if err == nil { t.Error("Roundtripper should fail") } - defer trans.disconnectWebsocket() } func TestNewWsTransportDelay(t *testing.T) { // Create test server with the echo handler. - s := httptest.NewServer(http.HandlerFunc(relay_tester)) + s := httptest.NewServer(http.HandlerFunc(relayTester)) defer s.Close() // Convert http://127.0.0.1 to ws://127.0.0. @@ -256,10 +302,13 @@ func TestNewWsTransportDelay(t *testing.T) { if trans == nil { t.Error("NewWSTransporter constructor fails") } - req := httptest.NewRequest("POST", "http://localhost", nil) + + defer trans.disconnectWebsocket() + + req := httptest.NewRequest("POST", "http://localhost", http.NoBody) + _, err := trans.RoundTrip(req) if err != nil { t.Error("Roundtripper should not fail") } - defer trans.disconnectWebsocket() } diff --git a/pkg/wsman/client/types.go b/pkg/wsman/client/types.go index 3913f0ae..105852c1 100644 --- a/pkg/wsman/client/types.go +++ b/pkg/wsman/client/types.go @@ -1,6 +1,6 @@ package client -// Parameters struct defines the connection settings for wsman client +// Parameters struct defines the connection settings for wsman client. type Parameters struct { Target string Username string diff --git a/pkg/wsman/client/wsman.go b/pkg/wsman/client/wsman.go index ab977c39..85503446 100644 --- a/pkg/wsman/client/wsman.go +++ b/pkg/wsman/client/wsman.go @@ -20,13 +20,15 @@ import ( "github.com/sirupsen/logrus" ) -const ContentType = "application/soap+xml; charset=utf-8" -const NS_WSMAN = "http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd" -const NS_WSMID = "http://schemas.dmtf.org/wbem/wsman/identity/1/wsmanidentity.xsd" -const TLSPort = "16993" -const NonTLSPort = "16992" -const RedirectionTLSPort = "16995" -const RedirectionNonTLSPort = "16994" +const ( + ContentType = "application/soap+xml; charset=utf-8" + NSWSMAN = "http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd" + NSWSMID = "http://schemas.dmtf.org/wbem/wsman/identity/1/wsmanidentity.xsd" + TLSPort = "16993" + NonTLSPort = "16992" + RedirectionTLSPort = "16995" + RedirectionNonTLSPort = "16994" +) type Message struct { XMLInput string @@ -57,16 +59,21 @@ type Target struct { bufferPool sync.Pool } +const timeout = 10 * time.Second + func NewWsman(cp Parameters) *Target { path := "/wsman" port := NonTLSPort + if cp.UseTLS { port = TLSPort } + protocol := "http" if port == TLSPort { protocol = "https" } + res := &Target{ endpoint: protocol + "://" + cp.Target + ":" + port + path, username: cp.Username, @@ -75,66 +82,83 @@ func NewWsman(cp Parameters) *Target { logAMTMessages: cp.LogAMTMessages, } - res.Timeout = 10 * time.Second + res.Timeout = timeout res.Transport = &http.Transport{ TLSClientConfig: &tls.Config{InsecureSkipVerify: cp.SelfSignedAllowed}, } + if res.useDigest { res.challenge = &AuthChallenge{Username: res.username, Password: res.password} } + return res } -// Post overrides http.Client's Post method -func (c *Target) Post(msg string) (response []byte, err error) { +// Post overrides http.Client's Post method. +func (t *Target) Post(msg string) (response []byte, err error) { msgBody := []byte(msg) + + var auth string + bodyReader := bytes.NewReader(msgBody) - req, err := http.NewRequest("POST", c.endpoint, bodyReader) + + req, err := http.NewRequest("POST", t.endpoint, bodyReader) if err != nil { return nil, err } - if c.username != "" && c.password != "" { - if c.useDigest { - - auth, err := c.challenge.authorize("POST", "/wsman") + if t.username != "" && t.password != "" { + if t.useDigest { + auth, err = t.challenge.authorize("POST", "/wsman") if err != nil { - return nil, fmt.Errorf("failed digest auth %v", err) + return nil, fmt.Errorf("failed digest auth %w", err) } - if c.challenge.Realm != "" { + + if t.challenge.Realm != "" { req.Header.Set("Authorization", auth) } } else { - req.SetBasicAuth(c.username, c.password) + req.SetBasicAuth(t.username, t.password) } } + req.Header.Add("content-type", ContentType) - if c.logAMTMessages { + if t.logAMTMessages { logrus.Trace(msg) } - res, err := c.Do(req) + + res, err := t.Do(req) if err != nil { + res.Body.Close() + return nil, err } - if c.useDigest && res.StatusCode == 401 { - if err := c.challenge.parseChallenge(res.Header.Get("WWW-Authenticate")); err != nil { + if t.useDigest && res.StatusCode == 401 { + if err := t.challenge.parseChallenge(res.Header.Get("WWW-Authenticate")); err != nil { return nil, err } - auth, err := c.challenge.authorize("POST", "/wsman") + + auth, err = t.challenge.authorize("POST", "/wsman") if err != nil { - return nil, fmt.Errorf("failed digest auth %v", err) + return nil, fmt.Errorf("failed digest auth %w", err) } + bodyReader = bytes.NewReader(msgBody) - req, err = http.NewRequest("POST", c.endpoint, bodyReader) + + req, err = http.NewRequest("POST", t.endpoint, bodyReader) if err != nil { return nil, err } + req.Header.Set("Authorization", auth) req.Header.Add("content-type", ContentType) - res, err = c.Do(req) + + res, err = t.Do(req) if err != nil && err.Error() != io.EOF.Error() { + res.Body.Close() + return nil, err } } @@ -142,15 +166,23 @@ func (c *Target) Post(msg string) (response []byte, err error) { defer res.Body.Close() if res.StatusCode >= 400 { - b, _ := io.ReadAll(res.Body) - if c.logAMTMessages { + b, err := io.ReadAll(res.Body) + if err != nil { + return nil, err + } + + if t.logAMTMessages { logrus.Trace(string(b)) } - return nil, fmt.Errorf("wsman.Client: post received %v\n'%v'", res.Status, string(b)) + + errPostResponse := errors.New("wsman.Client post received") + + return nil, fmt.Errorf("%w: %v\n%v", errPostResponse, res.Status, string(b)) } response, err = io.ReadAll(res.Body) - if c.logAMTMessages { + + if t.logAMTMessages { logrus.Trace(string(response)) } @@ -161,18 +193,21 @@ func (c *Target) Post(msg string) (response []byte, err error) { return response, nil } -// ProxyUrl sets proxy address for the underlying Transport if supported -func (c *Target) ProxyUrl(proxy_str string) (err error) { - //check if c.Transport is *http.Transport, otherwise currently it is not supported - _, ok := c.Transport.(*http.Transport) +// ProxyURL sets proxy address for the underlying Transport if supported. +func (t *Target) ProxyURL(proxyStr string) (err error) { + // check if c.Transport is *http.Transport, otherwise currently it is not supported + _, ok := t.Transport.(*http.Transport) if !ok { return errors.New("transport does not support proxy") } + // check if proxy parsing failed or check if scheme is not nil - proxyUrl, err := url.Parse(proxy_str) - if err != nil || (proxyUrl != nil && proxyUrl.Scheme == "") { + proxyURL, err := url.Parse(proxyStr) + if err != nil || (proxyURL != nil && proxyURL.Scheme == "") { return errors.New("unknown URL Scheme") } - c.Transport.(*http.Transport).Proxy = http.ProxyURL(proxyUrl) + + t.Transport.(*http.Transport).Proxy = http.ProxyURL(proxyURL) + return nil } diff --git a/pkg/wsman/client/wsman_tcp.go b/pkg/wsman/client/wsman_tcp.go index 1b64d16f..3f6a6a4e 100644 --- a/pkg/wsman/client/wsman_tcp.go +++ b/pkg/wsman/client/wsman_tcp.go @@ -11,6 +11,7 @@ func NewWsmanTCP(cp Parameters) *Target { if cp.UseTLS { port = RedirectionTLSPort } + return &Target{ endpoint: cp.Target + ":" + port, username: cp.Username, @@ -20,26 +21,28 @@ func NewWsmanTCP(cp Parameters) *Target { challenge: &AuthChallenge{}, bufferPool: sync.Pool{ New: func() interface{} { - return make([]byte, 4096) // Adjust size according to your needs + return make([]byte, 4096) // Adjust size according to your needs. }, }, } } -// Connect establishes a TCP connection to the endpoint specified in the Target struct +// Connect establishes a TCP connection to the endpoint specified in the Target struct. func (t *Target) Connect() error { conn, err := net.Dial("tcp", t.endpoint) if err != nil { return fmt.Errorf("failed to connect to %s: %w", t.endpoint, err) } + t.conn = conn - // Type assert the net.Conn to *net.TCPConn to access TCP-specific options + + // Type assert the net.Conn to *net.TCPConn to access TCP-specific options. tcpConn, ok := t.conn.(*net.TCPConn) if !ok { return fmt.Errorf("connection is not a TCP connection") } - // Disable Nagle's Algorithm for this TCP connection + // Disable Nagle's Algorithm for this TCP connection. if err := tcpConn.SetNoDelay(true); err != nil { return fmt.Errorf("failed to set NoDelay: %w", err) } @@ -47,26 +50,34 @@ func (t *Target) Connect() error { return nil } -// Send sends data to the connected TCP endpoint in the Target struct +// Send sends data to the connected TCP endpoint in the Target struct. func (t *Target) Send(data []byte) error { if t.conn == nil { return fmt.Errorf("no active connection") } + _, err := t.conn.Write(data) if err != nil { return fmt.Errorf("failed to send data: %w", err) } + return nil } -// Receive reads data from the connected TCP endpoint in the Target struct +// Receive reads data from the connected TCP endpoint in the Target struct. func (t *Target) Receive() ([]byte, error) { if t.conn == nil { return nil, fmt.Errorf("no active connection") } - tmp := t.bufferPool.Get().([]byte) - defer t.bufferPool.Put(tmp) + item := t.bufferPool.Get() + + tmp, ok := item.([]byte) + if !ok { + return nil, fmt.Errorf("failed to get buffer from pool") + } + + defer t.bufferPool.Put(&tmp) n, err := t.conn.Read(tmp) if err != nil { @@ -76,15 +87,18 @@ func (t *Target) Receive() ([]byte, error) { return append([]byte(nil), tmp[:n]...), nil } -// CloseConnection cleanly closes the TCP connection +// CloseConnection cleanly closes the TCP connection. func (t *Target) CloseConnection() error { if t.conn == nil { return fmt.Errorf("no active connection to close") } + err := t.conn.Close() if err != nil { return fmt.Errorf("failed to close connection: %w", err) } + t.conn = nil + return nil } diff --git a/pkg/wsman/client/wsman_test.go b/pkg/wsman/client/wsman_test.go index e4fe60e5..7912e005 100644 --- a/pkg/wsman/client/wsman_test.go +++ b/pkg/wsman/client/wsman_test.go @@ -6,11 +6,15 @@ package client import ( + "net/http" + "net/http/httptest" "strings" "testing" +) - "net/http" - "net/http/httptest" +const ( + testMsg = "Request" + testResponse = "OK" ) func TestNewClient(t *testing.T) { @@ -30,12 +34,15 @@ func TestNewClient(t *testing.T) { if client.endpoint != expectedTarget { t.Errorf("Expected endpoint to be %s, but got %s", cp.Target, client.endpoint) } + if client.username != cp.Username { t.Errorf("Expected username to be %s, but got %s", cp.Username, client.username) } + if client.password != cp.Password { t.Errorf("Expected password to be %s, but got %s", cp.Password, client.password) } + if client.useDigest != cp.UseDigest { t.Errorf("Expected useDigest to be %v, but got %v", cp.UseDigest, client.useDigest) } @@ -58,12 +65,15 @@ func TestNewClient_TLS(t *testing.T) { if client.endpoint != expectedTarget { t.Errorf("Expected endpoint to be %s, but got %s", cp.Target, client.endpoint) } + if client.username != cp.Username { t.Errorf("Expected username to be %s, but got %s", cp.Username, client.username) } + if client.password != cp.Password { t.Errorf("Expected password to be %s, but got %s", cp.Password, client.password) } + if client.useDigest != cp.UseDigest { t.Errorf("Expected useDigest to be %v, but got %v", cp.UseDigest, client.useDigest) } @@ -73,7 +83,11 @@ func TestClient_Post(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", ContentType) w.WriteHeader(http.StatusOK) - _, _ = w.Write([]byte("OK")) + + _, err := w.Write([]byte(testResponse)) + if err != nil { + t.Errorf("Unexpected error during write: %v", err) + } })) defer ts.Close() @@ -88,7 +102,7 @@ func TestClient_Post(t *testing.T) { } client := NewWsman(cp) - msg := "Request" + msg := testMsg client.endpoint = ts.URL @@ -97,11 +111,12 @@ func TestClient_Post(t *testing.T) { t.Errorf("Unexpected error during POST: %v", err) } - expectedResponse := "OK" + expectedResponse := testResponse if string(response) != expectedResponse { t.Errorf("Expected response to be %s, but got %s", expectedResponse, response) } } + func newMockDigestAuthHandler(username, password string, handler http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { authHeader := r.Header.Get("Authorization") @@ -119,14 +134,19 @@ func newMockDigestAuthHandler(username, password string, handler http.Handler) h } }) } + func TestClient_PostWithDigestAuth(t *testing.T) { // Use a simple digest auth implementation for testing purposes - ts := httptest.NewServer(newMockDigestAuthHandler("user", "password", http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", ContentType) w.WriteHeader(http.StatusOK) - _, _ = w.Write([]byte("OK")) + + _, err := w.Write([]byte(testResponse)) + if err != nil { + t.Errorf("Unexpected error during write: %v", err) + } })))) + defer ts.Close() cp := Parameters{ @@ -140,15 +160,16 @@ func TestClient_PostWithDigestAuth(t *testing.T) { } client := NewWsman(cp) - msg := "Request" + msg := testMsg client.endpoint = ts.URL + response, err := client.Post(msg) if err != nil { t.Errorf("Unexpected error during POST with digest auth: %v", err) } - expectedResponse := "OK" + expectedResponse := testResponse if string(response) != expectedResponse { t.Errorf("Expected response to be %s, but got %s", expectedResponse, response) } @@ -159,6 +180,7 @@ func TestClient_PostWithDigestAuthUnauthorized(t *testing.T) { w.Header().Set("Content-Type", ContentType) w.WriteHeader(http.StatusOK) }))) + defer ts.Close() cp := Parameters{ @@ -172,9 +194,10 @@ func TestClient_PostWithDigestAuthUnauthorized(t *testing.T) { } client := NewWsman(cp) - msg := "Request" + msg := testMsg client.endpoint = ts.URL + _, err := client.Post(msg) if err == nil { t.Error("Expected error during POST with wrong digest auth credentials, but got nil") @@ -186,13 +209,19 @@ func TestClient_PostWithBasicAuth(t *testing.T) { username, password, ok := r.BasicAuth() if !ok || username != "user" || password != "password" { http.Error(w, "Unauthorized", http.StatusUnauthorized) + return } w.Header().Set("Content-Type", ContentType) w.WriteHeader(http.StatusOK) - _, _ = w.Write([]byte("OK")) + + _, err := w.Write([]byte(testResponse)) + if err != nil { + t.Errorf("Unexpected error during write: %v", err) + } })) + defer ts.Close() cp := Parameters{ @@ -206,23 +235,27 @@ func TestClient_PostWithBasicAuth(t *testing.T) { } client := NewWsman(cp) - msg := "Request" + msg := testMsg client.endpoint = ts.URL + response, err := client.Post(msg) if err != nil { t.Errorf("Unexpected error during POST with basic auth: %v", err) } - expectedResponse := "OK" + expectedResponse := testResponse + if string(response) != expectedResponse { t.Errorf("Expected response to be %s, but got %s", expectedResponse, response) } } + func TestClient_PostUnauthorized(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { http.Error(w, "Unauthorized", http.StatusUnauthorized) })) + defer ts.Close() cp := Parameters{ @@ -235,9 +268,10 @@ func TestClient_PostUnauthorized(t *testing.T) { LogAMTMessages: false, } client := NewWsman(cp) - msg := "Request" + msg := testMsg client.endpoint = ts.URL + _, err := client.Post(msg) if err == nil { t.Error("Expected error during POST with wrong credentials, but got nil") @@ -248,8 +282,13 @@ func TestClient_PostInvalidResponse(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", ContentType) w.WriteHeader(http.StatusInternalServerError) - _, _ = w.Write([]byte("Internal Server Error")) + + _, err := w.Write([]byte("Internal Server Error")) + if err != nil { + t.Errorf("Unexpected error during write: %v", err) + } })) + defer ts.Close() cp := Parameters{ @@ -263,9 +302,10 @@ func TestClient_PostInvalidResponse(t *testing.T) { } client := NewWsman(cp) - msg := "Request" + msg := testMsg client.endpoint = ts.URL + _, err := client.Post(msg) if err == nil { t.Error("Expected error during POST with invalid response, but got nil") @@ -276,7 +316,7 @@ func TestClient_PostWithDigestBlankRealm(t *testing.T) { ts := httptest.NewServer(newMockDigestAuthHandler("user", "password", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { authHeader := r.Header.Get("Authorization") if strings.HasPrefix(authHeader, "Digest ") { - //Simulate internal server error + // Simulate internal server error w.WriteHeader(http.StatusInternalServerError) } else { // Simulate a server requesting digest authentication with required fields @@ -298,21 +338,21 @@ func TestClient_PostWithDigestBlankRealm(t *testing.T) { client := NewWsman(cp) client.challenge.Realm = "" - msg := "Request" + msg := testMsg client.endpoint = ts.URL + _, err := client.Post(msg) if err == nil { t.Error("Expected error during POST with wrong digest auth credentials, but got nil") } + if !strings.Contains(err.Error(), "500 Internal Server Error") { t.Error("Wsman client should not send digest on initial challenges") } - } func TestClient_ProxyUrlTransport(t *testing.T) { - cp := Parameters{ Target: "example.com", Username: "user", @@ -324,7 +364,8 @@ func TestClient_ProxyUrlTransport(t *testing.T) { } client := NewWsman(cp) - err := client.ProxyUrl("http://localhost:3128") + + err := client.ProxyURL("http://localhost:3128") if err != nil { t.Error("Failed to set proxy on proper Transport") } @@ -342,13 +383,14 @@ func TestClient_InvalidProxyUrlGoodTransport(t *testing.T) { } client := NewWsman(cp) - err := client.ProxyUrl("localhost") + + err := client.ProxyURL("localhost") if err == nil { t.Error("Failed to detect invalid proxy url") } } -// inline struct for mock roundtripper +// inline struct for mock roundtripper. type rt struct{} func (*rt) RoundTrip(r *http.Request) (*http.Response, error) { @@ -369,7 +411,8 @@ func TestClient_SimpleRountripper(t *testing.T) { mockrt := rt{} client := NewWsman(cp) client.Transport = &mockrt - err := client.ProxyUrl("http://localhost:3128") + + err := client.ProxyURL("http://localhost:3128") if err == nil { t.Error("Failed to detect proper transport") } diff --git a/pkg/wsman/common/constants.go b/pkg/wsman/common/constants.go index 10125d4e..3ca60443 100644 --- a/pkg/wsman/common/constants.go +++ b/pkg/wsman/common/constants.go @@ -7,9 +7,11 @@ package common // TODO: Review if this file is still necessary. +const ValueNotFound string = "Value not found in map" + // OUTPUTS Lookups -// ReturnValues is a map of return values to their string representation +// ReturnValuesToString is a map of return values to their string representation. var ReturnValuesToString = map[int]string{ 0: "PT_STATUS_SUCCESS", 1: "PT_STATUS_INTERNAL_ERROR", @@ -69,15 +71,16 @@ var ReturnValuesToString = map[int]string{ 2082: "PT_STATUS_OPERATION_IN_PROGRESS", } -// ConvertReturnValueToString returns the string representation of the return value +// ConvertReturnValueToString returns the string representation of the return value. func ConvertReturnValueToString(value int) string { if value, exists := ReturnValuesToString[value]; exists { return value } - return "Value not found in map" + + return ValueNotFound } -// EnabledStateStrings is a map of EnabledState values to their string representations +// EnabledStateToString is a map of EnabledState values to their string representations. var EnabledStateToString = map[int]string{ 0: "Unknown", 1: "Other", @@ -92,15 +95,16 @@ var EnabledStateToString = map[int]string{ 10: "Starting", } -// ConvertEnabledStateToString returns the string representation of an EnabledState value +// ConvertEnabledStateToString returns the string representation of an EnabledState value. func ConvertEnabledStateToString(value int) string { if value, exists := EnabledStateToString[value]; exists { return value } - return "Value not found in map" + + return ValueNotFound } -// RequestedStateStrings is a map of RequestedState values to their string representations +// RequestedStateToString is a map of RequestedState values to their string representations. var RequestedStateToString = map[int]string{ 0: "Unknown", 2: "Enabled", @@ -116,15 +120,16 @@ var RequestedStateToString = map[int]string{ 12: "NotApplicable", } -// ConvertRequestedStateToString returns the string representation of a RequestedState value +// ConvertRequestedStateToString returns the string representation of a RequestedState value. func ConvertRequestedStateToString(value int) string { if value, exists := RequestedStateToString[value]; exists { return value } - return "Value not found in map" + + return ValueNotFound } -// OperationalStatusToString is a map of OperationalStatus value to string +// OperationalStatusToString is a map of OperationalStatus value to string. var OperationalStatusToString = map[int]string{ 0: "Unknown", 1: "Other", @@ -148,15 +153,16 @@ var OperationalStatusToString = map[int]string{ 19: "Relocating", } -// ConvertOperationalStatusToString returns the string representation of OperationalStatus +// ConvertOperationalStatusToString returns the string representation of OperationalStatus. func ConvertOperationalStatusToString(value int) string { if value, exists := OperationalStatusToString[value]; exists { return value } - return "Value not found in map" + + return ValueNotFound } -// EnabledDefaultToString is a map of EnabledDefault value to string +// EnabledDefaultToString is a map of EnabledDefault value to string. var EnabledDefaultToString = map[int]string{ 2: "Enabled", 3: "Disabled", @@ -166,15 +172,16 @@ var EnabledDefaultToString = map[int]string{ 9: "Quiesce", } -// ConvertEnabledDefaultToString returns the string representation of EnabledDefault +// ConvertEnabledDefaultToString returns the string representation of EnabledDefault. func ConvertEnabledDefaultToString(value int) string { if value, exists := EnabledDefaultToString[value]; exists { return value } - return "Value not found in map" + + return ValueNotFound } -// Indicates the current health of the element. +// HealthStateToString indicates the current health of the element. var HealthStateToString = map[int]string{ 0: "Unknown", 5: "OK", @@ -185,15 +192,16 @@ var HealthStateToString = map[int]string{ 30: "Non-recoverable Error", } -// ConvertHealthStateToString returns the string representation of the health state +// ConvertHealthStateToString returns the string representation of the health state. func ConvertHealthStateToString(value int) string { if value, exists := HealthStateToString[value]; exists { return value } - return "Value not found in map" + + return ValueNotFound } -// PackageTypeToString is a mapping of the PackageType value to a string +// PackageTypeToString is a mapping of the PackageType value to a string. var PackageTypeToString = map[int]string{ 0: "Unknown", 1: "Other", @@ -215,11 +223,11 @@ var PackageTypeToString = map[int]string{ 17: "Blade Expansion", } -// ConvertPackageTypeToString returns the string representation of the PackageType value +// ConvertPackageTypeToString returns the string representation of the PackageType value. func ConvertPackageTypeToString(value int) string { if value, exists := PackageTypeToString[value]; exists { return value } - return "Value not found in map" + return ValueNotFound } diff --git a/pkg/wsman/ips/alarmclock/constants.go b/pkg/wsman/ips/alarmclock/constants.go index ea0a0a83..f7320073 100644 --- a/pkg/wsman/ips/alarmclock/constants.go +++ b/pkg/wsman/ips/alarmclock/constants.go @@ -5,4 +5,4 @@ package alarmclock -const IPS_AlarmClockOccurrence string = "IPS_AlarmClockOccurrence" +const IPSAlarmClockOccurrence string = "IPS_AlarmClockOccurrence" diff --git a/pkg/wsman/ips/alarmclock/marshal.go b/pkg/wsman/ips/alarmclock/marshal.go index 9c82df6e..2b6c43c8 100644 --- a/pkg/wsman/ips/alarmclock/marshal.go +++ b/pkg/wsman/ips/alarmclock/marshal.go @@ -11,20 +11,22 @@ import ( "gopkg.in/yaml.v3" ) -// JSON marshals the type into JSON format +// JSON marshals the type into JSON format. func (r *Response) JSON() string { jsonOutput, err := json.Marshal(r.Body) if err != nil { return "" } + return string(jsonOutput) } -// YAML marshals the type into YAML format +// YAML marshals the type into YAML format. func (r *Response) YAML() string { yamlOutput, err := yaml.Marshal(r.Body) if err != nil { return "" } + return string(yamlOutput) } diff --git a/pkg/wsman/ips/alarmclock/occurrence.go b/pkg/wsman/ips/alarmclock/occurrence.go index 27470e90..9d4e3e66 100644 --- a/pkg/wsman/ips/alarmclock/occurrence.go +++ b/pkg/wsman/ips/alarmclock/occurrence.go @@ -16,33 +16,37 @@ import ( // NewAlarmClockOccurrence returns a new instance of the AlarmClockOccurrence struct. func NewAlarmClockOccurrenceWithClient(wsmanMessageCreator *message.WSManMessageCreator, client client.WSMan) Occurrence { return Occurrence{ - base: message.NewBaseWithClient(wsmanMessageCreator, IPS_AlarmClockOccurrence, client), + base: message.NewBaseWithClient(wsmanMessageCreator, IPSAlarmClockOccurrence, client), } } -// Get retrieves the representation of the instance +// Get retrieves the representation of the instance. func (occurrence Occurrence) Get(alarmName string) (response Response, err error) { selector := message.Selector{ Name: "Name", Value: alarmName, } + response = Response{ Message: &client.Message{ XMLInput: occurrence.base.Get(&selector), }, } + err = occurrence.base.Execute(response.Message) if err != nil { return } + err = xml.Unmarshal([]byte(response.XMLOutput), &response) if err != nil { return } + return } -// Delete removes a the specified instance +// Delete removes a the specified instance. func (occurrence Occurrence) Delete(handle string) (response Response, err error) { selector := message.Selector{Name: "Name", Value: handle} response = Response{ @@ -50,32 +54,38 @@ func (occurrence Occurrence) Delete(handle string) (response Response, err error XMLInput: occurrence.base.Delete(selector), }, } + err = occurrence.base.Execute(response.Message) if err != nil { return } + err = xml.Unmarshal([]byte(response.XMLOutput), &response) if err != nil { return } + return } -// Enumerate returns an enumeration context which is used in a subsequent Pull call +// Enumerate returns an enumeration context which is used in a subsequent Pull call. func (occurrence Occurrence) Enumerate() (response Response, err error) { response = Response{ Message: &client.Message{ XMLInput: occurrence.base.Enumerate(), }, } + err = occurrence.base.Execute(response.Message) if err != nil { return } + err = xml.Unmarshal([]byte(response.XMLOutput), &response) if err != nil { return } + return } @@ -86,13 +96,16 @@ func (occurrence Occurrence) Pull(enumerationContext string) (response Response, XMLInput: occurrence.base.Pull(enumerationContext), }, } + err = occurrence.base.Execute(response.Message) if err != nil { return } + err = xml.Unmarshal([]byte(response.XMLOutput), &response) if err != nil { return } + return } diff --git a/pkg/wsman/ips/alarmclock/occurrence_test.go b/pkg/wsman/ips/alarmclock/occurrence_test.go index d111123b..ac2ad83c 100644 --- a/pkg/wsman/ips/alarmclock/occurrence_test.go +++ b/pkg/wsman/ips/alarmclock/occurrence_test.go @@ -10,11 +10,10 @@ import ( "fmt" "testing" - "github.com/stretchr/testify/assert" - "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/internal/message" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/common" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/wsmantesting" + "github.com/stretchr/testify/assert" ) func TestJson(t *testing.T) { @@ -41,8 +40,8 @@ func TestYaml(t *testing.T) { func TestPositiveIPS_AlarmClockOccurrence(t *testing.T) { messageID := 0 - resourceUriBase := "http://intel.com/wbem/wscim/1/ips-schema/1/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.IPSResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "ips/alarmclock", } @@ -58,21 +57,22 @@ func TestPositiveIPS_AlarmClockOccurrence(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //GETS + // GETS { "should create a valid ips_AlarmClockOccurrence Get wsman message", "IPS_AlarmClockOccurrence", - wsmantesting.GET, + wsmantesting.Get, "", "testalarm", func() (Response, error) { - client.CurrentMessage = "Get" + client.CurrentMessage = wsmantesting.CurrentMessageGet + return elementUnderTest.Get("testalarm") }, Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, GetResponse: AlarmClockOccurrence{ - XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.IPSSchema, IPS_AlarmClockOccurrence), Local: IPS_AlarmClockOccurrence}, + XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.IPSSchema, IPSAlarmClockOccurrence), Local: IPSAlarmClockOccurrence}, ElementName: "testalarm", InstanceID: "testalarm", StartTime: "testdatetime", @@ -81,15 +81,16 @@ func TestPositiveIPS_AlarmClockOccurrence(t *testing.T) { }, }, }, - //ENUMERATES + // ENUMERATES { "should create a valid IPS_AlarmClockOccurrence Enumerate wsman message", "IPS_AlarmClockOccurrence", - wsmantesting.ENUMERATE, - wsmantesting.ENUMERATE_BODY, + wsmantesting.Enumerate, + wsmantesting.EnumerateBody, "", func() (Response, error) { - client.CurrentMessage = "Enumerate" + client.CurrentMessage = wsmantesting.CurrentMessageEnumerate + return elementUnderTest.Enumerate() }, Body{ @@ -99,15 +100,16 @@ func TestPositiveIPS_AlarmClockOccurrence(t *testing.T) { }, }, }, - //PULLS + // PULLS { "should create a valid IPS_AlarmClockOccurrence Pull wsman message", "IPS_AlarmClockOccurrence", - wsmantesting.PULL, - wsmantesting.PULL_BODY, + wsmantesting.Pull, + wsmantesting.PullBody, "", func() (Response, error) { - client.CurrentMessage = "Pull" + client.CurrentMessage = wsmantesting.CurrentMessagePull + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -116,7 +118,7 @@ func TestPositiveIPS_AlarmClockOccurrence(t *testing.T) { XMLName: xml.Name{Space: message.XMLPullResponseSpace, Local: "PullResponse"}, Items: []AlarmClockOccurrence{ { - XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.IPSSchema, IPS_AlarmClockOccurrence), Local: IPS_AlarmClockOccurrence}, + XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.IPSSchema, IPSAlarmClockOccurrence), Local: IPSAlarmClockOccurrence}, ElementName: "testalarm", InstanceID: "testalarm", StartTime: "testdatetime", @@ -131,11 +133,12 @@ func TestPositiveIPS_AlarmClockOccurrence(t *testing.T) { { "should create a valid ips_AlarmClockOccurrence Delete wsman message", "IPS_AlarmClockOccurrence", - wsmantesting.DELETE, + wsmantesting.Delete, "", "testalarm", func() (Response, error) { - client.CurrentMessage = "Delete" + client.CurrentMessage = wsmantesting.CurrentMessageDelete + return elementUnderTest.Delete("testalarm") }, Body{XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}}, @@ -144,7 +147,7 @@ func TestPositiveIPS_AlarmClockOccurrence(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, test.extraHeader, test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, test.extraHeader, test.body) messageID++ response, err := test.responseFunc() assert.NoError(t, err) @@ -154,10 +157,11 @@ func TestPositiveIPS_AlarmClockOccurrence(t *testing.T) { } }) } + func TestNegativeIPS_AlarmClockOccurrence(t *testing.T) { messageID := 0 - resourceUriBase := "http://intel.com/wbem/wscim/1/ips-schema/1/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.IPSResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "ips/alarmclock", } @@ -173,21 +177,22 @@ func TestNegativeIPS_AlarmClockOccurrence(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //GETS + // GETS { "should create a valid ips_AlarmClockOccurrence Get wsman message", "IPS_AlarmClockOccurrence", - wsmantesting.GET, + wsmantesting.Get, "", "testalarm", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Get("testalarm") }, Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, GetResponse: AlarmClockOccurrence{ - XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.IPSSchema, IPS_AlarmClockOccurrence), Local: IPS_AlarmClockOccurrence}, + XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.IPSSchema, IPSAlarmClockOccurrence), Local: IPSAlarmClockOccurrence}, ElementName: "testalarm", InstanceID: "testalarm", StartTime: "testdatetime", @@ -196,15 +201,16 @@ func TestNegativeIPS_AlarmClockOccurrence(t *testing.T) { }, }, }, - //ENUMERATES + // ENUMERATES { "should create a valid IPS_AlarmClockOccurrence Enumerate wsman message", "IPS_AlarmClockOccurrence", - wsmantesting.ENUMERATE, - wsmantesting.ENUMERATE_BODY, + wsmantesting.Enumerate, + wsmantesting.EnumerateBody, "", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Enumerate() }, Body{ @@ -214,15 +220,16 @@ func TestNegativeIPS_AlarmClockOccurrence(t *testing.T) { }, }, }, - //PULLS + // PULLS { "should create a valid IPS_AlarmClockOccurrence Pull wsman message", "IPS_AlarmClockOccurrence", - wsmantesting.PULL, - wsmantesting.PULL_BODY, + wsmantesting.Pull, + wsmantesting.PullBody, "", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -231,7 +238,7 @@ func TestNegativeIPS_AlarmClockOccurrence(t *testing.T) { XMLName: xml.Name{Space: message.XMLPullResponseSpace, Local: "PullResponse"}, Items: []AlarmClockOccurrence{ { - XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.IPSSchema, IPS_AlarmClockOccurrence), Local: IPS_AlarmClockOccurrence}, + XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.IPSSchema, IPSAlarmClockOccurrence), Local: IPSAlarmClockOccurrence}, ElementName: "testalarm", InstanceID: "testalarm", StartTime: "testdatetime", @@ -246,11 +253,12 @@ func TestNegativeIPS_AlarmClockOccurrence(t *testing.T) { { "should create a valid ips_AlarmClockOccurrence Delete wsman message", "IPS_AlarmClockOccurrence", - wsmantesting.DELETE, + wsmantesting.Delete, "", "testalarm", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Delete("testalarm") }, Body{XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}}, @@ -259,7 +267,7 @@ func TestNegativeIPS_AlarmClockOccurrence(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, test.extraHeader, test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, test.extraHeader, test.body) messageID++ response, err := test.responseFunc() assert.Error(t, err) diff --git a/pkg/wsman/ips/alarmclock/types.go b/pkg/wsman/ips/alarmclock/types.go index e7c0ebaa..49d8cffa 100644 --- a/pkg/wsman/ips/alarmclock/types.go +++ b/pkg/wsman/ips/alarmclock/types.go @@ -18,7 +18,7 @@ type Occurrence struct { } // OUTPUT -// Response Types +// Response Types. type ( Response struct { *client.Message diff --git a/pkg/wsman/ips/hostbasedsetup/decoder.go b/pkg/wsman/ips/hostbasedsetup/decoder.go index 98bf5a6d..a4b31b9d 100644 --- a/pkg/wsman/ips/hostbasedsetup/decoder.go +++ b/pkg/wsman/ips/hostbasedsetup/decoder.go @@ -6,11 +6,12 @@ package hostbasedsetup const ( - IPS_HostBasedSetupService string = "IPS_HostBasedSetupService" - Setup string = "Setup" - AdminSetup string = "AdminSetup" - AddNextCertInChain string = "AddNextCertInChain" - UpgradeClientToAdmin string = "UpgradeClientToAdmin" + IPSHostBasedSetupService string = "IPS_HostBasedSetupService" + Setup string = "Setup" + AdminSetup string = "AdminSetup" + AddNextCertInChain string = "AddNextCertInChain" + UpgradeClientToAdmin string = "UpgradeClientToAdmin" + ValueNotFound string = "Value not found in map" ) const ( @@ -19,19 +20,20 @@ const ( AdminPassEncryptionTypeHTTPDigestMD5A1 ) -// adminPassEncryptionTypeToString is a map of AdminPassEncryptionType value to string +// adminPassEncryptionTypeToString is a map of AdminPassEncryptionType value to string. var adminPassEncryptionTypeToString = map[AdminPassEncryptionType]string{ AdminPassEncryptionTypeNone: "None", AdminPassEncryptionTypeOther: "Other", AdminPassEncryptionTypeHTTPDigestMD5A1: "HTTPDigestMD5A1", } -// String returns a human-readable string representation of the AdminPassEncryptionType enumeration +// String returns a human-readable string representation of the AdminPassEncryptionType enumeration. func (a AdminPassEncryptionType) String() string { if s, ok := adminPassEncryptionTypeToString[a]; ok { return s } - return "Value not found in map" + + return ValueNotFound } const ( @@ -40,19 +42,20 @@ const ( SigningAlgorithmRSASHA2256 ) -// signingAlgorithmToString is a map of SigningAlgorithm value to string +// signingAlgorithmToString is a map of SigningAlgorithm value to string. var signingAlgorithmToString = map[SigningAlgorithm]string{ SigningAlgorithmNone: "None", SigningAlgorithmOther: "Other", SigningAlgorithmRSASHA2256: "RSASHA2256", } -// String returns a human-readable string representation of the SigningAlgorithm enumeration +// String returns a human-readable string representation of the SigningAlgorithm enumeration. func (s SigningAlgorithm) String() string { if s, ok := signingAlgorithmToString[s]; ok { return s } - return "Value not found in map" + + return ValueNotFound } const ( @@ -61,19 +64,20 @@ const ( Admin ) -// currentControlModeToString is a map of CurrentControlMode value to string +// currentControlModeToString is a map of CurrentControlMode value to string. var currentControlModeToString = map[CurrentControlMode]string{ NotProvisioned: "NotProvisioned", Client: "Client", Admin: "Admin", } -// String returns a human-readable string representation of the CurrentControlMode enumeration +// String returns a human-readable string representation of the CurrentControlMode enumeration. func (c CurrentControlMode) String() string { if s, ok := currentControlModeToString[c]; ok { return s } - return "Value not found in map" + + return ValueNotFound } const ( @@ -82,19 +86,20 @@ const ( CertChainStatusChainComplete ) -// certChainStatusToString is a map of CertChainStatus value to string +// certChainStatusToString is a map of CertChainStatus value to string. var certChainStatusToString = map[CertChainStatus]string{ CertChainStatusNotStarted: "NotStarted", CertChainStatusChainInProgress: "ChainInProgress", CertChainStatusChainComplete: "ChainComplete", } -// String returns a human-readable string representation of the CertChainStatus enumeration +// String returns a human-readable string representation of the CertChainStatus enumeration. func (c CertChainStatus) String() string { if s, ok := certChainStatusToString[c]; ok { return s } - return "Value not found in map" + + return ValueNotFound } const ( @@ -103,19 +108,20 @@ const ( AllowedControlModesAdmin ) -// allowedControlModesToString is a map of AllowedControlModes value to string +// allowedControlModesToString is a map of AllowedControlModes value to string. var allowedControlModesToString = map[AllowedControlModes]string{ AllowedControlModesNotProvisioned: "NotProvisioned", AllowedControlModesClient: "Client", AllowedControlModesAdmin: "Admin", } -// String returns a human-readable string representation of the AllowedControlModes enumeration +// String returns a human-readable string representation of the AllowedControlModes enumeration. func (a AllowedControlModes) String() string { if s, ok := allowedControlModesToString[a]; ok { return s } - return "Value not found in map" + + return ValueNotFound } const ( @@ -128,7 +134,7 @@ const ( SetupReturnValueFlashWriteLimitExceeded ) -// setupReturnValueToString is a map of ReturnValue value to string +// setupReturnValueToString is a map of ReturnValue value to string. var setupReturnValueToString = map[SetupReturnValue]string{ SetupReturnValueSuccess: "Success", SetupReturnValueInternalError: "InternalError", @@ -139,12 +145,13 @@ var setupReturnValueToString = map[SetupReturnValue]string{ SetupReturnValueFlashWriteLimitExceeded: "FlashWriteLimitExceeded", } -// String returns a human-readable string representation of the ReturnValue enumeration +// String returns a human-readable string representation of the ReturnValue enumeration. func (s SetupReturnValue) String() string { if s, ok := setupReturnValueToString[s]; ok { return s } - return "Value not found in map" + + return ValueNotFound } const ( @@ -156,7 +163,7 @@ const ( AddNextCertInChainReturnValueCertChainLengthExceeded ) -// addNextCertInChainReturnValueToString is a map of ReturnValue value to string +// addNextCertInChainReturnValueToString is a map of ReturnValue value to string. var addNextCertInChainReturnValueToString = map[AddNextCertInChainReturnValue]string{ AddNextCertInChainReturnValueSuccess: "Success", AddNextCertInChainReturnValueInvalidParam: "InvalidParam", @@ -166,12 +173,13 @@ var addNextCertInChainReturnValueToString = map[AddNextCertInChainReturnValue]st AddNextCertInChainReturnValueCertChainLengthExceeded: "CertChainLengthExceeded", } -// String returns a human-readable string representation of the ReturnValue enumeration +// String returns a human-readable string representation of the ReturnValue enumeration. func (a AddNextCertInChainReturnValue) String() string { if s, ok := addNextCertInChainReturnValueToString[a]; ok { return s } - return "Value not found in map" + + return ValueNotFound } const ( @@ -184,7 +192,7 @@ const ( AdminSetupReturnValueFlashWriteLimitExceeded ) -// adminSetupReturnValueToString is a map of ReturnValue value to string +// adminSetupReturnValueToString is a map of ReturnValue value to string. var adminSetupReturnValueToString = map[AdminSetupReturnValue]string{ AdminSetupReturnValueSuccess: "Success", AdminSetupReturnValueInternalError: "InternalError", @@ -194,10 +202,11 @@ var adminSetupReturnValueToString = map[AdminSetupReturnValue]string{ AdminSetupReturnValueFlashWriteLimitExceeded: "FlashWriteLimitExceeded", } -// String returns a human-readable string representation of the ReturnValue enumeration +// String returns a human-readable string representation of the ReturnValue enumeration. func (a AdminSetupReturnValue) String() string { if s, ok := adminSetupReturnValueToString[a]; ok { return s } - return "Value not found in map" + + return ValueNotFound } diff --git a/pkg/wsman/ips/hostbasedsetup/decoder_test.go b/pkg/wsman/ips/hostbasedsetup/decoder_test.go index a6173c31..a52b2003 100644 --- a/pkg/wsman/ips/hostbasedsetup/decoder_test.go +++ b/pkg/wsman/ips/hostbasedsetup/decoder_test.go @@ -24,6 +24,7 @@ func TestAdminPassEncryptionType_String(t *testing.T) { } } } + func TestSigningAlgorithm_String(t *testing.T) { tests := []struct { state SigningAlgorithm @@ -41,6 +42,7 @@ func TestSigningAlgorithm_String(t *testing.T) { } } } + func TestCurrentControlMode_String(t *testing.T) { tests := []struct { state CurrentControlMode diff --git a/pkg/wsman/ips/hostbasedsetup/marshal.go b/pkg/wsman/ips/hostbasedsetup/marshal.go index 12dee61f..4ce95546 100644 --- a/pkg/wsman/ips/hostbasedsetup/marshal.go +++ b/pkg/wsman/ips/hostbasedsetup/marshal.go @@ -11,20 +11,22 @@ import ( "gopkg.in/yaml.v3" ) -// JSON marshals the type into JSON format +// JSON marshals the type into JSON format. func (r *Response) JSON() string { jsonOutput, err := json.Marshal(r.Body) if err != nil { return "" } + return string(jsonOutput) } -// YAML marshals the type into YAML format +// YAML marshals the type into YAML format. func (r *Response) YAML() string { yamlOutput, err := yaml.Marshal(r.Body) if err != nil { return "" } + return string(yamlOutput) } diff --git a/pkg/wsman/ips/hostbasedsetup/service.go b/pkg/wsman/ips/hostbasedsetup/service.go index 244d51b9..783105cf 100644 --- a/pkg/wsman/ips/hostbasedsetup/service.go +++ b/pkg/wsman/ips/hostbasedsetup/service.go @@ -11,6 +11,7 @@ package hostbasedsetup import ( "crypto/md5" "encoding/xml" + "errors" "fmt" "io" @@ -22,44 +23,50 @@ import ( // NewHostBasedSetupService returns a new instance of the HostBasedSetupService struct. func NewHostBasedSetupServiceWithClient(wsmanMessageCreator *message.WSManMessageCreator, client client.WSMan) Service { return Service{ - base: message.NewBaseWithClient(wsmanMessageCreator, IPS_HostBasedSetupService, client), + base: message.NewBaseWithClient(wsmanMessageCreator, IPSHostBasedSetupService, client), } } -// Get retrieves the representation of the instance +// Get retrieves the representation of the instance. func (service Service) Get() (response Response, err error) { response = Response{ Message: &client.Message{ XMLInput: service.base.Get(nil), }, } + err = service.base.Execute(response.Message) if err != nil { - return + return response, err } + err = xml.Unmarshal([]byte(response.XMLOutput), &response) if err != nil { - return + return response, err } - return + + return response, nil } -// Enumerate returns an enumeration context which is used in a subsequent Pull call +// Enumerate returns an enumeration context which is used in a subsequent Pull call. func (service Service) Enumerate() (response Response, err error) { response = Response{ Message: &client.Message{ XMLInput: service.base.Enumerate(), }, } + err = service.base.Execute(response.Message) if err != nil { - return + return response, err } + err = xml.Unmarshal([]byte(response.XMLOutput), &response) if err != nil { - return + return response, err } - return + + return response, nil } // Pull returns the instances of this class. An enumeration context provided by the Enumerate call is used as input. @@ -69,21 +76,24 @@ func (service Service) Pull(enumerationContext string) (response Response, err e XMLInput: service.base.Pull(enumerationContext), }, } + err = service.base.Execute(response.Message) if err != nil { - return + return response, err } + err = xml.Unmarshal([]byte(response.XMLOutput), &response) if err != nil { - return + return response, err } - return + + return response, nil } // Add a certificate to the provisioning certificate chain, to be used by AdminSetup or UpgradeClientToAdmin methods. -func (service Service) AddNextCertInChain(cert string, isLeaf bool, isRoot bool) (response Response, err error) { - header := service.base.WSManMessageCreator.CreateHeader(methods.GenerateAction(IPS_HostBasedSetupService, AddNextCertInChain), IPS_HostBasedSetupService, nil, "", "") - body := service.base.WSManMessageCreator.CreateBody(methods.GenerateInputMethod(AddNextCertInChain), IPS_HostBasedSetupService, AddNextCertInChain_INPUT{ +func (service Service) AddNextCertInChain(cert string, isLeaf, isRoot bool) (response Response, err error) { + header := service.base.WSManMessageCreator.CreateHeader(methods.GenerateAction(IPSHostBasedSetupService, AddNextCertInChain), IPSHostBasedSetupService, nil, "", "") + body := service.base.WSManMessageCreator.CreateBody(methods.GenerateInputMethod(AddNextCertInChain), IPSHostBasedSetupService, AddNextCertInChainInput{ H: "http://intel.com/wbem/wscim/1/ips-schema/1/IPS_HostBasedSetupService", NextCertificate: cert, IsLeafCertificate: isLeaf, @@ -94,28 +104,32 @@ func (service Service) AddNextCertInChain(cert string, isLeaf bool, isRoot bool) XMLInput: service.base.WSManMessageCreator.CreateXML(header, body), }, } + err = service.base.Execute(response.Message) if err != nil { - return + return response, err } + err = xml.Unmarshal([]byte(response.XMLOutput), &response) if err != nil { - return + return response, err } - if response.Body.AdminSetup_OUTPUT.ReturnValue != 0 { - err = fmt.Errorf("AddNextCertInChain returned %d", response.Body.AdminSetup_OUTPUT.ReturnValue) + + if response.Body.AddNextCertInChain_OUTPUT.ReturnValue != 0 { + err = generateErrorMessage("addnextcertinchain", response.Body.AdminSetup_OUTPUT.ReturnValue) } - return + + return response, err } // Setup Intel® AMT from the local host, resulting in Admin Setup Mode. Requires OS administrator rights, and moves Intel® AMT from "Pre Provisioned" state to "Post Provisioned" state. The control mode after this method is run will be "Admin". -func (service Service) AdminSetup(adminPassEncryptionType AdminPassEncryptionType, digestRealm string, adminPassword string, mcNonce string, signingAlgorithm SigningAlgorithm, digitalSignature string) (response Response, err error) { +func (service Service) AdminSetup(adminPassEncryptionType AdminPassEncryptionType, digestRealm, adminPassword, mcNonce string, signingAlgorithm SigningAlgorithm, digitalSignature string) (response Response, err error) { hashInHex := createMD5Hash(adminPassword, digestRealm) - header := service.base.WSManMessageCreator.CreateHeader(methods.GenerateAction(IPS_HostBasedSetupService, AdminSetup), IPS_HostBasedSetupService, nil, "", "") - body := service.base.WSManMessageCreator.CreateBody(methods.GenerateInputMethod(AdminSetup), IPS_HostBasedSetupService, AdminSetup_INPUT{ + header := service.base.WSManMessageCreator.CreateHeader(methods.GenerateAction(IPSHostBasedSetupService, AdminSetup), IPSHostBasedSetupService, nil, "", "") + body := service.base.WSManMessageCreator.CreateBody(methods.GenerateInputMethod(AdminSetup), IPSHostBasedSetupService, AdminSetupInput{ H: "http://intel.com/wbem/wscim/1/ips-schema/1/IPS_HostBasedSetupService", NetAdminPassEncryptionType: int(adminPassEncryptionType), - NetworkAdminPassword: string(hashInHex), + NetworkAdminPassword: hashInHex, McNonce: mcNonce, SigningAlgorithm: int(signingAlgorithm), DigitalSignature: digitalSignature, @@ -125,61 +139,74 @@ func (service Service) AdminSetup(adminPassEncryptionType AdminPassEncryptionTyp XMLInput: service.base.WSManMessageCreator.CreateXML(header, body), }, } + err = service.base.Execute(response.Message) if err != nil { - return + return response, err } + err = xml.Unmarshal([]byte(response.XMLOutput), &response) if err != nil { - return + return response, err } + if response.Body.AdminSetup_OUTPUT.ReturnValue != 0 { - err = fmt.Errorf("AdminSetup returned %d", response.Body.AdminSetup_OUTPUT.ReturnValue) + err = generateErrorMessage("adminsetup", response.Body.AdminSetup_OUTPUT.ReturnValue) } - return + + return response, err } func (service Service) Setup(adminPassEncryptionType AdminPassEncryptionType, digestRealm, adminPassword string) (response Response, err error) { hashInHex := createMD5Hash(adminPassword, digestRealm) - header := service.base.WSManMessageCreator.CreateHeader(methods.GenerateAction(IPS_HostBasedSetupService, Setup), IPS_HostBasedSetupService, nil, "", "") - body := service.base.WSManMessageCreator.CreateBody(methods.GenerateInputMethod(Setup), IPS_HostBasedSetupService, Setup_INPUT{ + header := service.base.WSManMessageCreator.CreateHeader(methods.GenerateAction(IPSHostBasedSetupService, Setup), IPSHostBasedSetupService, nil, "", "") + body := service.base.WSManMessageCreator.CreateBody(methods.GenerateInputMethod(Setup), IPSHostBasedSetupService, SetupInput{ H: "http://intel.com/wbem/wscim/1/ips-schema/1/IPS_HostBasedSetupService", NetAdminPassEncryptionType: int(adminPassEncryptionType), - NetworkAdminPassword: string(hashInHex), + NetworkAdminPassword: hashInHex, }) response = Response{ Message: &client.Message{ XMLInput: service.base.WSManMessageCreator.CreateXML(header, body), }, } + err = service.base.Execute(response.Message) if err != nil { - return + return response, err } + err = xml.Unmarshal([]byte(response.XMLOutput), &response) if err != nil { - return + return response, err } + if response.Body.Setup_OUTPUT.ReturnValue != 0 { - //, errors.New("unable to activate CCM, check to make sure the device is not alreacy activated") - err = fmt.Errorf("Setup returned %d", response.Body.Setup_OUTPUT.ReturnValue) + err = generateErrorMessage("setup", response.Body.Setup_OUTPUT.ReturnValue) } - return + + return response, err } -func createMD5Hash(adminPassword string, digestRealm string) string { +func createMD5Hash(adminPassword, digestRealm string) string { // Create an md5 hash. setupPassword := "admin:" + digestRealm + ":" + adminPassword hash := md5.New() - _, _ = io.WriteString(hash, setupPassword) + + _, err := io.WriteString(hash, setupPassword) + if err != nil { + return "" + } + hashInHex := fmt.Sprintf("%x", hash.Sum(nil)) + return hashInHex } // Upgrade Intel® AMT from Client to Admin Control Mode. func (service Service) UpgradeClientToAdmin(mcNonce string, signingAlgorithm SigningAlgorithm, digitalSignature string) (response Response, err error) { - header := service.base.WSManMessageCreator.CreateHeader(methods.GenerateAction(IPS_HostBasedSetupService, UpgradeClientToAdmin), IPS_HostBasedSetupService, nil, "", "") - body := service.base.WSManMessageCreator.CreateBody(methods.GenerateInputMethod(UpgradeClientToAdmin), IPS_HostBasedSetupService, UpgradeClientToAdmin_INPUT{ + header := service.base.WSManMessageCreator.CreateHeader(methods.GenerateAction(IPSHostBasedSetupService, UpgradeClientToAdmin), IPSHostBasedSetupService, nil, "", "") + body := service.base.WSManMessageCreator.CreateBody(methods.GenerateInputMethod(UpgradeClientToAdmin), IPSHostBasedSetupService, UpgradeClientToAdminInput{ H: "http://intel.com/wbem/wscim/1/ips-schema/1/IPS_HostBasedSetupService", McNonce: mcNonce, SigningAlgorithm: int(signingAlgorithm), @@ -190,13 +217,23 @@ func (service Service) UpgradeClientToAdmin(mcNonce string, signingAlgorithm Sig XMLInput: service.base.WSManMessageCreator.CreateXML(header, body), }, } + err = service.base.Execute(response.Message) if err != nil { - return + return response, err } + err = xml.Unmarshal([]byte(response.XMLOutput), &response) if err != nil { - return + return response, err } - return + + return response, nil +} + +// generateErrorMessage returns an error message based on the return value. +func generateErrorMessage(call string, returnValue SetupReturnValue) error { + ErrSetupFailed := errors.New(call + " failed") + + return fmt.Errorf("%w: returned %d", ErrSetupFailed, returnValue) } diff --git a/pkg/wsman/ips/hostbasedsetup/service_test.go b/pkg/wsman/ips/hostbasedsetup/service_test.go index 83ef923b..c3fa9705 100644 --- a/pkg/wsman/ips/hostbasedsetup/service_test.go +++ b/pkg/wsman/ips/hostbasedsetup/service_test.go @@ -10,11 +10,10 @@ import ( "fmt" "testing" - "github.com/stretchr/testify/assert" - "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/internal/message" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/common" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/wsmantesting" + "github.com/stretchr/testify/assert" ) func TestJson(t *testing.T) { @@ -23,7 +22,7 @@ func TestJson(t *testing.T) { PullResponse: PullResponse{}, }, } - expectedResult := "{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"GetResponse\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"ElementName\":\"\",\"SystemCreationClassName\":\"\",\"SystemName\":\"\",\"CreationClassName\":\"\",\"Name\":\"\",\"CurrentControlMode\":0,\"AllowedControlModes\":null,\"ConfigurationNonce\":\"\",\"CertChainStatus\":0},\"EnumerateResponse\":{\"EnumerationContext\":\"\"},\"PullResponse\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"HostBasedSetupServiceItems\":null},\"Setup_OUTPUT\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"ReturnValue\":0},\"AdminSetup_OUTPUT\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"ReturnValue\":0},\"AddNextCertInChain_OUTPUT\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"ReturnValue\":0},\"UpgradeClientToAdmin_OUTPUT\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"ReturnValue\":0}}" + expectedResult := "{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"GetResponse\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"ElementName\":\"\",\"SystemCreationClassName\":\"\",\"SystemName\":\"\",\"CreationClassName\":\"\",\"Name\":\"\",\"CurrentControlMode\":0,\"AllowedControlModes\":null,\"ConfigurationNonce\":\"\",\"CertChainStatus\":0},\"EnumerateResponse\":{\"EnumerationContext\":\"\"},\"PullResponse\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"HostBasedSetupServiceItems\":null},\"SetupOutput\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"ReturnValue\":0},\"AdminSetupOutput\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"ReturnValue\":0},\"AddNextCertInChainOutput\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"ReturnValue\":0},\"UpgradeClientToAdminOutput\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"ReturnValue\":0}}" result := response.JSON() assert.Equal(t, expectedResult, result) } @@ -34,15 +33,15 @@ func TestYaml(t *testing.T) { PullResponse: PullResponse{}, }, } - expectedResult := "xmlname:\n space: \"\"\n local: \"\"\ngetresponse:\n xmlname:\n space: \"\"\n local: \"\"\n elementname: \"\"\n systemcreationclassname: \"\"\n systemname: \"\"\n creationclassname: \"\"\n name: \"\"\n currentcontrolmode: 0\n allowedcontrolmodes: []\n configurationnonce: \"\"\n certchainstatus: 0\nenumerateresponse:\n enumerationcontext: \"\"\npullresponse:\n xmlname:\n space: \"\"\n local: \"\"\n hostbasedsetupserviceitems: []\nsetup_output:\n xmlname:\n space: \"\"\n local: \"\"\n returnvalue: 0\nadminsetup_output:\n xmlname:\n space: \"\"\n local: \"\"\n returnvalue: 0\naddnextcertinchain_output:\n xmlname:\n space: \"\"\n local: \"\"\n returnvalue: 0\nupgradeclienttoadmin_output:\n xmlname:\n space: \"\"\n local: \"\"\n returnvalue: 0\n" + expectedResult := "xmlname:\n space: \"\"\n local: \"\"\ngetresponse:\n xmlname:\n space: \"\"\n local: \"\"\n elementname: \"\"\n systemcreationclassname: \"\"\n systemname: \"\"\n creationclassname: \"\"\n name: \"\"\n currentcontrolmode: 0\n allowedcontrolmodes: []\n configurationnonce: \"\"\n certchainstatus: 0\nenumerateresponse:\n enumerationcontext: \"\"\npullresponse:\n xmlname:\n space: \"\"\n local: \"\"\n hostbasedsetupserviceitems: []\nsetupoutput:\n xmlname:\n space: \"\"\n local: \"\"\n returnvalue: 0\nadminsetupoutput:\n xmlname:\n space: \"\"\n local: \"\"\n returnvalue: 0\naddnextcertinchainoutput:\n xmlname:\n space: \"\"\n local: \"\"\n returnvalue: 0\nupgradeclienttoadminoutput:\n xmlname:\n space: \"\"\n local: \"\"\n returnvalue: 0\n" result := response.YAML() assert.Equal(t, expectedResult, result) } func TestPositiveIPS_HostBasedSetupService(t *testing.T) { messageID := 0 - resourceUriBase := "http://intel.com/wbem/wscim/1/ips-schema/1/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.IPSResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "ips/hostbasedsetup", } @@ -58,25 +57,26 @@ func TestPositiveIPS_HostBasedSetupService(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //GETS + // GETS { "should create a valid IPS_HostBasedSetupService Get wsman message", - IPS_HostBasedSetupService, - wsmantesting.GET, + IPSHostBasedSetupService, + wsmantesting.Get, "", "", func() (Response, error) { - client.CurrentMessage = "Get" + client.CurrentMessage = wsmantesting.CurrentMessageGet + return elementUnderTest.Get() }, Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, GetResponse: HostBasedSetupService{ - XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.IPSSchema, IPS_HostBasedSetupService), Local: IPS_HostBasedSetupService}, + XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.IPSSchema, IPSHostBasedSetupService), Local: IPSHostBasedSetupService}, AllowedControlModes: []AllowedControlModes{AllowedControlModesAdmin, AllowedControlModesClient}, CertChainStatus: CertChainStatusNotStarted, ConfigurationNonce: "4P3sY7swlhjkhJNxDkEBIUcmpHE=", - CreationClassName: IPS_HostBasedSetupService, + CreationClassName: IPSHostBasedSetupService, CurrentControlMode: Admin, ElementName: "Intel(r) AMT Host Based Setup Service", Name: "Intel(r) AMT Host Based Setup Service", @@ -85,15 +85,16 @@ func TestPositiveIPS_HostBasedSetupService(t *testing.T) { }, }, }, - //ENUMERATES + // ENUMERATES { "should create a valid IPS_HostBasedSetupService Enumerate wsman message", - IPS_HostBasedSetupService, - wsmantesting.ENUMERATE, - wsmantesting.ENUMERATE_BODY, + IPSHostBasedSetupService, + wsmantesting.Enumerate, + wsmantesting.EnumerateBody, "", func() (Response, error) { - client.CurrentMessage = "Enumerate" + client.CurrentMessage = wsmantesting.CurrentMessageEnumerate + return elementUnderTest.Enumerate() }, Body{ @@ -103,15 +104,16 @@ func TestPositiveIPS_HostBasedSetupService(t *testing.T) { }, }, }, - //PULLS + // PULLS { "should create a valid IPS_HostBasedSetupService Pull wsman message", - IPS_HostBasedSetupService, - wsmantesting.PULL, - wsmantesting.PULL_BODY, + IPSHostBasedSetupService, + wsmantesting.Pull, + wsmantesting.PullBody, "", func() (Response, error) { - client.CurrentMessage = "Pull" + client.CurrentMessage = wsmantesting.CurrentMessagePull + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -120,11 +122,11 @@ func TestPositiveIPS_HostBasedSetupService(t *testing.T) { XMLName: xml.Name{Space: message.XMLPullResponseSpace, Local: "PullResponse"}, HostBasedSetupServiceItems: []HostBasedSetupService{ { - XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.IPSSchema, IPS_HostBasedSetupService), Local: IPS_HostBasedSetupService}, + XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.IPSSchema, IPSHostBasedSetupService), Local: IPSHostBasedSetupService}, AllowedControlModes: []AllowedControlModes{AllowedControlModesAdmin, AllowedControlModesClient}, CertChainStatus: CertChainStatusNotStarted, ConfigurationNonce: "4P3sY7swlhjkhJNxDkEBIUcmpHE=", - CreationClassName: IPS_HostBasedSetupService, + CreationClassName: IPSHostBasedSetupService, CurrentControlMode: Admin, ElementName: "Intel(r) AMT Host Based Setup Service", Name: "Intel(r) AMT Host Based Setup Service", @@ -140,17 +142,18 @@ func TestPositiveIPS_HostBasedSetupService(t *testing.T) { { "should create a valid IPS_HostBasedSetupService AddNextCertInChain wsman message", "IPS_HostBasedSetupService", - wsmantesting.ADD_NEXT_CERT_IN_CHAIN, + wsmantesting.AddNextCertInChain, fmt.Sprintf(`%struefalse`, wsmantesting.ClientCertificate), "", func() (Response, error) { client.CurrentMessage = "AddNextCertInChain" + return elementUnderTest.AddNextCertInChain(wsmantesting.ClientCertificate, true, false) }, Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, AddNextCertInChain_OUTPUT: AddNextCertInChain_OUTPUT{ - XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.IPSSchema, IPS_HostBasedSetupService), Local: "AddNextCertInChain_OUTPUT"}, + XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.IPSSchema, IPSHostBasedSetupService), Local: "AddNextCertInChain_OUTPUT"}, ReturnValue: 0, }, }, @@ -160,17 +163,18 @@ func TestPositiveIPS_HostBasedSetupService(t *testing.T) { { "should create a valid IPS_HostBasedSetupService AdminSetup wsman message", "IPS_HostBasedSetupService", - wsmantesting.ADMIN_SETUP, + wsmantesting.AdminSetup, fmt.Sprintf(`%d%s%s%d%s`, wsmantesting.AdminPassEncryptionType, "f73b2c17b1ecbd7a235ec37d66cbed71", wsmantesting.MCNonce, wsmantesting.SigningAlgorithm, wsmantesting.DigitalSignature), "", func() (Response, error) { client.CurrentMessage = "AdminSetup" + return elementUnderTest.AdminSetup(wsmantesting.AdminPassEncryptionType, wsmantesting.DigestRealm, wsmantesting.AdminPassword, wsmantesting.MCNonce, wsmantesting.SigningAlgorithm, wsmantesting.DigitalSignature) }, Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, AdminSetup_OUTPUT: AdminSetup_OUTPUT{ - XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.IPSSchema, IPS_HostBasedSetupService), Local: "AdminSetup_OUTPUT"}, + XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.IPSSchema, IPSHostBasedSetupService), Local: "AdminSetup_OUTPUT"}, ReturnValue: 0, }, }, @@ -180,37 +184,39 @@ func TestPositiveIPS_HostBasedSetupService(t *testing.T) { { "should create a valid IPS_HostBasedSetupService UpgradeToAdminSetup wsman message", "IPS_HostBasedSetupService", - wsmantesting.UPGRADE_CLIENT_TO_ADMIN, + wsmantesting.UpgradeClientToAdmin, fmt.Sprintf(`%s%d%s`, wsmantesting.MCNonce, wsmantesting.SigningAlgorithm, wsmantesting.DigitalSignature), "", func() (Response, error) { client.CurrentMessage = "UpgradeClientToAdmin" + return elementUnderTest.UpgradeClientToAdmin(wsmantesting.MCNonce, wsmantesting.SigningAlgorithm, wsmantesting.DigitalSignature) }, Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, UpgradeClientToAdmin_OUTPUT: UpgradeClientToAdmin_OUTPUT{ - XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.IPSSchema, IPS_HostBasedSetupService), Local: "UpgradeClientToAdmin_OUTPUT"}, + XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.IPSSchema, IPSHostBasedSetupService), Local: "UpgradeClientToAdmin_OUTPUT"}, ReturnValue: 0, }, }, }, - //Setup + // Setup { "should create a valid IPS_HostBasedSetupService Setup wsman message", "IPS_HostBasedSetupService", - wsmantesting.SETUP, + wsmantesting.Setup, fmt.Sprintf(`%d%s`, wsmantesting.AdminPassEncryptionType, "f73b2c17b1ecbd7a235ec37d66cbed71"), "", func() (Response, error) { client.CurrentMessage = "Setup" + return elementUnderTest.Setup(wsmantesting.AdminPassEncryptionType, wsmantesting.DigestRealm, wsmantesting.AdminPassword) }, Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, Setup_OUTPUT: Setup_OUTPUT{ - XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.IPSSchema, IPS_HostBasedSetupService), Local: "Setup_OUTPUT"}, + XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.IPSSchema, IPSHostBasedSetupService), Local: "Setup_OUTPUT"}, ReturnValue: 0, }, }, @@ -219,7 +225,7 @@ func TestPositiveIPS_HostBasedSetupService(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, "", test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, "", test.body) messageID++ response, err := test.responseFunc() assert.NoError(t, err) @@ -229,10 +235,11 @@ func TestPositiveIPS_HostBasedSetupService(t *testing.T) { } }) } + func TestNegativeIPS_HostBasedSetupService(t *testing.T) { messageID := 0 - resourceUriBase := "http://intel.com/wbem/wscim/1/ips-schema/1/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.IPSResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "ips/hostbasedsetup", } @@ -248,25 +255,26 @@ func TestNegativeIPS_HostBasedSetupService(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //GETS + // GETS { "should create a valid IPS_HostBasedSetupService Get wsman message", - IPS_HostBasedSetupService, - wsmantesting.GET, + IPSHostBasedSetupService, + wsmantesting.Get, "", "", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Get() }, Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, GetResponse: HostBasedSetupService{ - XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.IPSSchema, IPS_HostBasedSetupService), Local: IPS_HostBasedSetupService}, + XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.IPSSchema, IPSHostBasedSetupService), Local: IPSHostBasedSetupService}, AllowedControlModes: []AllowedControlModes{AllowedControlModesAdmin, AllowedControlModesClient}, CertChainStatus: CertChainStatusNotStarted, ConfigurationNonce: "4P3sY7swlhjkhJNxDkEBIUcmpHE=", - CreationClassName: IPS_HostBasedSetupService, + CreationClassName: IPSHostBasedSetupService, CurrentControlMode: Admin, ElementName: "Intel(r) AMT Host Based Setup Service", Name: "Intel(r) AMT Host Based Setup Service", @@ -275,15 +283,16 @@ func TestNegativeIPS_HostBasedSetupService(t *testing.T) { }, }, }, - //ENUMERATES + // ENUMERATES { "should create a valid IPS_HostBasedSetupService Enumerate wsman message", - IPS_HostBasedSetupService, - wsmantesting.ENUMERATE, - wsmantesting.ENUMERATE_BODY, + IPSHostBasedSetupService, + wsmantesting.Enumerate, + wsmantesting.EnumerateBody, "", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Enumerate() }, Body{ @@ -293,15 +302,16 @@ func TestNegativeIPS_HostBasedSetupService(t *testing.T) { }, }, }, - //PULLS + // PULLS { "should create a valid IPS_HostBasedSetupService Pull wsman message", - IPS_HostBasedSetupService, - wsmantesting.PULL, - wsmantesting.PULL_BODY, + IPSHostBasedSetupService, + wsmantesting.Pull, + wsmantesting.PullBody, "", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -310,11 +320,11 @@ func TestNegativeIPS_HostBasedSetupService(t *testing.T) { XMLName: xml.Name{Space: message.XMLPullResponseSpace, Local: "PullResponse"}, HostBasedSetupServiceItems: []HostBasedSetupService{ { - XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.IPSSchema, IPS_HostBasedSetupService), Local: IPS_HostBasedSetupService}, + XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.IPSSchema, IPSHostBasedSetupService), Local: IPSHostBasedSetupService}, AllowedControlModes: []AllowedControlModes{AllowedControlModesAdmin, AllowedControlModesClient}, CertChainStatus: CertChainStatusNotStarted, ConfigurationNonce: "4P3sY7swlhjkhJNxDkEBIUcmpHE=", - CreationClassName: IPS_HostBasedSetupService, + CreationClassName: IPSHostBasedSetupService, CurrentControlMode: Admin, ElementName: "Intel(r) AMT Host Based Setup Service", Name: "Intel(r) AMT Host Based Setup Service", @@ -330,17 +340,18 @@ func TestNegativeIPS_HostBasedSetupService(t *testing.T) { { "should create a valid IPS_HostBasedSetupService AddNextCertInChain wsman message", "IPS_HostBasedSetupService", - wsmantesting.ADD_NEXT_CERT_IN_CHAIN, + wsmantesting.AddNextCertInChain, fmt.Sprintf(`%struefalse`, wsmantesting.ClientCertificate), "", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.AddNextCertInChain(wsmantesting.ClientCertificate, true, false) }, Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, AddNextCertInChain_OUTPUT: AddNextCertInChain_OUTPUT{ - XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.IPSSchema, IPS_HostBasedSetupService), Local: "AddNextCertInChain_OUTPUT"}, + XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.IPSSchema, IPSHostBasedSetupService), Local: "AddNextCertInChain_OUTPUT"}, ReturnValue: 0, }, }, @@ -350,17 +361,18 @@ func TestNegativeIPS_HostBasedSetupService(t *testing.T) { { "should create a valid IPS_HostBasedSetupService AdminSetup wsman message", "IPS_HostBasedSetupService", - wsmantesting.ADMIN_SETUP, + wsmantesting.AdminSetup, fmt.Sprintf(`%d%s%s%d%s`, wsmantesting.AdminPassEncryptionType, "f73b2c17b1ecbd7a235ec37d66cbed71", wsmantesting.MCNonce, wsmantesting.SigningAlgorithm, wsmantesting.DigitalSignature), "", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.AdminSetup(wsmantesting.AdminPassEncryptionType, wsmantesting.DigestRealm, wsmantesting.AdminPassword, wsmantesting.MCNonce, wsmantesting.SigningAlgorithm, wsmantesting.DigitalSignature) }, Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, AdminSetup_OUTPUT: AdminSetup_OUTPUT{ - XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.IPSSchema, IPS_HostBasedSetupService), Local: "AdminSetup_OUTPUT"}, + XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.IPSSchema, IPSHostBasedSetupService), Local: "AdminSetup_OUTPUT"}, ReturnValue: 0, }, }, @@ -370,37 +382,39 @@ func TestNegativeIPS_HostBasedSetupService(t *testing.T) { { "should create a valid IPS_HostBasedSetupService UpgradeToAdminSetup wsman message", "IPS_HostBasedSetupService", - wsmantesting.UPGRADE_CLIENT_TO_ADMIN, + wsmantesting.UpgradeClientToAdmin, fmt.Sprintf(`%s%d%s`, wsmantesting.MCNonce, wsmantesting.SigningAlgorithm, wsmantesting.DigitalSignature), "", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.UpgradeClientToAdmin(wsmantesting.MCNonce, wsmantesting.SigningAlgorithm, wsmantesting.DigitalSignature) }, Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, UpgradeClientToAdmin_OUTPUT: UpgradeClientToAdmin_OUTPUT{ - XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.IPSSchema, IPS_HostBasedSetupService), Local: "UpgradeClientToAdmin_OUTPUT"}, + XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.IPSSchema, IPSHostBasedSetupService), Local: "UpgradeClientToAdmin_OUTPUT"}, ReturnValue: 0, }, }, }, - //Setup + // Setup { "should create a valid IPS_HostBasedSetupService Setup wsman message", "IPS_HostBasedSetupService", - wsmantesting.SETUP, + wsmantesting.Setup, fmt.Sprintf(`%d%s`, wsmantesting.AdminPassEncryptionType, "f73b2c17b1ecbd7a235ec37d66cbed71"), "", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Setup(wsmantesting.AdminPassEncryptionType, wsmantesting.DigestRealm, wsmantesting.AdminPassword) }, Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, Setup_OUTPUT: Setup_OUTPUT{ - XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.IPSSchema, IPS_HostBasedSetupService), Local: "Setup_OUTPUT"}, + XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.IPSSchema, IPSHostBasedSetupService), Local: "Setup_OUTPUT"}, ReturnValue: 0, }, }, @@ -409,7 +423,7 @@ func TestNegativeIPS_HostBasedSetupService(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, "", test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, "", test.body) messageID++ response, err := test.responseFunc() assert.Error(t, err) diff --git a/pkg/wsman/ips/hostbasedsetup/types.go b/pkg/wsman/ips/hostbasedsetup/types.go index 801cd273..67d8acc9 100644 --- a/pkg/wsman/ips/hostbasedsetup/types.go +++ b/pkg/wsman/ips/hostbasedsetup/types.go @@ -18,7 +18,7 @@ type Service struct { } // OUTPUT -// Response Types +// Response Types. type ( Response struct { *client.Message @@ -74,16 +74,16 @@ type ( ) // INPUT -// Request Types +// Request Types. type ( - AddNextCertInChain_INPUT struct { + AddNextCertInChainInput struct { XMLName xml.Name `xml:"h:AddNextCertInChain_INPUT"` H string `xml:"xmlns:h,attr"` NextCertificate string `xml:"h:NextCertificate"` IsLeafCertificate bool `xml:"h:IsLeafCertificate"` IsRootCertificate bool `xml:"h:IsRootCertificate"` } - AdminSetup_INPUT struct { + AdminSetupInput struct { XMLName xml.Name `xml:"h:AdminSetup_INPUT"` H string `xml:"xmlns:h,attr"` NetAdminPassEncryptionType int `xml:"h:NetAdminPassEncryptionType"` @@ -92,13 +92,13 @@ type ( SigningAlgorithm int `xml:"h:SigningAlgorithm"` DigitalSignature string `xml:"h:DigitalSignature"` } - Setup_INPUT struct { + SetupInput struct { XMLName xml.Name `xml:"h:Setup_INPUT"` H string `xml:"xmlns:h,attr"` NetAdminPassEncryptionType int `xml:"h:NetAdminPassEncryptionType"` NetworkAdminPassword string `xml:"h:NetworkAdminPassword"` } - UpgradeClientToAdmin_INPUT struct { + UpgradeClientToAdminInput struct { XMLName xml.Name `xml:"h:UpgradeClientToAdmin_INPUT"` H string `xml:"xmlns:h,attr"` McNonce string `xml:"h:McNonce"` @@ -107,26 +107,26 @@ type ( } ) -// AdminPassEncryptionType is the encryption type for the network admin password +// AdminPassEncryptionType is the encryption type for the network admin password. type AdminPassEncryptionType int -// SigningAlgorithm is the algorithm used to sign the setup operation +// SigningAlgorithm is the algorithm used to sign the setup operation. type SigningAlgorithm int -// CurrentControlMode is an enumeration value that indicates the current control mode of the Intel(r) AMT subsystem after provisioning +// CurrentControlMode is an enumeration value that indicates the current control mode of the Intel(r) AMT subsystem after provisioning. type CurrentControlMode int -// CertChainStatus is an enumeration value that indicates the status of "AddNextCertInChain" progress +// CertChainStatus is an enumeration value that indicates the status of "AddNextCertInChain" progress. type CertChainStatus int -// AllowedControlModes is an array of values that indicates the allowed control modes for the Intel(r) AMT subsystem +// AllowedControlModes is an array of values that indicates the allowed control modes for the Intel(r) AMT subsystem. type AllowedControlModes int -// SetupReturnValue is an enumeration value that indicates the status of the operation +// SetupReturnValue is an enumeration value that indicates the status of the operation. type SetupReturnValue int -// AddNextCertInChainReturnValue is an enumeration value that indicates the status of the operation +// AddNextCertInChainReturnValue is an enumeration value that indicates the status of the operation. type AddNextCertInChainReturnValue int -// AdminSetupReturnValue is an enumeration value that indicates the status of the operation +// AdminSetupReturnValue is an enumeration value that indicates the status of the operation. type AdminSetupReturnValue int diff --git a/pkg/wsman/ips/ieee8021x/credentialcontext.go b/pkg/wsman/ips/ieee8021x/credentialcontext.go index a5551038..7ff736d3 100644 --- a/pkg/wsman/ips/ieee8021x/credentialcontext.go +++ b/pkg/wsman/ips/ieee8021x/credentialcontext.go @@ -15,44 +15,50 @@ import ( // NewIEEE8021xCredentialContext returns a new instance of the IPS_8021xCredentialContext struct. func NewIEEE8021xCredentialContextWithClient(wsmanMessageCreator *message.WSManMessageCreator, client client.WSMan) CredentialContext { return CredentialContext{ - base: message.NewBaseWithClient(wsmanMessageCreator, IPS_8021xCredentialContext, client), + base: message.NewBaseWithClient(wsmanMessageCreator, IPS8021xCredentialContext, client), } } -// Get retrieves the representation of the instance +// Get retrieves the representation of the instance. func (credentialContext CredentialContext) Get() (response Response, err error) { response = Response{ Message: &client.Message{ XMLInput: credentialContext.base.Get(nil), }, } + err = credentialContext.base.Execute(response.Message) if err != nil { - return + return response, err } + err = xml.Unmarshal([]byte(response.XMLOutput), &response) if err != nil { - return + return response, err } - return + + return response, nil } -// Enumerate returns an enumeration context which is used in a subsequent Pull call +// Enumerate returns an enumeration context which is used in a subsequent Pull call. func (credentialContext CredentialContext) Enumerate() (response Response, err error) { response = Response{ Message: &client.Message{ XMLInput: credentialContext.base.Enumerate(), }, } + err = credentialContext.base.Execute(response.Message) if err != nil { - return + return response, err } + err = xml.Unmarshal([]byte(response.XMLOutput), &response) if err != nil { - return + return response, err } - return + + return response, nil } // Pull returns the instances of this class. An enumeration context provided by the Enumerate call is used as input. @@ -62,13 +68,16 @@ func (credentialContext CredentialContext) Pull(enumerationContext string) (resp XMLInput: credentialContext.base.Pull(enumerationContext), }, } + err = credentialContext.base.Execute(response.Message) if err != nil { - return + return response, err } + err = xml.Unmarshal([]byte(response.XMLOutput), &response) if err != nil { - return + return response, err } - return + + return response, nil } diff --git a/pkg/wsman/ips/ieee8021x/credentialcontext_test.go b/pkg/wsman/ips/ieee8021x/credentialcontext_test.go index 2d0a02eb..b14637fe 100644 --- a/pkg/wsman/ips/ieee8021x/credentialcontext_test.go +++ b/pkg/wsman/ips/ieee8021x/credentialcontext_test.go @@ -9,11 +9,10 @@ import ( "encoding/xml" "testing" - "github.com/stretchr/testify/assert" - "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/internal/message" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/common" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/wsmantesting" + "github.com/stretchr/testify/assert" ) func TestJson(t *testing.T) { @@ -40,8 +39,8 @@ func TestYaml(t *testing.T) { func TestPositiveIPS_8021xCredentialContext(t *testing.T) { messageID := 0 - resourceUriBase := "http://intel.com/wbem/wscim/1/ips-schema/1/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.IPSResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "ips/ieee8021x/credentialcontext", } @@ -57,7 +56,7 @@ func TestPositiveIPS_8021xCredentialContext(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //GETS + // GETS // { // "should create a valid IPS_8021xCredentialContext Get wsman message", // "IPS_8021xCredentialContext", @@ -65,20 +64,22 @@ func TestPositiveIPS_8021xCredentialContext(t *testing.T) { // "", // "", // func() (Response, error) { - // client.CurrentMessage = "Get" + // client.CurrentMessage = wsmantesting.CurrentMessageGet + // return elementUnderTest.Get() // }, // Body{}, // }, - //ENUMERATES + // ENUMERATES { "should create a valid IPS_8021xCredentialContext Enumerate wsman message", "IPS_8021xCredentialContext", - wsmantesting.ENUMERATE, - wsmantesting.ENUMERATE_BODY, + wsmantesting.Enumerate, + wsmantesting.EnumerateBody, "", func() (Response, error) { - client.CurrentMessage = "Enumerate" + client.CurrentMessage = wsmantesting.CurrentMessageEnumerate + return elementUnderTest.Enumerate() }, Body{ @@ -88,7 +89,7 @@ func TestPositiveIPS_8021xCredentialContext(t *testing.T) { }, }, }, - //PULLS + // PULLS // { // "should create a valid IPS_8021xCredentialContext Pull wsman message", // "IPS_8021xCredentialContext", @@ -96,7 +97,8 @@ func TestPositiveIPS_8021xCredentialContext(t *testing.T) { // wsmantesting.PULL_BODY, // "", // func() (Response, error) { - // client.CurrentMessage = "Pull" + // client.CurrentMessage = wsmantesting.CurrentMessagePull + // return elementUnderTest.Pull(wsmantesting.EnumerationContext) // }, // Body{}, @@ -105,7 +107,7 @@ func TestPositiveIPS_8021xCredentialContext(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, "", test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, "", test.body) messageID++ response, err := test.responseFunc() assert.NoError(t, err) diff --git a/pkg/wsman/ips/ieee8021x/decoder.go b/pkg/wsman/ips/ieee8021x/decoder.go index fa31eff6..d2683492 100644 --- a/pkg/wsman/ips/ieee8021x/decoder.go +++ b/pkg/wsman/ips/ieee8021x/decoder.go @@ -6,9 +6,10 @@ package ieee8021x const ( - IPS_IEEE8021xSettings string = "IPS_IEEE8021xSettings" - IPS_8021xCredentialContext string = "IPS_8021xCredentialContext" - SetCertificates string = "SetCertificates" + IPSIEEE8021xSettings string = "IPS_IEEE8021xSettings" + IPS8021xCredentialContext string = "IPS_8021xCredentialContext" + SetCertificates string = "SetCertificates" + ValueNotFound string = "Value not found in map" ) const ( @@ -17,19 +18,20 @@ const ( EnabledWithoutCertificates Enabled = 6 ) -// enabledToString is a map of Enabled value to string +// enabledToString is a map of Enabled value to string. var enabledToString = map[Enabled]string{ EnabledWithCertificates: "EnabledWithCertificates", Disabled: "Disabled", EnabledWithoutCertificates: "EnabledWithoutCertificates", } -// String returns a human-readable string representation of the Enabled enumeration +// String returns a human-readable string representation of the Enabled enumeration. func (e Enabled) String() string { if s, ok := enabledToString[e]; ok { return s } - return "Value not found in map" + + return ValueNotFound } const ( @@ -51,16 +53,17 @@ const ( ReturnValueInternalError ) -// returnValueToString is a map of ReturnValue value to string +// returnValueToString is a map of ReturnValue value to string. var returnValueToString = map[ReturnValue]string{ ReturnValueSuccess: "Success", ReturnValueInternalError: "InternalError", } -// String returns a human-readable string representation of the ReturnValue enumeration +// String returns a human-readable string representation of the ReturnValue enumeration. func (r ReturnValue) String() string { if s, ok := returnValueToString[r]; ok { return s } - return "Value not found in map" + + return ValueNotFound } diff --git a/pkg/wsman/ips/ieee8021x/marshal.go b/pkg/wsman/ips/ieee8021x/marshal.go index e23c3e2d..0636e0f7 100644 --- a/pkg/wsman/ips/ieee8021x/marshal.go +++ b/pkg/wsman/ips/ieee8021x/marshal.go @@ -11,20 +11,22 @@ import ( "gopkg.in/yaml.v3" ) -// JSON marshals the type into JSON format +// JSON marshals the type into JSON format. func (r *Response) JSON() string { jsonOutput, err := json.Marshal(r.Body) if err != nil { return "" } + return string(jsonOutput) } -// YAML marshals the type into YAML format +// YAML marshals the type into YAML format. func (r *Response) YAML() string { yamlOutput, err := yaml.Marshal(r.Body) if err != nil { return "" } + return string(yamlOutput) } diff --git a/pkg/wsman/ips/ieee8021x/settings.go b/pkg/wsman/ips/ieee8021x/settings.go index f1e9969f..52704108 100644 --- a/pkg/wsman/ips/ieee8021x/settings.go +++ b/pkg/wsman/ips/ieee8021x/settings.go @@ -17,43 +17,49 @@ import ( // NewIEEE8021xSettings returns a new instance of the IEEE8021xSettings struct. func NewIEEE8021xSettingsWithClient(wsmanMessageCreator *message.WSManMessageCreator, client client.WSMan) Settings { return Settings{ - base: message.NewBaseWithClient(wsmanMessageCreator, IPS_IEEE8021xSettings, client), + base: message.NewBaseWithClient(wsmanMessageCreator, IPSIEEE8021xSettings, client), } } -// Get retrieves the representation of the instance +// Get retrieves the representation of the instance. func (settings Settings) Get() (response Response, err error) { response = Response{ Message: &client.Message{ XMLInput: settings.base.Get(nil), }, } + err = settings.base.Execute(response.Message) if err != nil { - return + return response, err } + err = xml.Unmarshal([]byte(response.XMLOutput), &response) if err != nil { - return + return response, err } + return } -// Enumerate returns an enumeration context which is used in a subsequent Pull call +// Enumerate returns an enumeration context which is used in a subsequent Pull call. func (settings Settings) Enumerate() (response Response, err error) { response = Response{ Message: &client.Message{ XMLInput: settings.base.Enumerate(), }, } + err = settings.base.Execute(response.Message) if err != nil { - return + return response, err } + err = xml.Unmarshal([]byte(response.XMLOutput), &response) if err != nil { - return + return response, err } + return } @@ -64,38 +70,44 @@ func (settings Settings) Pull(enumerationContext string) (response Response, err XMLInput: settings.base.Pull(enumerationContext), }, } + err = settings.base.Execute(response.Message) if err != nil { - return + return response, err } + err = xml.Unmarshal([]byte(response.XMLOutput), &response) if err != nil { - return + return response, err } + return } -// Put will change properties of the selected instance +// Put will change properties of the selected instance. func (settings Settings) Put(ieee8021xSettings IEEE8021xSettingsRequest) (response Response, err error) { - ieee8021xSettings.H = fmt.Sprintf("%s%s", message.IPSSchema, IPS_IEEE8021xSettings) + ieee8021xSettings.H = fmt.Sprintf("%s%s", message.IPSSchema, IPSIEEE8021xSettings) response = Response{ Message: &client.Message{ XMLInput: settings.base.Put(ieee8021xSettings, false, nil), }, } + err = settings.base.Execute(response.Message) if err != nil { - return + return response, err } + err = xml.Unmarshal([]byte(response.XMLOutput), &response) if err != nil { - return + return response, err } + return } func (settings Settings) SetCertificates(serverCertificateIssuer, clientCertificate string) (response Response, err error) { - header := settings.base.WSManMessageCreator.CreateHeader(methods.GenerateAction(IPS_IEEE8021xSettings, SetCertificates), IPS_IEEE8021xSettings, nil, "", "") + header := settings.base.WSManMessageCreator.CreateHeader(methods.GenerateAction(IPSIEEE8021xSettings, SetCertificates), IPSIEEE8021xSettings, nil, "", "") serverCert := ServerCertificateIssuer{ Address: "default", ReferenceParameters: ReferenceParameters{ @@ -120,7 +132,7 @@ func (settings Settings) SetCertificates(serverCertificateIssuer, clientCertific }, }, } - body := settings.base.WSManMessageCreator.CreateBody(methods.GenerateInputMethod(SetCertificates), IPS_IEEE8021xSettings, + body := settings.base.WSManMessageCreator.CreateBody(methods.GenerateInputMethod(SetCertificates), IPSIEEE8021xSettings, Certificate{ H: "http://intel.com/wbem/wscim/1/ips-schema/1/IPS_IEEE8021xSettings", ServerCertificateIssuer: serverCert, @@ -132,13 +144,16 @@ func (settings Settings) SetCertificates(serverCertificateIssuer, clientCertific XMLInput: settings.base.WSManMessageCreator.CreateXML(header, body), }, } + err = settings.base.Execute(response.Message) if err != nil { - return + return response, err } + err = xml.Unmarshal([]byte(response.XMLOutput), &response) if err != nil { - return + return response, err } - return + + return response, nil } diff --git a/pkg/wsman/ips/ieee8021x/settings_test.go b/pkg/wsman/ips/ieee8021x/settings_test.go index d78e127c..41144be4 100644 --- a/pkg/wsman/ips/ieee8021x/settings_test.go +++ b/pkg/wsman/ips/ieee8021x/settings_test.go @@ -10,17 +10,16 @@ import ( "fmt" "testing" - "github.com/stretchr/testify/assert" - "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/internal/message" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/common" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/wsmantesting" + "github.com/stretchr/testify/assert" ) func TestPositiveIPS_IEEE8021xSettings(t *testing.T) { messageID := 0 - resourceUriBase := "http://intel.com/wbem/wscim/1/ips-schema/1/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.IPSResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "ips/ieee8021x/settings", } @@ -36,21 +35,22 @@ func TestPositiveIPS_IEEE8021xSettings(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //GETS + // GETS { "should create a valid IPS_IEEE8021xSettings Get wsman message", "IPS_IEEE8021xSettings", - wsmantesting.GET, + wsmantesting.Get, "", "", func() (Response, error) { - client.CurrentMessage = "Get" + client.CurrentMessage = wsmantesting.CurrentMessageGet + return elementUnderTest.Get() }, Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, IEEE8021xSettingsResponse: IEEE8021xSettingsResponse{ - XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.IPSSchema, IPS_IEEE8021xSettings), Local: IPS_IEEE8021xSettings}, + XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.IPSSchema, IPSIEEE8021xSettings), Local: IPSIEEE8021xSettings}, ElementName: "Intel(r) AMT: 8021X Settings", InstanceID: "Intel(r) AMT: 8021X Settings", Enabled: 3, @@ -59,15 +59,16 @@ func TestPositiveIPS_IEEE8021xSettings(t *testing.T) { }, }, }, - //ENUMERATES + // ENUMERATES { "should create a valid IPS_IEEE8021xSettings Enumerate wsman message", "IPS_IEEE8021xSettings", - wsmantesting.ENUMERATE, - wsmantesting.ENUMERATE_BODY, + wsmantesting.Enumerate, + wsmantesting.EnumerateBody, "", func() (Response, error) { - client.CurrentMessage = "Enumerate" + client.CurrentMessage = wsmantesting.CurrentMessageEnumerate + return elementUnderTest.Enumerate() }, Body{ @@ -77,15 +78,16 @@ func TestPositiveIPS_IEEE8021xSettings(t *testing.T) { }, }, }, - //PULLS + // PULLS { "should create a valid IPS_IEEE8021xSettings Pull wsman message", "IPS_IEEE8021xSettings", - wsmantesting.PULL, - wsmantesting.PULL_BODY, + wsmantesting.Pull, + wsmantesting.PullBody, "", func() (Response, error) { - client.CurrentMessage = "Pull" + client.CurrentMessage = wsmantesting.CurrentMessagePull + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -94,7 +96,7 @@ func TestPositiveIPS_IEEE8021xSettings(t *testing.T) { XMLName: xml.Name{Space: message.XMLPullResponseSpace, Local: "PullResponse"}, IEEE8021xSettingsItems: []IEEE8021xSettingsResponse{ { - XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.IPSSchema, IPS_IEEE8021xSettings), Local: IPS_IEEE8021xSettings}, + XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.IPSSchema, IPSIEEE8021xSettings), Local: IPSIEEE8021xSettings}, ElementName: "Intel(r) AMT: 8021X Settings", InstanceID: "Intel(r) AMT: 8021X Settings", Enabled: 3, @@ -109,17 +111,18 @@ func TestPositiveIPS_IEEE8021xSettings(t *testing.T) { { "should create a valid ips_IEEE8021xSettings set certificates wsman message", "IPS_IEEE8021xSettings", - wsmantesting.SET_CERTIFICATES, + wsmantesting.SetCertificates, fmt.Sprintf(`defaulthttp://intel.com/wbem/wscim/1/amt-schema/1/AMT_PublicKeyCertificate%sdefaulthttp://intel.com/wbem/wscim/1/amt-schema/1/AMT_PublicKeyCertificate%s`, wsmantesting.ServerCertificateIssuer, wsmantesting.ClientCertificate), "", func() (Response, error) { client.CurrentMessage = "SetCertificates" + return elementUnderTest.SetCertificates(wsmantesting.ServerCertificateIssuer, wsmantesting.ClientCertificate) }, Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, SetCertificatesResponse: SetCertificates_OUTPUT{ - XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.IPSSchema, IPS_IEEE8021xSettings), Local: "SetCertificates_OUTPUT"}, + XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.IPSSchema, IPSIEEE8021xSettings), Local: "SetCertificates_OUTPUT"}, ReturnValue: 0, }, }, @@ -128,7 +131,7 @@ func TestPositiveIPS_IEEE8021xSettings(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, "", test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, "", test.body) messageID++ response, err := test.responseFunc() assert.NoError(t, err) @@ -138,10 +141,11 @@ func TestPositiveIPS_IEEE8021xSettings(t *testing.T) { } }) } + func TestNegativeIPS_IEEE8021xSettings(t *testing.T) { messageID := 0 - resourceUriBase := "http://intel.com/wbem/wscim/1/ips-schema/1/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.IPSResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "ips/ieee8021x/settings", } @@ -157,21 +161,22 @@ func TestNegativeIPS_IEEE8021xSettings(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //GETS + // GETS { "should create a valid IPS_IEEE8021xSettings Get wsman message", "IPS_IEEE8021xSettings", - wsmantesting.GET, + wsmantesting.Get, "", "", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Get() }, Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, IEEE8021xSettingsResponse: IEEE8021xSettingsResponse{ - XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.IPSSchema, IPS_IEEE8021xSettings), Local: IPS_IEEE8021xSettings}, + XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.IPSSchema, IPSIEEE8021xSettings), Local: IPSIEEE8021xSettings}, ElementName: "Intel(r) AMT: 8021X Settings", InstanceID: "Intel(r) AMT: 8021X Settings", Enabled: 3, @@ -180,15 +185,16 @@ func TestNegativeIPS_IEEE8021xSettings(t *testing.T) { }, }, }, - //ENUMERATES + // ENUMERATES { "should create a valid IPS_IEEE8021xSettings Enumerate wsman message", "IPS_IEEE8021xSettings", - wsmantesting.ENUMERATE, - wsmantesting.ENUMERATE_BODY, + wsmantesting.Enumerate, + wsmantesting.EnumerateBody, "", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Enumerate() }, Body{ @@ -198,15 +204,16 @@ func TestNegativeIPS_IEEE8021xSettings(t *testing.T) { }, }, }, - //PULLS + // PULLS { "should create a valid IPS_IEEE8021xSettings Pull wsman message", "IPS_IEEE8021xSettings", - wsmantesting.PULL, - wsmantesting.PULL_BODY, + wsmantesting.Pull, + wsmantesting.PullBody, "", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -215,7 +222,7 @@ func TestNegativeIPS_IEEE8021xSettings(t *testing.T) { XMLName: xml.Name{Space: message.XMLPullResponseSpace, Local: "PullResponse"}, IEEE8021xSettingsItems: []IEEE8021xSettingsResponse{ { - XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.IPSSchema, IPS_IEEE8021xSettings), Local: IPS_IEEE8021xSettings}, + XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.IPSSchema, IPSIEEE8021xSettings), Local: IPSIEEE8021xSettings}, ElementName: "Intel(r) AMT: 8021X Settings", InstanceID: "Intel(r) AMT: 8021X Settings", Enabled: 3, @@ -230,17 +237,18 @@ func TestNegativeIPS_IEEE8021xSettings(t *testing.T) { { "should create a valid ips_IEEE8021xSettings set certificates wsman message", "IPS_IEEE8021xSettings", - wsmantesting.SET_CERTIFICATES, + wsmantesting.SetCertificates, fmt.Sprintf(`defaulthttp://intel.com/wbem/wscim/1/amt-schema/1/AMT_PublicKeyCertificate%sdefaulthttp://intel.com/wbem/wscim/1/amt-schema/1/AMT_PublicKeyCertificate%s`, wsmantesting.ServerCertificateIssuer, wsmantesting.ClientCertificate), "", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.SetCertificates(wsmantesting.ServerCertificateIssuer, wsmantesting.ClientCertificate) }, Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, SetCertificatesResponse: SetCertificates_OUTPUT{ - XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.IPSSchema, IPS_IEEE8021xSettings), Local: "SetCertificates_OUTPUT"}, + XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.IPSSchema, IPSIEEE8021xSettings), Local: "SetCertificates_OUTPUT"}, ReturnValue: 0, }, }, @@ -249,7 +257,7 @@ func TestNegativeIPS_IEEE8021xSettings(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, "", test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, "", test.body) messageID++ response, err := test.responseFunc() assert.Error(t, err) diff --git a/pkg/wsman/ips/ieee8021x/types.go b/pkg/wsman/ips/ieee8021x/types.go index a17cb352..f35bc0f2 100644 --- a/pkg/wsman/ips/ieee8021x/types.go +++ b/pkg/wsman/ips/ieee8021x/types.go @@ -13,7 +13,7 @@ import ( "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/common" ) -// Package Types +// Package Types. type ( Settings struct { base message.Base @@ -24,7 +24,7 @@ type ( ) // OUTPUT -// Response Types +// Response Types. type ( Response struct { *client.Message @@ -67,7 +67,7 @@ type ( ) // INPUT -// Request Types +// Request Types. type ( IEEE8021xSettingsRequest struct { XMLName xml.Name `xml:"h:IPS_IEEE8021xSettings,omitempty"` diff --git a/pkg/wsman/ips/messages.go b/pkg/wsman/ips/messages.go index 9a0586f7..f67c8494 100644 --- a/pkg/wsman/ips/messages.go +++ b/pkg/wsman/ips/messages.go @@ -6,14 +6,13 @@ package ips import ( - // "reflect" - "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/internal/message" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/client" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/ips/alarmclock" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/ips/hostbasedsetup" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/ips/ieee8021x" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/ips/optin" + "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/wsmantesting" ) type Messages struct { @@ -26,8 +25,8 @@ type Messages struct { } func NewMessages(client client.WSMan) Messages { - resourceUriBase := "http://intel.com/wbem/wscim/1/ips-schema/1/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.IPSResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) m := Messages{ wsmanMessageCreator: wsmanMessageCreator, } @@ -36,5 +35,6 @@ func NewMessages(client client.WSMan) Messages { m.AlarmClockOccurrence = alarmclock.NewAlarmClockOccurrenceWithClient(wsmanMessageCreator, client) m.IEEE8021xCredentialContext = ieee8021x.NewIEEE8021xCredentialContextWithClient(wsmanMessageCreator, client) m.IEEE8021xSettings = ieee8021x.NewIEEE8021xSettingsWithClient(wsmanMessageCreator, client) + return m } diff --git a/pkg/wsman/ips/messages_test.go b/pkg/wsman/ips/messages_test.go index 0a84ba7b..7a46551c 100644 --- a/pkg/wsman/ips/messages_test.go +++ b/pkg/wsman/ips/messages_test.go @@ -23,18 +23,23 @@ func TestNewMessages(t *testing.T) { if m.wsmanMessageCreator == nil { t.Error("wsmanMessageCreator is not initialized") } + if reflect.DeepEqual(m.OptInService, optin.Service{}) { t.Error("AlarmClockService is not initialized") } + if reflect.DeepEqual(m.HostBasedSetupService, hostbasedsetup.Service{}) { t.Error("AuditLog is not initialized") } + if reflect.DeepEqual(m.AlarmClockOccurrence, alarmclock.Occurrence{}) { t.Error("AuthorizationService is not initialized") } + if reflect.DeepEqual(m.IEEE8021xCredentialContext, ieee8021x.CredentialContext{}) { t.Error("BootCapabilities is not initialized") } + if reflect.DeepEqual(m.IEEE8021xSettings, ieee8021x.Settings{}) { t.Error("BootSettingData is not initialized") } diff --git a/pkg/wsman/ips/methods/methods.go b/pkg/wsman/ips/methods/methods.go index b60c8f86..62a83178 100644 --- a/pkg/wsman/ips/methods/methods.go +++ b/pkg/wsman/ips/methods/methods.go @@ -11,7 +11,7 @@ func RequestStateChange(className string) string { return fmt.Sprintf("http://intel.com/wbem/wscim/1/ips-schema/1/%s/RequestStateChange", className) } -func GenerateAction(className string, methodName string) string { +func GenerateAction(className, methodName string) string { return fmt.Sprintf("http://intel.com/wbem/wscim/1/ips-schema/1/%s/%s", className, methodName) } diff --git a/pkg/wsman/ips/methods/methods_test.go b/pkg/wsman/ips/methods/methods_test.go index fa418f7d..d9ddc7d4 100644 --- a/pkg/wsman/ips/methods/methods_test.go +++ b/pkg/wsman/ips/methods/methods_test.go @@ -11,23 +11,28 @@ import ( "github.com/stretchr/testify/assert" ) +const ( + TestMethod string = "TestMethod" + IPSTest string = "IPS_Test" +) + func TestMethods(t *testing.T) { t.Run("GenerateAction Test", func(t *testing.T) { expectedResult := "http://intel.com/wbem/wscim/1/ips-schema/1/IPS_Test/TestMethod" - className := "IPS_Test" - methodName := "TestMethod" + className := IPSTest + methodName := TestMethod result := GenerateAction(className, methodName) assert.Equal(t, expectedResult, result) }) t.Run("GenerateMethod Test", func(t *testing.T) { expectedResult := "TestMethod_INPUT" - methodName := "TestMethod" + methodName := TestMethod result := GenerateInputMethod(methodName) assert.Equal(t, expectedResult, result) }) t.Run("RequestStateChange Test", func(t *testing.T) { expectedResult := "http://intel.com/wbem/wscim/1/ips-schema/1/IPS_Test/RequestStateChange" - className := "IPS_Test" + className := IPSTest result := RequestStateChange(className) assert.Equal(t, expectedResult, result) }) diff --git a/pkg/wsman/ips/optin/decoder.go b/pkg/wsman/ips/optin/decoder.go index 554f592a..7bf6953b 100644 --- a/pkg/wsman/ips/optin/decoder.go +++ b/pkg/wsman/ips/optin/decoder.go @@ -5,7 +5,10 @@ package optin -const IPS_OptInService string = "IPS_OptInService" +const ( + IPSOptInService string = "IPS_OptInService" + ValueNotFound string = "Value not found in map" +) const ( OptInRequiredNone OptInRequired = iota @@ -13,19 +16,20 @@ const ( OptInRequiredAll OptInRequired = 4294967295 ) -// optInRequiredToString is a map of OptInRequired value to string +// optInRequiredToString is a map of OptInRequired value to string. var optInRequiredToString = map[OptInRequired]string{ OptInRequiredNone: "None", OptInRequiredKVM: "KVM", OptInRequiredAll: "All", } -// String returns a human-readable string representation of the OptInRequired enumeration +// String returns a human-readable string representation of the OptInRequired enumeration. func (o OptInRequired) String() string { if s, ok := optInRequiredToString[o]; ok { return s } - return "Value not found in map" + + return ValueNotFound } const ( @@ -36,7 +40,7 @@ const ( InSession ) -// optInStateToString is a map of OptInState value to string +// optInStateToString is a map of OptInState value to string. var optInStateToString = map[OptInState]string{ NotStarted: "NotStarted", Requested: "Requested", @@ -45,12 +49,13 @@ var optInStateToString = map[OptInState]string{ InSession: "InSession", } -// String returns a human-readable string representation of the OptInState enumeration +// String returns a human-readable string representation of the OptInState enumeration. func (o OptInState) String() string { if s, ok := optInStateToString[o]; ok { return s } - return "Value not found in map" + + return ValueNotFound } const ( @@ -58,18 +63,19 @@ const ( CanModifyOptInPolicyTrue CanModifyOptInPolicy = 1 ) -// canModifyOptInPolicyToString is a map of CanModifyOptInPolicy value to string +// canModifyOptInPolicyToString is a map of CanModifyOptInPolicy value to string. var canModifyOptInPolicyToString = map[CanModifyOptInPolicy]string{ CanModifyOptInPolicyFalse: "False", CanModifyOptInPolicyTrue: "True", } -// String returns a human-readable string representation of the CanModifyOptInPolicy enumeration +// String returns a human-readable string representation of the CanModifyOptInPolicy enumeration. func (c CanModifyOptInPolicy) String() string { if s, ok := canModifyOptInPolicyToString[c]; ok { return s } - return "Value not found in map" + + return ValueNotFound } const ( @@ -80,7 +86,7 @@ const ( ReturnValueFailedFFS ) -// returnValueToString is a map of ReturnValue value to string +// returnValueToString is a map of ReturnValue value to string. var returnValueToString = map[ReturnValue]string{ ReturnValueSuccess: "Success", ReturnValueInternalError: "InternalError", @@ -89,10 +95,11 @@ var returnValueToString = map[ReturnValue]string{ ReturnValueFailedFFS: "FailedFFS", } -// String returns a human-readable string representation of the ReturnValue enumeration +// String returns a human-readable string representation of the ReturnValue enumeration. func (r ReturnValue) String() string { if s, ok := returnValueToString[r]; ok { return s } - return "Value not found in map" + + return ValueNotFound } diff --git a/pkg/wsman/ips/optin/marshal.go b/pkg/wsman/ips/optin/marshal.go index 9dfb5656..89ed75f8 100644 --- a/pkg/wsman/ips/optin/marshal.go +++ b/pkg/wsman/ips/optin/marshal.go @@ -11,20 +11,22 @@ import ( "gopkg.in/yaml.v3" ) -// JSON marshals the type into JSON format +// JSON marshals the type into JSON format. func (r *Response) JSON() string { jsonOutput, err := json.Marshal(r.Body) if err != nil { return "" } + return string(jsonOutput) } -// YAML marshals the type into YAML format +// YAML marshals the type into YAML format. func (r *Response) YAML() string { yamlOutput, err := yaml.Marshal(r.Body) if err != nil { return "" } + return string(yamlOutput) } diff --git a/pkg/wsman/ips/optin/service.go b/pkg/wsman/ips/optin/service.go index d1d63404..89a172a5 100644 --- a/pkg/wsman/ips/optin/service.go +++ b/pkg/wsman/ips/optin/service.go @@ -20,7 +20,7 @@ import ( // NewOptInService returns a new instance of the OptInService struct. func NewOptInServiceWithClient(wsmanMessageCreator *message.WSManMessageCreator, client client.WSMan) Service { return Service{ - base: message.NewBaseWithClient(wsmanMessageCreator, IPS_OptInService, client), + base: message.NewBaseWithClient(wsmanMessageCreator, IPSOptInService, client), } } @@ -31,33 +31,39 @@ func (service Service) Get() (response Response, err error) { XMLInput: service.base.Get(nil), }, } + err = service.base.Execute(response.Message) if err != nil { - return + return response, err } + err = xml.Unmarshal([]byte(response.XMLOutput), &response) if err != nil { - return + return response, err } - return + + return response, err } -// Enumerate returns an enumeration context which is used in a subsequent Pull call +// Enumerate returns an enumeration context which is used in a subsequent Pull call. func (service Service) Enumerate() (response Response, err error) { response = Response{ Message: &client.Message{ XMLInput: service.base.Enumerate(), }, } + err = service.base.Execute(response.Message) if err != nil { - return + return response, err } + err = xml.Unmarshal([]byte(response.XMLOutput), &response) if err != nil { - return + return response, err } - return + + return response, err } // Pull returns the instances of this class. An enumeration context provided by the Enumerate call is used as input. @@ -67,21 +73,24 @@ func (service Service) Pull(enumerationContext string) (response Response, err e XMLInput: service.base.Pull(enumerationContext), }, } + err = service.base.Execute(response.Message) if err != nil { - return + return response, err } + err = xml.Unmarshal([]byte(response.XMLOutput), &response) if err != nil { - return + return response, err } - return + + return response, err } // Send the opt-in code to Intel® AMT. func (service Service) SendOptInCode(optInCode int) (response Response, err error) { - header := service.base.WSManMessageCreator.CreateHeader(string(actions.SendOptInCode), string(IPS_OptInService), nil, "", "") - body := service.base.WSManMessageCreator.CreateBody("SendOptInCode_INPUT", string(IPS_OptInService), OptInCode{ + header := service.base.WSManMessageCreator.CreateHeader(string(actions.SendOptInCode), IPSOptInService, nil, "", "") + body := service.base.WSManMessageCreator.CreateBody("SendOptInCode_INPUT", IPSOptInService, OptInCode{ H: "http://intel.com/wbem/wscim/1/ips-schema/1/IPS_OptInService", OptInCode: optInCode, }) @@ -90,72 +99,84 @@ func (service Service) SendOptInCode(optInCode int) (response Response, err erro XMLInput: service.base.WSManMessageCreator.CreateXML(header, body), }, } + err = service.base.Execute(response.Message) if err != nil { - return + return response, err } + err = xml.Unmarshal([]byte(response.XMLOutput), &response) if err != nil { - return + return response, err } - return + + return response, err } // Request an opt-in code. func (service Service) StartOptIn() (response Response, err error) { - header := service.base.WSManMessageCreator.CreateHeader(string(actions.StartOptIn), string(IPS_OptInService), nil, "", "") - body := service.base.WSManMessageCreator.CreateBody("StartOptIn_INPUT", string(IPS_OptInService), nil) + header := service.base.WSManMessageCreator.CreateHeader(string(actions.StartOptIn), IPSOptInService, nil, "", "") + body := service.base.WSManMessageCreator.CreateBody("StartOptIn_INPUT", IPSOptInService, nil) response = Response{ Message: &client.Message{ XMLInput: service.base.WSManMessageCreator.CreateXML(header, body), }, } + err = service.base.Execute(response.Message) if err != nil { - return + return response, err } + err = xml.Unmarshal([]byte(response.XMLOutput), &response) if err != nil { - return + return response, err } - return + + return response, err } // Cancel a previous opt-in code request. func (service Service) CancelOptIn() (response Response, err error) { - header := service.base.WSManMessageCreator.CreateHeader(string(actions.CancelOptIn), string(IPS_OptInService), nil, "", "") - body := service.base.WSManMessageCreator.CreateBody("CancelOptIn_INPUT", string(IPS_OptInService), nil) + header := service.base.WSManMessageCreator.CreateHeader(string(actions.CancelOptIn), IPSOptInService, nil, "", "") + body := service.base.WSManMessageCreator.CreateBody("CancelOptIn_INPUT", IPSOptInService, nil) response = Response{ Message: &client.Message{ XMLInput: service.base.WSManMessageCreator.CreateXML(header, body), }, } + err = service.base.Execute(response.Message) if err != nil { - return + return response, err } + err = xml.Unmarshal([]byte(response.XMLOutput), &response) if err != nil { - return + return response, err } - return + + return response, err } -// Put will change properties of the selected instance +// Put will change properties of the selected instance. func (service Service) Put(request OptInServiceRequest) (response Response, err error) { - request.H = fmt.Sprintf("%s%s", message.IPSSchema, IPS_OptInService) + request.H = fmt.Sprintf("%s%s", message.IPSSchema, IPSOptInService) response = Response{ Message: &client.Message{ XMLInput: service.base.Put(request, false, nil), }, } + err = service.base.Execute(response.Message) if err != nil { - return + return response, err } + err = xml.Unmarshal([]byte(response.XMLOutput), &response) if err != nil { - return + return response, err } - return + + return response, err } diff --git a/pkg/wsman/ips/optin/service_test.go b/pkg/wsman/ips/optin/service_test.go index f7c63e89..8fd53195 100644 --- a/pkg/wsman/ips/optin/service_test.go +++ b/pkg/wsman/ips/optin/service_test.go @@ -10,11 +10,10 @@ import ( "fmt" "testing" - "github.com/stretchr/testify/assert" - "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/internal/message" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/common" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/wsmantesting" + "github.com/stretchr/testify/assert" ) func TestJson(t *testing.T) { @@ -41,8 +40,8 @@ func TestYaml(t *testing.T) { func TestPositiveIPS_OptInService(t *testing.T) { messageID := 0 - resourceUriBase := "http://intel.com/wbem/wscim/1/ips-schema/1/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.IPSResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "ips/optin", } @@ -58,21 +57,22 @@ func TestPositiveIPS_OptInService(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //GETS + // GETS { "should create a valid IPS_OptInService Get wsman message", - IPS_OptInService, - wsmantesting.GET, + IPSOptInService, + wsmantesting.Get, "", "", func() (Response, error) { - client.CurrentMessage = "Get" + client.CurrentMessage = wsmantesting.CurrentMessageGet + return elementUnderTest.Get() }, Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, GetAndPutResponse: OptInServiceResponse{ - XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.IPSSchema, IPS_OptInService), Local: IPS_OptInService}, + XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.IPSSchema, IPSOptInService), Local: IPSOptInService}, CanModifyOptInPolicy: 1, CreationClassName: "IPS_OptInService", ElementName: "Intel(r) AMT OptIn Service", @@ -86,15 +86,16 @@ func TestPositiveIPS_OptInService(t *testing.T) { }, }, }, - //ENUMERATES + // ENUMERATES { "should create a valid IPS_OptInService Enumerate wsman message", - IPS_OptInService, - wsmantesting.ENUMERATE, - wsmantesting.ENUMERATE_BODY, + IPSOptInService, + wsmantesting.Enumerate, + wsmantesting.EnumerateBody, "", func() (Response, error) { - client.CurrentMessage = "Enumerate" + client.CurrentMessage = wsmantesting.CurrentMessageEnumerate + return elementUnderTest.Enumerate() }, Body{ @@ -104,15 +105,16 @@ func TestPositiveIPS_OptInService(t *testing.T) { }, }, }, - //PULLS + // PULLS { "should create a valid IPS_OptInService Pull wsman message", - IPS_OptInService, - wsmantesting.PULL, - wsmantesting.PULL_BODY, + IPSOptInService, + wsmantesting.Pull, + wsmantesting.PullBody, "", func() (Response, error) { - client.CurrentMessage = "Pull" + client.CurrentMessage = wsmantesting.CurrentMessagePull + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -121,7 +123,7 @@ func TestPositiveIPS_OptInService(t *testing.T) { XMLName: xml.Name{Space: message.XMLPullResponseSpace, Local: "PullResponse"}, OptInServiceItems: []OptInServiceResponse{ { - XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.IPSSchema, IPS_OptInService), Local: IPS_OptInService}, + XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.IPSSchema, IPSOptInService), Local: IPSOptInService}, CanModifyOptInPolicy: 1, CreationClassName: "IPS_OptInService", ElementName: "Intel(r) AMT OptIn Service", @@ -140,18 +142,19 @@ func TestPositiveIPS_OptInService(t *testing.T) { // SEND_OPT_IN_CODE { "should create a valid IPS_OptInService send opt in code wsman message", - IPS_OptInService, - wsmantesting.SEND_OPT_IN_CODE, + IPSOptInService, + wsmantesting.SendOptInCode, `1`, "", func() (Response, error) { client.CurrentMessage = "SendOptInCode" + return elementUnderTest.SendOptInCode(1) }, Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, SendOptInCodeResponse: SendOptInCode_OUTPUT{ - XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.IPSSchema, IPS_OptInService), Local: "SendOptInCode_OUTPUT"}, + XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.IPSSchema, IPSOptInService), Local: "SendOptInCode_OUTPUT"}, ReturnValue: 2, }, }, @@ -159,18 +162,19 @@ func TestPositiveIPS_OptInService(t *testing.T) { // START_OPT_IN { "should create a valid IPS_OptInService start opt in code wsman message", - IPS_OptInService, - wsmantesting.START_OPT_IN, + IPSOptInService, + wsmantesting.StartOptIn, ``, "", func() (Response, error) { client.CurrentMessage = "StartOptIn" + return elementUnderTest.StartOptIn() }, Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, StartOptInResponse: StartOptIn_OUTPUT{ - XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.IPSSchema, IPS_OptInService), Local: "StartOptIn_OUTPUT"}, + XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.IPSSchema, IPSOptInService), Local: "StartOptIn_OUTPUT"}, ReturnValue: 2, }, }, @@ -178,18 +182,19 @@ func TestPositiveIPS_OptInService(t *testing.T) { // CANCEL_OPT_IN { "should create a valid IPS_OptInService cancel opt in code wsman message", - IPS_OptInService, - wsmantesting.CANCEL_OPT_IN, + IPSOptInService, + wsmantesting.CancelOptIn, ``, "", func() (Response, error) { client.CurrentMessage = "CancelOptIn" + return elementUnderTest.CancelOptIn() }, Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, CancelOptInResponse: CancelOptIn_OUTPUT{ - XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.IPSSchema, IPS_OptInService), Local: "CancelOptIn_OUTPUT"}, + XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.IPSSchema, IPSOptInService), Local: "CancelOptIn_OUTPUT"}, ReturnValue: 2, }, }, @@ -198,7 +203,7 @@ func TestPositiveIPS_OptInService(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, "", test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, "", test.body) messageID++ response, err := test.responseFunc() assert.NoError(t, err) @@ -208,10 +213,11 @@ func TestPositiveIPS_OptInService(t *testing.T) { } }) } + func TestNegativeIPS_OptInService(t *testing.T) { messageID := 0 - resourceUriBase := "http://intel.com/wbem/wscim/1/ips-schema/1/" - wsmanMessageCreator := message.NewWSManMessageCreator(resourceUriBase) + resourceURIBase := wsmantesting.IPSResourceURIBase + wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "ips/optin", } @@ -227,21 +233,22 @@ func TestNegativeIPS_OptInService(t *testing.T) { responseFunc func() (Response, error) expectedResponse interface{} }{ - //GETS + // GETS { "should create a valid IPS_OptInService Get wsman message", - IPS_OptInService, - wsmantesting.GET, + IPSOptInService, + wsmantesting.Get, "", "", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Get() }, Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, GetAndPutResponse: OptInServiceResponse{ - XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.IPSSchema, IPS_OptInService), Local: IPS_OptInService}, + XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.IPSSchema, IPSOptInService), Local: IPSOptInService}, CanModifyOptInPolicy: 1, CreationClassName: "IPS_OptInService", ElementName: "Intel(r) AMT OptIn Service", @@ -255,15 +262,16 @@ func TestNegativeIPS_OptInService(t *testing.T) { }, }, }, - //ENUMERATES + // ENUMERATES { "should create a valid IPS_OptInService Enumerate wsman message", - IPS_OptInService, - wsmantesting.ENUMERATE, - wsmantesting.ENUMERATE_BODY, + IPSOptInService, + wsmantesting.Enumerate, + wsmantesting.EnumerateBody, "", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Enumerate() }, Body{ @@ -273,15 +281,16 @@ func TestNegativeIPS_OptInService(t *testing.T) { }, }, }, - //PULLS + // PULLS { "should create a valid IPS_OptInService Pull wsman message", - IPS_OptInService, - wsmantesting.PULL, - wsmantesting.PULL_BODY, + IPSOptInService, + wsmantesting.Pull, + wsmantesting.PullBody, "", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ @@ -290,7 +299,7 @@ func TestNegativeIPS_OptInService(t *testing.T) { XMLName: xml.Name{Space: message.XMLPullResponseSpace, Local: "PullResponse"}, OptInServiceItems: []OptInServiceResponse{ { - XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.IPSSchema, IPS_OptInService), Local: IPS_OptInService}, + XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.IPSSchema, IPSOptInService), Local: IPSOptInService}, CanModifyOptInPolicy: 1, CreationClassName: "IPS_OptInService", ElementName: "Intel(r) AMT OptIn Service", @@ -310,18 +319,19 @@ func TestNegativeIPS_OptInService(t *testing.T) { // SEND_OPT_IN_CODE { "should create a valid IPS_OptInService send opt in code wsman message", - IPS_OptInService, - wsmantesting.SEND_OPT_IN_CODE, + IPSOptInService, + wsmantesting.SendOptInCode, `1`, "", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.SendOptInCode(1) }, Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, SendOptInCodeResponse: SendOptInCode_OUTPUT{ - XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.IPSSchema, IPS_OptInService), Local: "SendOptInCode_OUTPUT"}, + XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.IPSSchema, IPSOptInService), Local: "SendOptInCode_OUTPUT"}, ReturnValue: 2, }, }, @@ -330,18 +340,19 @@ func TestNegativeIPS_OptInService(t *testing.T) { // START_OPT_IN { "should create a valid IPS_OptInService start opt in code wsman message", - IPS_OptInService, - wsmantesting.START_OPT_IN, + IPSOptInService, + wsmantesting.StartOptIn, ``, "", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.StartOptIn() }, Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, StartOptInResponse: StartOptIn_OUTPUT{ - XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.IPSSchema, IPS_OptInService), Local: "StartOptIn_OUTPUT"}, + XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.IPSSchema, IPSOptInService), Local: "StartOptIn_OUTPUT"}, ReturnValue: 2, }, }, @@ -350,18 +361,19 @@ func TestNegativeIPS_OptInService(t *testing.T) { // CANCEL_OPT_IN { "should create a valid IPS_OptInService cancel opt in code wsman message", - IPS_OptInService, - wsmantesting.CANCEL_OPT_IN, + IPSOptInService, + wsmantesting.CancelOptIn, ``, "", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError + return elementUnderTest.CancelOptIn() }, Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, CancelOptInResponse: CancelOptIn_OUTPUT{ - XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.IPSSchema, IPS_OptInService), Local: "CancelOptIn_OUTPUT"}, + XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.IPSSchema, IPSOptInService), Local: "CancelOptIn_OUTPUT"}, ReturnValue: 2, }, }, @@ -369,12 +381,12 @@ func TestNegativeIPS_OptInService(t *testing.T) { // PUT { "should create a valid IPS_OptInService Put wsman message", - IPS_OptInService, - wsmantesting.PUT, + IPSOptInService, + wsmantesting.Put, `1IPS_OptInServiceIntel(r) AMT OptIn ServiceIntel(r) AMT OptIn Service12030000Intel(r) AMTCIM_ComputerSystem`, "", func() (Response, error) { - client.CurrentMessage = "Error" + client.CurrentMessage = wsmantesting.CurrentMessageError request := OptInServiceRequest{ H: "http://intel.com/wbem/wscim/1/ips-schema/1//IPS_OptInService", CanModifyOptInPolicy: 1, @@ -388,12 +400,13 @@ func TestNegativeIPS_OptInService(t *testing.T) { SystemCreationClassName: "CIM_ComputerSystem", SystemName: "Intel(r) AMT", } + return elementUnderTest.Put(request) }, Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, GetAndPutResponse: OptInServiceResponse{ - XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.IPSSchema, IPS_OptInService), Local: IPS_OptInService}, + XMLName: xml.Name{Space: fmt.Sprintf("%s%s", message.IPSSchema, IPSOptInService), Local: IPSOptInService}, CanModifyOptInPolicy: 1, CreationClassName: "IPS_OptInService", ElementName: "Intel(r) AMT OptIn Service", @@ -411,7 +424,7 @@ func TestNegativeIPS_OptInService(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceUriBase, test.method, test.action, "", test.body) + expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, "", test.body) messageID++ response, err := test.responseFunc() assert.Error(t, err) diff --git a/pkg/wsman/ips/optin/types.go b/pkg/wsman/ips/optin/types.go index b7e61084..db6bff5f 100644 --- a/pkg/wsman/ips/optin/types.go +++ b/pkg/wsman/ips/optin/types.go @@ -18,7 +18,7 @@ type Service struct { } // OUTPUT -// Response Types +// Response Types. type ( Response struct { *client.Message @@ -38,17 +38,17 @@ type ( } OptInServiceResponse struct { - XMLName xml.Name `xml:"IPS_OptInService"` - Name string `xml:"Name,omitempty"` - CreationClassName string `xml:"CreationClassName,omitempty"` - SystemName string `xml:"SystemName,omitempty"` - SystemCreationClassName string `xml:"SystemCreationClassName,omitempty"` - ElementName string `xml:"ElementName,omitempty"` - OptInCodeTimeout int `xml:"OptInCodeTimeout,omitempty"` - OptInRequired OptInRequired `xml:"OptInRequired"` - OptInState OptInState `xml:"OptInState"` - CanModifyOptInPolicy CanModifyOptInPolicy `xml:"CanModifyOptInPolicy,omitempty"` - OptInDisplayTimeout int `xml:"OptInDisplayTimeout,omitempty"` + XMLName xml.Name `xml:"IPS_OptInService"` + Name string `xml:"Name,omitempty"` + CreationClassName string `xml:"CreationClassName,omitempty"` + SystemName string `xml:"SystemName,omitempty"` + SystemCreationClassName string `xml:"SystemCreationClassName,omitempty"` + ElementName string `xml:"ElementName,omitempty"` + OptInCodeTimeout int `xml:"OptInCodeTimeout,omitempty"` + OptInRequired uint32 `xml:"OptInRequired"` + OptInState int `xml:"OptInState"` + CanModifyOptInPolicy int `xml:"CanModifyOptInPolicy,omitempty"` + OptInDisplayTimeout int `xml:"OptInDisplayTimeout,omitempty"` } PullResponse struct { @@ -81,7 +81,7 @@ type ( ) // INPUT -// Request Types +// Request Types. type ( OptInCode struct { XMLName xml.Name `xml:"h:SendOptInCode_INPUT"` diff --git a/pkg/wsman/messages.go b/pkg/wsman/messages.go index ef5f93a1..6e2c6702 100644 --- a/pkg/wsman/messages.go +++ b/pkg/wsman/messages.go @@ -13,19 +13,23 @@ import ( "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/ips" ) -// NewMessages instantiates a new Messages class with client connection parameters +// NewMessages instantiates a new Messages class with client connection parameters. func NewMessages(cp client.Parameters) Messages { var client1 *client.Target + if cp.IsRedirection { client1 = client.NewWsmanTCP(cp) } else { client1 = client.NewWsman(cp) } + m := Messages{ Client: client1, } + m.AMT = amt.NewMessages(client1) m.CIM = cim.NewMessages(client1) m.IPS = ips.NewMessages(client1) + return m } diff --git a/pkg/wsman/messages_test.go b/pkg/wsman/messages_test.go index 8201e4ab..8378d5fe 100644 --- a/pkg/wsman/messages_test.go +++ b/pkg/wsman/messages_test.go @@ -16,6 +16,8 @@ import ( ) func TestNewMessages(t *testing.T) { + t.Parallel() + clientParams := client.Parameters{ Target: "test", Username: "username", @@ -30,12 +32,15 @@ func TestNewMessages(t *testing.T) { if m.Client == nil { t.Error("client is not initialized") } + if reflect.DeepEqual(m.AMT, amt.Messages{}) { t.Error("AMT is not initialized") } + if reflect.DeepEqual(m.CIM, cim.Messages{}) { t.Error("CIM is not initialized") } + if reflect.DeepEqual(m.IPS, ips.Messages{}) { t.Error("IPS is not initialized") } diff --git a/pkg/wsman/types.go b/pkg/wsman/types.go index 35cd266e..fff5dda9 100644 --- a/pkg/wsman/types.go +++ b/pkg/wsman/types.go @@ -12,7 +12,7 @@ import ( "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/ips" ) -// Messages implements client.WSMan, amt.Messages, cim.Messages, and ips.Messages +// Messages implements client.WSMan, amt.Messages, cim.Messages, and ips.Messages. type Messages struct { Client client.WSMan AMT amt.Messages diff --git a/pkg/wsman/wsmantesting/clientMock.go b/pkg/wsman/wsmantesting/clientMock.go index b86d9425..33a81137 100644 --- a/pkg/wsman/wsmantesting/clientMock.go +++ b/pkg/wsman/wsmantesting/clientMock.go @@ -1,10 +1,11 @@ package wsmantesting import ( - "fmt" "io" "os" "strings" + + "github.com/sirupsen/logrus" ) // MockClient is a mock implementation of the wsman.Client interface for testing. @@ -14,27 +15,29 @@ type MockClient struct { } func (c *MockClient) Post(msg string) ([]byte, error) { - if strings.ToLower(c.CurrentMessage) == "error" { + if strings.EqualFold(c.CurrentMessage, "error") { return []byte(""), nil } // read an xml file from disk: xmlFile, err := os.Open("../../wsmantesting/responses/" + c.PackageUnderTest + "/" + strings.ToLower(c.CurrentMessage) + ".xml") if err != nil { - fmt.Println("Error opening file:", err) + logrus.Print("Error opening file:", err) + return nil, err } defer xmlFile.Close() // read file into string xmlData, err := io.ReadAll(xmlFile) if err != nil { - fmt.Println("Error reading file:", err) + logrus.Print("Error reading file:", err) + return nil, err } // strip carriage returns and new line characters xmlData = []byte(strings.ReplaceAll(string(xmlData), "\r\n", "")) // Simulate a successful response for testing. - return []byte(xmlData), nil + return xmlData, nil } func (c *MockClient) Send(data []byte) error { return nil } func (c *MockClient) Receive() ([]byte, error) { return nil, nil } diff --git a/pkg/wsman/wsmantesting/constants.go b/pkg/wsman/wsmantesting/constants.go index 13b42b22..401776d3 100644 --- a/pkg/wsman/wsmantesting/constants.go +++ b/pkg/wsman/wsmantesting/constants.go @@ -12,14 +12,14 @@ const ( Envelope = `
` EnumerationContext = `AC070000-0000-0000-0000-000000000000` OperationTimeout = `PT60S` - GET = "http://schemas.xmlsoap.org/ws/2004/09/transfer/Get" - ENUMERATE = "http://schemas.xmlsoap.org/ws/2004/09/enumeration/Enumerate" - PULL = "http://schemas.xmlsoap.org/ws/2004/09/enumeration/Pull" - DELETE = "http://schemas.xmlsoap.org/ws/2004/09/transfer/Delete" - PUT = "http://schemas.xmlsoap.org/ws/2004/09/transfer/Put" - CREATE = "http://schemas.xmlsoap.org/ws/2004/09/transfer/Create" - ENUMERATE_BODY = "" - SET_BOOT_CONFIG_ROLE = "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_BootService/SetBootConfigRole" + Get = "http://schemas.xmlsoap.org/ws/2004/09/transfer/Get" + Enumerate = "http://schemas.xmlsoap.org/ws/2004/09/enumeration/Enumerate" + Pull = "http://schemas.xmlsoap.org/ws/2004/09/enumeration/Pull" + Delete = "http://schemas.xmlsoap.org/ws/2004/09/transfer/Delete" + Put = "http://schemas.xmlsoap.org/ws/2004/09/transfer/Put" + Create = "http://schemas.xmlsoap.org/ws/2004/09/transfer/Create" + EnumerateBody = "" + SetBootConfigRole = "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_BootService/SetBootConfigRole" ServerCertificateIssuer = `serverCertificateIssuer` ClientCertificate = `clientCertificate` DigestRealm = "Digest:Realm" @@ -28,19 +28,28 @@ const ( MCNonce = `ZxxE0cFy590zDBIR39q6QU6iuII=` SigningAlgorithm = 2 DigitalSignature = `T0NvoR7RUkOpVULIcNL0VhpEK5rO3j5/TBpN82q1YgPM5sRBxqymu7fKBgAGGN49oD8xsqW4X0SWxjuB3q/TLHjNJJNxoHHlXZnb77HTwfXHp59E/TM10UvOX96qEgKU5Mp+8/IE9LnYxC1ajQostSRA/X+HA5F6kRctLiCK+ViWUCk4sAtPzHhhHSTB/98KDWuacPepScSpref532hpD2/g43nD3Wg0SjmOMExPLMMnijWE9KDkxE00+Bos28DD3Yclj4BMhkoXDw6k4EcTWKbGhtF/9meXXmSPwRmXEaWe8COIDrQks1mpyLblYu8yHHnUjhssdcCQHtAOu7t0RA==` - SET_CERTIFICATES = "http://intel.com/wbem/wscim/1/ips-schema/1/IPS_IEEE8021xSettings/SetCertificates" - ADD_NEXT_CERT_IN_CHAIN = "http://intel.com/wbem/wscim/1/ips-schema/1/IPS_HostBasedSetupService/AddNextCertInChain" - ADMIN_SETUP = "http://intel.com/wbem/wscim/1/ips-schema/1/IPS_HostBasedSetupService/AdminSetup" - UPGRADE_CLIENT_TO_ADMIN = "http://intel.com/wbem/wscim/1/ips-schema/1/IPS_HostBasedSetupService/UpgradeClientToAdmin" - SETUP = "http://intel.com/wbem/wscim/1/ips-schema/1/IPS_HostBasedSetupService/Setup" - SEND_OPT_IN_CODE = "http://intel.com/wbem/wscim/1/ips-schema/1/IPS_OptInService/SendOptInCode" - START_OPT_IN = "http://intel.com/wbem/wscim/1/ips-schema/1/IPS_OptInService/StartOptIn" - CANCEL_OPT_IN = "http://intel.com/wbem/wscim/1/ips-schema/1/IPS_OptInService/CancelOptIn" + SetCertificates = "http://intel.com/wbem/wscim/1/ips-schema/1/IPS_IEEE8021xSettings/SetCertificates" + AddNextCertInChain = "http://intel.com/wbem/wscim/1/ips-schema/1/IPS_HostBasedSetupService/AddNextCertInChain" + AdminSetup = "http://intel.com/wbem/wscim/1/ips-schema/1/IPS_HostBasedSetupService/AdminSetup" + UpgradeClientToAdmin = "http://intel.com/wbem/wscim/1/ips-schema/1/IPS_HostBasedSetupService/UpgradeClientToAdmin" + Setup = "http://intel.com/wbem/wscim/1/ips-schema/1/IPS_HostBasedSetupService/Setup" + SendOptInCode = "http://intel.com/wbem/wscim/1/ips-schema/1/IPS_OptInService/SendOptInCode" + StartOptIn = "http://intel.com/wbem/wscim/1/ips-schema/1/IPS_OptInService/StartOptIn" + CancelOptIn = "http://intel.com/wbem/wscim/1/ips-schema/1/IPS_OptInService/CancelOptIn" TrustedRootCert = "MIIEOzCCAqOgAwIBAgIDAZiFMA0GCSqGSIb3DQEBDAUAMD0xFzAVBgNVBAMTDk1QU1Jvb3QtNjE0ZDg4MRAwDgYDVQQKEwd1bmtub3duMRAwDgYDVQQGEwd1bmtub3duMCAXDTIwMDgyNTE4MzMzN1oYDzIwNTEwODI1MTgzMzM3WjA9MRcwFQYDVQQDEw5NUFNSb290LTYxNGQ4ODEQMA4GA1UEChMHdW5rbm93bjEQMA4GA1UEBhMHdW5rbm93bjCCAaIwDQYJKoZIhvcNAQEBBQADggGPADCCAYoCggGBAOi1jx9L8DG6gBPxd9gmJ6vqQC/F/TBMTJvb3ZAuRbDxUKnxZk3PafyNM6fO8QTL4qZVhvyGEZaIzVePrdJj31aZ93mNY2TJee3/DLRsJUIZHGFufBvi8pgQL+JjE9JmFD5/S2yciHIEVpKmXo1CbGmZGsnb8NRjaQVwB94pI1mg8JFMxyKzU/cUoCBfI+wmeMgBVdOJPNpH2zjC/GxwEFNQaxGe9GHmYbwoeiDeMPo75E/o+Gw6kJm429cuhJBC3KqHevAJj9V2nSUvoO0oxKqzLVkUYcjHEGYjxIvP6a6uo7x9llwfshJsBZ3PE5hucNdWS3dY3GeCqOwcaAQQIj2jULpZ/KlgVAdBK/o5QjE+IIQXCVK9USvktGzz7I5oH98zy8jCFStbGM7PQCo+DEnHn/SANmVbcy3hjzrXC8zf5dvmKiUb2eKnpv+z3FHsi64sVwFqBArB2ipcTM/qv4nEM6uLW1t+7+NB0OyaBmLktJrpb6af7z/EW1QuPIfTcQIDAQABo0IwQDAMBgNVHRMEBTADAQH/MBEGCWCGSAGG+EIBAQQEAwIABzAdBgNVHQ4EFgQUYU2IeTFqWXI1rG+JqZq8eVDO/LMwDQYJKoZIhvcNAQEMBQADggGBANoKIsFOn8/Lrb98DjOP+LUeopoU9KQ70ndreNqchrkPmM61V9IdD9OZiLr/7OY/rLGZwNvkhQYRPUa842Mqjfpr4YcV6HC0j6Zg0lcpxQ5eGGBkLb/teBcboi3sZcJvbCFUW2DJjhy7uqYxzE4eqSsKx5fEjp/wa6oNzNrgWRXyxQlaOo42RjXnOXS7sB0jPrgO0FClL1Xzif06kFHzzyJCVUqzNEJv0ynLgkpzCVdUUfoMM1RcKc3xJes5C0zg64ugj2R9e4VwJfn9W3+rlYS1So1q1jL8w+3qOM7lXyvr8Bdgc5BMvrOvHxzdOnpZmUEJkbKty62e8fYKN+WP7BrpxnzFQSzczX5S0uN4rn0rLO4wxVf2rtnTqIhKKYTsPMRBVEjpbRT1smzPPdINKu5l/Rz/zZS0b5I4yKJrkTYNgoPC/QSq8A9uXZxxQvj6x1bWZJVWywmaqYolEp8NaVHd+JYnlTmr4XpMHm01TPi1laowtY3ZepnKm8I55Ly0JA==" + CIMResourceURIBase = "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/" + AMTResourceURIBase = "http://intel.com/wbem/wscim/1/amt-schema/1/" + IPSResourceURIBase = "http://intel.com/wbem/wscim/1/ips-schema/1/" + CurrentMessageEnumerate = "Enumerate" + CurrentMessagePull = "Pull" + CurrentMessageGet = "Get" + CurrentMessagePut = "Put" + CurrentMessageDelete = "Delete" + CurrentMessageError = "Error" ) -var PULL_BODY = fmt.Sprintf(`%s99999999`, EnumerationContext) +var PullBody = fmt.Sprintf(`%s99999999`, EnumerationContext) -var ExpectedResponse = func(messageID int, resourceUriBase, method, action, extraHeader, body string) string { - return fmt.Sprintf(`%s%s%s/wsman%s%s%dhttp://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous%s%s
%s
`, XMLHeader, Envelope, action, resourceUriBase, method, messageID, OperationTimeout, extraHeader, body) +var ExpectedResponse = func(messageID int, resourceURIBase, method, action, extraHeader, body string) string { + return fmt.Sprintf(`%s%s%s/wsman%s%s%dhttp://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous%s%s%s`, XMLHeader, Envelope, action, resourceURIBase, method, messageID, OperationTimeout, extraHeader, body) }