diff --git a/.circleci/config.yml b/.circleci/config.yml deleted file mode 100644 index 815df77e..00000000 --- a/.circleci/config.yml +++ /dev/null @@ -1,369 +0,0 @@ -version: 2.1 -executors: - my-executor: - machine: - enabled: true - image: ubuntu-2004:202104-01 - working_directory: ~/repo - environment: - shell: /bin/bash - TERM: xterm - TZ: "Europe/Berlin" - deployer: - docker: - - image: oisp/deployer - auth: - username: $DOCKER_USERNAME - password: $DOCKER_PASSWORD - environment: - shell: /bin/bash - TERM: xterm - -commands: -#################################### -# NEW CI OVER SSH STARTS HERE # -#################################### - e2e-over-ssh: - description: "Say hello with ssh" - steps: - - add_ssh_keys: - fingerprints: - - "ba:fc:ed:ea:ba:be:ce:75:a8:cf:11:bb:99:9d:d2:54" - - run: - shell: /bin/bash - name: Clone Repository - command: >- - ssh arkocal@82.165.71.183 "echo Building all on external server && - echo ${CIRCLE_REPOSITORY_URL} && - mkdir /tmp/${CIRCLE_PROJECT_REPONAME}-${CIRCLE_BUILD_NUM} && - cd /tmp/${CIRCLE_PROJECT_REPONAME}-${CIRCLE_BUILD_NUM} && - git clone ${CIRCLE_REPOSITORY_URL} -b ${CIRCLE_BRANCH} && - cd /tmp/${CIRCLE_PROJECT_REPONAME}-${CIRCLE_BUILD_NUM}/${CIRCLE_PROJECT_REPONAME}/ && - git submodule init && - git submodule update && - make update TERM=xterm" - - run: - shell: /bin/bash - name: Wait for queue - command: >- - ssh arkocal@82.165.71.183 "echo \"Waiting for other tests to complete\" && - echo \"Delete /tmp/ci_test.lock manually if you are sure no other tests are running.\" && - while [[ -f /tmp/ci_test.lock ]]; do sleep 5; echo -n \".\"; done && - touch /tmp/ci_test.lock;" - - run: - shell: /bin/bash - name: Cleanup - command: >- - ssh arkocal@82.165.71.183 - "cd /tmp/${CIRCLE_PROJECT_REPONAME}-${CIRCLE_BUILD_NUM}/${CIRCLE_PROJECT_REPONAME}/ && - make restart-cluster" - - run: - shell: /bin/bash - name: Build - command: >- - export TEST_ID=${CIRCLE_PROJECT_REPONAME}-${CIRCLE_BUILD_NUM} && - ssh arkocal@82.165.71.183 - "(cd /tmp/${TEST_ID}/${CIRCLE_PROJECT_REPONAME} && - yes | make build DOCKER_TAG=test_${TEST_ID} DEBUG=true TERM=xterm) || - (rm /tmp/ci_test.lock && exit 1)" - - run: - shell: /bin/bash - name: Test - command: >- - (export TEST_ID=${CIRCLE_PROJECT_REPONAME}-${CIRCLE_BUILD_NUM} && - touch .can_delete_if_success && - ssh arkocal@82.165.71.183 - "cd /tmp/${TEST_ID}/${CIRCLE_PROJECT_REPONAME} && - (export NAMESPACE=${TEST_ID} && echo Namespace is: \${NAMESPACE} && - export NODOCKERLOGIN=true && - export KUBECONFIG=\$(k3d get-kubeconfig) && - sh util/deploy_operators.sh && - make import-images DOCKER_TAG=test_${TEST_ID} DEBUG=true && - (make undeploy-oisp || true) && - make deploy-oisp-test DOCKER_TAG=test_${TEST_ID} USE_LOCAL_REGISTRY=true && - make DOCKER_TAG=test_${TEST_ID} test)") || - (rm .can_delete_if_success) - # Provoke error in next step by removing .can_delete_if_success early - - run: - shell: /bin/bash - name: Remove locks and check success - command: >- - ssh arkocal@82.165.71.183 "(rm /tmp/ci_test.lock || true)" && - rm .can_delete_if_success - -################################################################################ -# NEW CI OVER SSH ENDS HERE # -# TODO: refactoring, once the migration is done, each step should be a cmd # -################################################################################ - setup-build-environment: - description: "Setup build Environment" - steps: - - run: - shell: /bin/bash - name: Setup build environment - command: | - cd util && \ - bash setup-ubuntu20.04.sh - # create 8GB swap - sudo dd if=/dev/zero of=/swapfile bs=1M count=8000 - sudo mkswap /swapfile - sudo swapon /swapfile - setup-branch: - description: "Setup subbranches" - steps: - - run: - shell: /bin/bash - name: Setup sub branches - command: | - sudo apt install jq - # First find out Base Branch (if any) - if [ ! -z "${CIRCLE_PULL_REQUEST}" ]; then - PR=${CIRCLE_PR_NUMBER} - PR_REPO=${CIRCLE_PR_REPONAME} - PROJECT_USERNAME=${CIRCLE_PROJECT_USERNAME} - url="https://api.github.com/repos/${PROJECT_USERNAME}/${PR_REPO}/pulls/${PR}" - BASE_BRANCH=$(curl "$url" | jq '.base.ref' | tr -d '"') - echo Detected Pull Request with Base Branch ${BASE_BRANCH} - fi - git submodule update --recursive --init - if ( [[ "$CIRCLE_BRANCH" = "develop" ]] || [[ "${BASE_BRANCH}" = "develop" ]] ) && [ -z "${CIRCLE_TAG}" ]; then - #If on develop or a PR towards develop assume that all submodules are updated - echo Detected that PR is related to develop branch and not tagged. Will update all subrepos. - make update - fi - e2e-linter: - description: "Run linting on E2E tests" - steps: - - run: - name: Lint E2E tests - shel: /bin/bash - command: | - cd tests - source ~/.profile - nvm use 10 - sudo chown circleci -R /home/circleci/.npm - sudo chmod 755 -R /home/circleci/.npm - npm install - node_modules/grunt-cli/bin/grunt validate - build-branch: - description: "Build branch" - steps: - - run: - shell: /bin/bash - name: Build branch - # DEBUG=true, because on k8s the tests run inside the debug contianer - command: | - yes| make build DOCKER_TAG="test" DEBUG=true - e2e-test: - description: "E2E test" - parameters: - upgrade-test: - type: string - default: "false" - steps: - - run: - shell: /bin/bash - name: E2e Test - command: | - export PATH=$PATH:/snap/bin - make import-images DOCKER_TAG=test DEBUG=true - npm install nodemailer - export NODOCKERLOGIN=true - retval=2; - export DOCKER_TAG=test - export USE_LOCAL_REGISTRY=true - # If CURRENT_RELEASE_VERSION is set, do an upgrade test from the release version to latest - if [[ "<< parameters.upgrade-test >>" = "true" ]] && [[ -n "${CURRENT_RELEASE_VERSION}" ]]; - then - export DOCKER_TAG="${CURRENT_RELEASE_VERSION}" - export USE_LOCAL_REGISTRY=false - fi - until [ ${retval} -eq 0 ]; do - make undeploy-oisp - (for i in {1..20}; do sleep 60; echo .; done&) && make deploy-oisp-test - if [[ "<< parameters.upgrade-test >>" = "true" ]] && [[ -n "${CURRENT_RELEASE_VERSION}" ]]; - then - (for i in {1..20}; do sleep 60; echo .; done&) && make upgrade-oisp DOCKER_TAG=test USE_LOCAL_REGISTRY=true KEYCLOAK_FORCE_MIGRATION="true" - kubectl -n $(NAMESPACE) scale deployment debugger --replicas=1 - fi - make test - retval=$? - done - no_output_timeout: 20m - push-images: - description: "Push images" - parameters: - tag: - type: string - default: "latest" - steps: - - run: - shell: /bin/bash - name: Push images to docker hub - command: | - # login based on preconfigured env variables - docker login -u ${DOCKER_USERNAME} -p ${DOCKER_PASSWORD} - - # Tag passed "test" images as "latest" - images=$(docker images --format "{{.Repository}}:{{.Tag}}"| grep :test) - for image in $images; do - newimage=$(echo $image | sed -r "s/:test/:latest/g" | sed -r "s/${DOCKER_PREFIX}/oisp/g"); - docker tag $image $newimage; - done - #Start with latest tag, replace later by the real-tags - DOCKER_TAG="latest" - if [ "<< parameters.tag >>" = "date" ]; then - # Should be nightly build - TARGET_DOCKER_TAG=nightly-`date -I` - DOCKER_PUSH_LATEST=true - fi - if [ "<< parameters.tag >>" = "tag" ]; then - # Should be master build - TARGET_DOCKER_TAG=`git describe --tags --exact-match` || exit 1 - fi - # First push latest if applicable and then the real tag - echo Now trying to push with Tag ${DOCKER_TAG} push latest ${DOCKER_PUSH_LATEST} - if [ "$DOCKER_PUSH_LATEST" = "true" ]; then - echo Pushing images with latest tag - if [ -z "$PUSH_DRYRUN" ]; then - make push-images DOCKER_PREFIX=oisp - else - echo Only dry run mode. Not pushing to dockerhub! - fi - fi - # Now replace all latest tagged images by the real tag - echo Now pushing images with tag $DOCKER_TAG - images=$(docker images --format "{{.Repository}}:{{.Tag}}"| grep :latest | grep "oisp/") - for image in $images; do - newimage=$(echo $image | sed -r "s/:latest/:$TARGET_DOCKER_TAG/g"); - echo tagging $image to $newimage; - docker tag $image $newimage - if [ -z "$PUSH_DRYRUN" ]; then - docker push ${newimage} - else - echo Only dry run mode. Not pushing to dockerhub! - fi - done - - check-signed: - description: "Check whether latest commit is signed" - steps: - - run: - name: Check whether most recent commit is signed - shell: /bin/bash - command: | - MESSAGE=`git log -1 --pretty=%B` - echo "Checking whether signed" - if [[ "${MESSAGE}" == *Signed-off-by:*@* ]]; then - echo "Commit is signedoff" - else - echo "Commit is not signedoff" - exit 1 - fi - check-tagged: - description: "Check whether latest commit is tagged" - steps: - - run: - name: Check whether most recent commit is tagged - shell: /bin/bash - command: | - git describe --tags --exact-match || exit 1 - deploy: - description: "Deploy OISP to a production cluster." - steps: - - run: - name: Run deploy script - shell: /bin/bash - command: | - export HELM_ARGS="--atomic \ - --set less_resources=\"false\" --set production=\"true\" \ - --set certmanager.secret=\"frontend-web-prod-tls\" \ - --set certmanager.issuer=\"letsencrypt-prod\" \ - --set numberReplicas.frontend=2 \ - --set numberReplicas.backend=3" - cd ~ && sh deploy.sh - -jobs: - build: - executor: my-executor - steps: - - e2e-over-ssh - build-pr: - executor: my-executor - steps: - - checkout - - check-signed - - setup-build-environment - - setup-branch - - e2e-linter - - build-branch - - e2e-test - build-tagged: - executor: my-executor - steps: - - checkout - - setup-build-environment - - setup-branch - - e2e-linter - - build-branch - - e2e-test - - push-images: - tag: "tag" - build-nightly: - executor: my-executor - steps: - - checkout - - setup-build-environment - - setup-branch - - e2e-linter - - build-branch - - e2e-test: - upgrade-test: "true" - - push-images: - tag: "date" - deploy-production: - executor: deployer - steps: - - deploy - - -workflows: - version: 2.1 - workflow: - jobs: - - build-pr: - filters: - branches: - ignore: - - develop - - master - - ci-feature - - build: - filters: - branches: - only: - - develop - - ci-feature - - build-tagged: - filters: - branches: - ignore: /.*/ - tags: - only: /^v.*/ - nightly: - triggers: - - schedule: - cron: "0 0 * * *" - filters: - branches: - only: - - develop - jobs: - - build-nightly: - filters: - branches: - only: - - develop - - deploy-production: - requires: - - build-nightly diff --git a/.github/workflows/makefile.yaml b/.github/workflows/makefile.yaml index 904909bd..e96498dc 100644 --- a/.github/workflows/makefile.yaml +++ b/.github/workflows/makefile.yaml @@ -125,69 +125,8 @@ jobs: retval=2; export DOCKER_TAG=test export USE_LOCAL_REGISTRY=true - # If CURRENT_RELEASE_VERSION is set, do an upgrade test from the release version to latest - if [[ ${UPGRADE_TEST} = "true" ]] && [[ -n ${CURRENT_RELEASE_VERSION} ]]; - then - export DOCKERUSER=${{ secrets.DOCKER_USERNAME }} - export DOCKERPASS=${{ secrets.DOCKER_PASSWORD }} - export DOCKER_TAG=${CURRENT_RELEASE_VERSION} - export USE_LOCAL_REGISTRY=false - export NODOCKERLOGIN=false - fi - KEYCLOAK_ADMIN_USERNAME=$(kubectl -n iff get secrets keycloak-initial-admin -o json | jq -r .data.username | base64 -d) - KEYCLOAK_ADMIN_PASSWORD=$(kubectl -n iff get secrets keycloak-initial-admin -o json | jq -r .data.password | base64 -d) make deploy-oisp-test - if [[ ${UPGRADE_TEST} = "true" ]] && [[ -n ${CURRENT_RELEASE_VERSION} ]]; - then - (for i in {1..20}; do sleep 60; echo .; done&) && make wait-until-ready - (for i in {1..20}; do sleep 60; echo .; done&) && make upgrade-oisp DOCKER_TAG=test USE_LOCAL_REGISTRY=true KEYCLOAK_FORCE_MIGRATION="true" - kubectl -n oisp scale deployment debugger --replicas=1 - (for i in {1..20}; do sleep 60; echo .; done&) && make wait-until-ready - fi - velero backup create test-backup --include-resources configmaps,secrets --selector 'app.kubernetes.io/part-of=oisp' --include-namespaces oisp - until [[ $(velero backup describe test-backup | grep "Completed") ]]; do - sleep 15 - echo . - done make test retval=$? - loops=0 - until [ ${retval} -eq 0 ] || [ ${loops} -gt 3 ]; do - make undeploy-oisp - (for i in {1..20}; do sleep 60; echo .; done&) && make deploy-oisp-test - restore_name=$(velero restore create --from-backup test-backup --existing-resource-policy update | head -n 1 | cut -d " " -f 3 | cut -d "\"" -f 2) - until [[ $(velero restore describe ${restore_name} | grep "Completed") ]]; do - sleep 15 - echo . - done - # reset database to delete any leftover from previous deployment - make reset-db - # Delete the test users inside keycloak, they are not deleted by make reset-db - KEYCLOAK_POD=$(kubectl get -n iff pods -l app=keycloak -o json | jq -r .items[0].metadata.name) - kubectl -n iff exec ${KEYCLOAK_POD} -- \ - /opt/keycloak/bin/kcadm.sh config credentials \ - --server http://keycloak.local/auth \ - --realm master \ - --user ${KEYCLOAK_ADMIN_USERNAME} \ - --password ${KEYCLOAK_ADMIN_PASSWORD} - TEST_USER_ID1=$(kubectl -n iff exec ${KEYCLOAK_POD} -- \ - /opt/keycloak/bin/kcadm.sh get users -r iff -q email=oisp@testing.com | jq -r .[0].id) - kubectl -n iff exec ${KEYCLOAK_POD} -- \ - /opt/keycloak/bin/kcadm.sh delete users/${TEST_USER_ID1} -r iff - TEST_USER_ID2=$(kubectl -n iff exec ${KEYCLOAK_POD} -- \ - /opt/keycloak/bin/kcadm.sh get users -r iff -q email=oisp2@testing.com | jq -r .[0].id) - kubectl -n iff exec ${KEYCLOAK_POD} -- \ - /opt/keycloak/bin/kcadm.sh delete users/${TEST_USER_ID2} -r iff - if [[ ${UPGRADE_TEST} = "true" ]] && [[ -n ${CURRENT_RELEASE_VERSION} ]]; - then - (for i in {1..20}; do sleep 60; echo .; done&) && make wait-until-ready - (for i in {1..20}; do sleep 60; echo .; done&) && make upgrade-oisp DOCKER_TAG=test USE_LOCAL_REGISTRY=true KEYCLOAK_FORCE_MIGRATION="true" - kubectl -n oisp scale deployment debugger --replicas=1 - (for i in {1..20}; do sleep 60; echo .; done&) && make wait-until-ready - fi - make test - retval=$? - loops=$((loops+1)) - done echo Test return value: ${retval} exit ${retval} diff --git a/Makefile b/Makefile index 4c6c0cc8..96d5b75b 100644 --- a/Makefile +++ b/Makefile @@ -279,28 +279,9 @@ recreate-registry: @k3d registry delete k3d-iff.localhost @k3d registry create iff.localhost -p 12345 -# ======= -# TESTING -# ======= -## prepare-tests: Push the working directory to the debugger pod. -## This has no permanent effect as the pod on which the tests -## are prepared is mortal -## -prepare-tests: wait-until-ready - kubectl -n $(NAMESPACE) exec $(DEBUGGER_POD) -c debugger -- /bin/bash -c "rm -rf *" - kubectl -n $(NAMESPACE) exec $(DEBUGGER_POD) -c debugger -- /bin/bash -c "rm -rf .* || true" - kubectl -n $(NAMESPACE) exec $(DEBUGGER_POD) -c debugger -- /bin/bash -c "pkill node || true" - kubectl -n $(NAMESPACE) exec $(DEBUGGER_POD) -c debugger -- fake-smtp-server -s 2525 > /dev/null 2>&1 & - kubectl -n $(NAMESPACE) cp $(CURRENT_DIR) $(DEBUGGER_POD):/home -c debugger - -## test: Run tests -## -test: OISP_TESTS_SKIP_SCALE ?= "true" -test: prepare-tests test-prep-only - kubectl -n $(NAMESPACE) exec $(DEBUGGER_POD) -c debugger \ - -- /bin/bash -c "cd /home/$(CURRENT_DIR_BASE)/tests && make test TERM=xterm NAMESPACE=$(NAMESPACE) OISP_TESTS_SKIP_SCALE=$(OISP_TESTS_SKIP_SCALE)" - @$(call msg,"Starting the e2e bats testing ..."); - @cd tests/bats && bats test-* +test: +## TO-DO: adjust bats tests to not use OISP +## @cd tests/bats && bats test-* # ============== # BUILD COMMANDS diff --git a/docker-compose.yml b/docker-compose.yml index 510fe1da..191a259b 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -23,13 +23,6 @@ services: labels: - oisp=true - oisp.git_commit=${GIT_COMMIT_FRONTEND} - backend: - image: ${DOCKER_PREFIX:-oisp}/backend:${DOCKER_TAG} - build: - context: ./oisp-backend - labels: - - oisp=true - - oisp.git_commit=${GIT_COMMIT_BACKEND} kairosdb: image: ${DOCKER_PREFIX:-oisp}/kairosdb:${DOCKER_TAG} build: @@ -49,20 +42,6 @@ services: build: context: ./oisp-mqtt-gw/KafkaBridge dockerfile: Dockerfile - grafana: - image: ${DOCKER_PREFIX:-oisp}/grafana:${DOCKER_TAG} - build: - context: ./docker/grafana - labels: - - oisp=true - - oisp.git_commit=${GIT_COMMIT_PLATFORM_LAUNCHER} - backup-service: - image: ${DOCKER_PREFIX:-oisp}/backup-service:${DOCKER_TAG} - build: - context: ./docker/backup-service - labels: - - oisp=true - - oisp.git_commit=${GIT_COMMIT_PLATFORM_LAUNCHER} wait-for-it: image: ${DOCKER_PREFIX:-oisp}/wait-for-it:${DOCKER_TAG} build: diff --git a/docker/backup-service/Dockerfile b/docker/backup-service/Dockerfile deleted file mode 100644 index d4ab8de0..00000000 --- a/docker/backup-service/Dockerfile +++ /dev/null @@ -1,23 +0,0 @@ -FROM alpine:3.13.0 - -ARG gittag - -RUN apk update && apk upgrade -RUN apk add --update make curl git bash ncurses jq py-pip coreutils -RUN pip install shyaml s3cmd - -# Install kubectl -RUN curl -LO https://storage.googleapis.com/kubernetes-release/release/`curl -s https://storage.googleapis.com/kubernetes-release/release/stable.txt`/bin/linux/amd64/kubectl && \ - chmod +x ./kubectl && \ - mv ./kubectl /usr/local/bin/kubectl - -RUN adduser -D backupuser - - -USER backupuser - -RUN cd /home/backupuser/ && git clone https://github.com/Open-IoT-Service-Platform/platform-launcher.git - -WORKDIR /home/backupuser/platform-launcher - -CMD ["tail", "-f", "/dev/null"] diff --git a/docker/grafana/Dockerfile b/docker/grafana/Dockerfile deleted file mode 100644 index 2c79c85b..00000000 --- a/docker/grafana/Dockerfile +++ /dev/null @@ -1,34 +0,0 @@ -# -# Copyright (c) 2018 Intel Corporation -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -ARG GRAFANA_VERSION="6.2.2" - -FROM grafana/grafana:${GRAFANA_VERSION} - -USER grafana - -ARG GF_INSTALL_PLUGINS="grafana-kairosdb-datasource" - -ADD ./kairosdb.yaml /etc/grafana/provisioning/datasources/ -ADD ./dashscript.js /usr/share/grafana/public/dashboards/ - -RUN if [ ! -z "${GF_INSTALL_PLUGINS}" ]; then \ - OLDIFS=$IFS; \ - IFS=','; \ - for plugin in ${GF_INSTALL_PLUGINS}; do \ - IFS=$OLDIFS; \ - grafana-cli --pluginsDir "$GF_PATHS_PLUGINS" plugins install ${plugin}; \ - done; \ -fi diff --git a/docker/grafana/dashscript.js b/docker/grafana/dashscript.js deleted file mode 100644 index a2f06b0d..00000000 --- a/docker/grafana/dashscript.js +++ /dev/null @@ -1,127 +0,0 @@ -/* -Copyright (c) 2018 Intel Corporation - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - -http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -'use strict'; - -// accessible variables in this scope -var window, document, ARGS, $, jQuery, moment, kbn; - -// Setup some variables -var dashboard; - -// All url parameters are available via the ARGS object -var ARGS; - -// Initialize a skeleton with nothing but a rows array and service object -dashboard = { - rows : [], -}; - -var KAIROSDB = "KairosDB"; -var OPENTSDB = "OpenTSDB"; -var DATASOURCE = KAIROSDB - -// Set default time -// time can be overridden in the url using from/to parameters, but this is -// handled automatically in grafana core during dashboard initialization -dashboard.time = { - from: "now-1h", - to: "now" -}; - -var rows = 1; -var name = "No Name"; -var queries = []; -var metrics = []; -var asciiA = 65; - -if (!_.isUndefined(ARGS.rows)) { - rows = parseInt(ARGS.rows, 10); -} - -if (!_.isUndefined(ARGS.name)) { - name = ARGS.name; -} - -if (!_.isUndefined(ARGS.metrics)) { - metrics = ARGS.metrics.split(","); -} - -function createOpentsdbQuery(metric, index) { - return { - "aggregator": "sum", - "downsampleAggregator": "avg", - "downsampleFillPolicy": "none", - "metric": metric, - "refId": String.fromCharCode(asciiA + index) - }; -} - -function createKairosdbQuery(metric, index) { - return { - "query": { - "metricName": metric, - "tags": { - "type": [] - }, - "groupBy": { - "tags": [], - "value": [], - "time": [] - }, - "aggregators": [] - }, - "refId": String.fromCharCode(asciiA + index) - }; -} - - -for (var i = 0; i < metrics.length; i++) { - switch (DATASOURCE) { - case KAIROSDB: - queries.push(createKairosdbQuery(metrics[i], i)); - break; - case OPENTSDB: - default: - queries.push(createOpentsdbQuery(metrics[i], i)); - break; - } -} - -dashboard.title = name; - -for (var i = 0; i < rows; i++) { - dashboard.rows.push({ - title: 'Chart', - height: '900px', - panels: [ - { - title: 'Metrics of Account: ' + name, - type: 'graph', - datasource: DATASOURCE, - span: 12, - fill: 1, - linewidth: 2, - targets: queries, - seriesOverrides: [], - tooltip: { - shared: true - } - }] - }); -} - -return dashboard; diff --git a/docker/grafana/kairosdb.yaml b/docker/grafana/kairosdb.yaml deleted file mode 100644 index 743cb40e..00000000 --- a/docker/grafana/kairosdb.yaml +++ /dev/null @@ -1,41 +0,0 @@ -# config file version -apiVersion: 1 - -# list of datasources to insert/update depending -# what's available in the database -datasources: - # name of the datasource. Required -- name: KairosDB - # datasource type. Required - type: grafana-kairosdb-datasource - # access mode. proxy or direct (Server or Browser in the UI). Required - access: proxy - # org id. will default to orgId 1 if not specified - orgId: 1 - # url - url: $DATASOURCE_URL - # database password, if used - #password: - # database user, if used - #user: - # database name, if used - #database: - # enable/disable basic auth - #basicAuth: - # basic auth username - #basicAuthUser: - # basic auth password - #basicAuthPassword: - # enable/disable with credentials headers - #withCredentials: - # mark as default datasource. Max one per org - isDefault: true - # fields that will be converted to json and stored in jsonData - jsonData: - keepCookies: ["jwt"] - # json object of data that will be encrypted. - #secureJsonData: - # allow users to edit datasources from the UI. - editable: false - # version of datasource - version: 1 diff --git a/docker/grafana/opentsdb.yaml b/docker/grafana/opentsdb.yaml deleted file mode 100644 index 4567586d..00000000 --- a/docker/grafana/opentsdb.yaml +++ /dev/null @@ -1,43 +0,0 @@ -# config file version -apiVersion: 1 - -# list of datasources to insert/update depending -# what's available in the database -datasources: - # name of the datasource. Required -- name: OpenTSDB - # datasource type. Required - type: opentsdb - # access mode. proxy or direct (Server or Browser in the UI). Required - access: proxy - # org id. will default to orgId 1 if not specified - orgId: 1 - # url - url: $DATASOURCE_URL - # database password, if used - #password: - # database user, if used - #user: - # database name, if used - #database: - # enable/disable basic auth - #basicAuth: - # basic auth username - #basicAuthUser: - # basic auth password - #basicAuthPassword: - # enable/disable with credentials headers - #withCredentials: - # mark as default datasource. Max one per org - isDefault: true - # fields that will be converted to json and stored in jsonData - jsonData: - keepCookies: ["jwt"] - tsdbVersion: 3 - tsdbResolution: 1 - # json object of data that will be encrypted. - #secureJsonData: - # allow users to edit datasources from the UI. - editable: false - # version of datasource - version: 1 diff --git a/kubernetes/templates/backend.yaml b/kubernetes/templates/backend.yaml deleted file mode 100644 index 737bc473..00000000 --- a/kubernetes/templates/backend.yaml +++ /dev/null @@ -1,125 +0,0 @@ -apiVersion: v1 -kind: Service -metadata: - labels: - app: backend - name: backend -spec: - ports: - - port: 8080 - selector: - app: backend ---- -apiVersion: apps/v1 -kind: Deployment -metadata: - annotations: - configmap.reloader.stakater.com/reload: "oisp-config" - name: backend - labels: - app: backend -spec: - replicas: {{ .Values.numberReplicas.backend }} - selector: - matchLabels: - app: backend - strategy: - rollingUpdate: - maxSurge: 1 - maxUnavailable: 1 - type: RollingUpdate - template: - metadata: - creationTimestamp: null - labels: - app: backend - spec: - initContainers: - - name: wait-for-kairos - {{ if .Values.use_local_registry }} - image: k3d-iff.localhost:12345/{{ .Values.imagePrefix }}/wait-for-it:{{ .Values.tag }} - {{ else }} - image: {{ .Values.imagePrefix }}/wait-for-it:{{ .Values.tag }} - {{ end }} - args: ["kairosdb:8080", "--", "echo", "kariosds is up"] - - name: wait-for-kafka - {{ if .Values.use_local_registry }} - image: k3d-iff.localhost:12345/{{ .Values.imagePrefix }}/wait-for-it:{{ .Values.tag }} - {{ else }} - image: {{ .Values.imagePrefix }}/wait-for-it:{{ .Values.tag }} - {{ end }} - args: [{{ .Values.kafka.service }}, "--", "echo", "kafka is up"] - containers: - - name: backend - {{ if .Values.use_local_registry }} - image: k3d-iff.localhost:12345/{{ .Values.imagePrefix }}/backend:{{ .Values.tag }} - {{ else }} - image: {{ .Values.imagePrefix }}/backend:{{ .Values.tag }} - {{ end }} - ports: - - containerPort: 8080 - command: ["make"] - args: ["runjar"] - env: - - name: OISP_BACKEND_CONFIG - valueFrom: - configMapKeyRef: - key: backend - name: oisp-config - - name: OISP_BACKEND_JAEGER_CONFIG - valueFrom: - configMapKeyRef: - key: backend-jaeger - name: oisp-config - - name: OISP_KAFKA_CONFIG - valueFrom: - configMapKeyRef: - key: kafka - name: oisp-config - - name: OISP_ZOOKEEPER_CONFIG - valueFrom: - configMapKeyRef: - key: zookeeper - name: oisp-config - - name: OISP_TSDB_PROPERTIES - valueFrom: - configMapKeyRef: - key: kairosdb-properties - name: oisp-config - - name: OISP_OBJECT_STORE_MINIO_PROPERTIES - valueFrom: - configMapKeyRef: - key: minio - name: oisp-config - workingDir: /app - readinessProbe: - tcpSocket: - port: 8080 - resources: - {{ if .Values.less_resources }} - requests: - cpu: 50m - {{ else }} - limits: - cpu: 500m - requests: - cpu: 500m - {{ end }} - {{ if .Values.jaeger_tracing }} - - name: jaeger-agent - image: jaegertracing/jaeger-agent:1.6.0 - ports: - - containerPort: 5775 - protocol: UDP - - containerPort: 5778 - protocol: TCP - - containerPort: 6831 - protocol: UDP - - containerPort: 6832 - protocol: UDP - command: - - "/go/bin/agent-linux" - - "--collector.host-port=jaeger-collector:14267" - {{ end }} - imagePullSecrets: - - name: dockercred diff --git a/kubernetes/templates/frontend.yaml b/kubernetes/templates/frontend.yaml index 3c845dc1..bf233692 100644 --- a/kubernetes/templates/frontend.yaml +++ b/kubernetes/templates/frontend.yaml @@ -41,147 +41,6 @@ spec: labels: app: frontend spec: - initContainers: - - name: wait-for-redis - {{ if .Values.use_local_registry }} - image: k3d-iff.localhost:12345/{{ .Values.imagePrefix }}/wait-for-it:{{ .Values.tag }} - {{ else }} - image: {{ .Values.imagePrefix }}/wait-for-it:{{ .Values.tag }} - {{ end }} - args: ["redis:6379", "--", "echo", "redis is up"] - - name: wait-for-kafka - {{ if .Values.use_local_registry }} - image: k3d-iff.localhost:12345/{{ .Values.imagePrefix }}/wait-for-it:{{ .Values.tag }} - {{ else }} - image: {{ .Values.imagePrefix }}/wait-for-it:{{ .Values.tag }} - {{ end }} - args: [{{ .Values.kafka.service }}, "--", "echo", "kafka is up"] - - name: prepare-db - {{ if .Values.use_local_registry }} - image: k3d-iff.localhost:12345/{{ .Values.imagePrefix }}/frontend:{{ .Values.tag }} - {{ else }} - image: {{ .Values.imagePrefix }}/frontend:{{ .Values.tag }} - {{ end }} - env: - - name: NODE_ENV - value: local - - name: PGSSLMODE - value: require - - name: OISP_FRONTEND_CONFIG - valueFrom: - configMapKeyRef: - name: oisp-config - key: frontend - - name: OISP_POSTGRES_CONFIG - valueFrom: - configMapKeyRef: - name: oisp-config - key: postgres - - name: OISP_REDIS_CONFIG - valueFrom: - configMapKeyRef: - name: oisp-config - key: redis - - name: OISP_KAFKA_CONFIG - valueFrom: - configMapKeyRef: - name: oisp-config - key: kafka - - name: OISP_SMTP_CONFIG - valueFrom: - configMapKeyRef: - name: oisp-config - key: smtp - - name: OISP_FRONTENDSECURITY_CONFIG - valueFrom: - configMapKeyRef: - name: oisp-config - key: frontend-security - - name: OISP_GATEWAY_CONFIG - valueFrom: - configMapKeyRef: - name: oisp-config - key: gateway - - name: OISP_BACKENDHOST_CONFIG - valueFrom: - configMapKeyRef: - name: oisp-config - key: backend-host - - name: OISP_MAIL_CONFIG - valueFrom: - configMapKeyRef: - name: oisp-config - key: mail - - name: OISP_KEYCLOAK_CONFIG - valueFrom: - configMapKeyRef: - name: oisp-config - key: keycloak - command: ["/bin/bash", "-c"] - args: ["node admin createDB; node admin updateDB"] - - name: add-system-users - {{ if .Values.use_local_registry }} - image: k3d-iff.localhost:12345/{{ .Values.imagePrefix }}/frontend:{{ .Values.tag }} - {{ else }} - image: {{ .Values.imagePrefix }}/frontend:{{ .Values.tag }} - {{ end }} - env: - - name: NODE_ENV - value: local - - name: PGSSLMODE - value: require - - name: OISP_FRONTEND_CONFIG - valueFrom: - configMapKeyRef: - name: oisp-config - key: frontend - - name: OISP_POSTGRES_CONFIG - valueFrom: - configMapKeyRef: - name: oisp-config - key: postgres - - name: OISP_REDIS_CONFIG - valueFrom: - configMapKeyRef: - name: oisp-config - key: redis - - name: OISP_KAFKA_CONFIG - valueFrom: - configMapKeyRef: - name: oisp-config - key: kafka - - name: OISP_SMTP_CONFIG - valueFrom: - configMapKeyRef: - name: oisp-config - key: smtp - - name: OISP_FRONTENDSECURITY_CONFIG - valueFrom: - configMapKeyRef: - name: oisp-config - key: frontend-security - - name: OISP_GATEWAY_CONFIG - valueFrom: - configMapKeyRef: - name: oisp-config - key: gateway - - name: OISP_BACKENDHOST_CONFIG - valueFrom: - configMapKeyRef: - name: oisp-config - key: backend-host - - name: OISP_MAIL_CONFIG - valueFrom: - configMapKeyRef: - name: oisp-config - key: mail - - name: OISP_KEYCLOAK_CONFIG - valueFrom: - configMapKeyRef: - name: oisp-config - key: keycloak - command: ["/bin/bash", "-c"] - args: ["node admin addSystemUsers"] containers: - name: frontend {{ if .Values.use_local_registry }} @@ -192,26 +51,7 @@ spec: ports: - containerPort: 4001 args: - - ./wait-for-it.sh - - acid-cluster.iff.svc.cluster.local:5432 - - -t - - "300000" - - -s - - -- - - ./wait-for-it.sh - - redis:6379 - - -t - - "300000" - - -s - - -- - - ./wait-for-it.sh - - {{ .Values.kafka.service }} - - -t - - "300000" - - -s - - -- - ./scripts/docker-start.sh - - "--disable-rate-limits" env: - name: NODE_ENV {{ if .Values.production }} @@ -226,51 +66,11 @@ spec: configMapKeyRef: name: oisp-config key: frontend - - name: OISP_POSTGRES_CONFIG - valueFrom: - configMapKeyRef: - name: oisp-config - key: postgres - - name: OISP_REDIS_CONFIG - valueFrom: - configMapKeyRef: - name: oisp-config - key: redis - - name: OISP_KAFKA_CONFIG - valueFrom: - configMapKeyRef: - name: oisp-config - key: kafka - - name: OISP_SMTP_CONFIG - valueFrom: - configMapKeyRef: - name: oisp-config - key: smtp - - name: OISP_FRONTENDSECURITY_CONFIG - valueFrom: - configMapKeyRef: - name: oisp-config - key: frontend-security - name: OISP_KEYCLOAK_CONFIG valueFrom: configMapKeyRef: name: oisp-config key: keycloak - - name: OISP_GATEWAY_CONFIG - valueFrom: - configMapKeyRef: - name: oisp-config - key: gateway - - name: OISP_BACKENDHOST_CONFIG - valueFrom: - configMapKeyRef: - name: oisp-config - key: backend-host - - name: OISP_MAIL_CONFIG - valueFrom: - configMapKeyRef: - name: oisp-config - key: mail - name: OISP_GRAFANA_CONFIG valueFrom: configMapKeyRef: @@ -295,21 +95,5 @@ spec: requests: cpu: 500m {{ end }} - {{ if .Values.jaeger_tracing }} - - name: jaeger-agent - image: jaegertracing/jaeger-agent:1.6.0 - ports: - - containerPort: 5775 - protocol: UDP - - containerPort: 5778 - protocol: TCP - - containerPort: 6831 - protocol: UDP - - containerPort: 6832 - protocol: UDP - command: - - "/go/bin/agent-linux" - - "--collector.host-port=jaeger-collector:14267" - {{ end }} imagePullSecrets: - name: dockercred diff --git a/kubernetes/templates/grafana.yaml b/kubernetes/templates/grafana.yaml deleted file mode 100644 index 2bf1c167..00000000 --- a/kubernetes/templates/grafana.yaml +++ /dev/null @@ -1,69 +0,0 @@ -apiVersion: v1 - -kind: Service -metadata: - labels: - app: grafana - name: grafana -spec: - ports: - - port: 3000 - selector: - app: grafana ---- -apiVersion: apps/v1 -kind: Deployment -metadata: - labels: - app: grafana - name: grafana -spec: - replicas: 1 - selector: - matchLabels: - app: grafana - template: - metadata: - labels: - app: grafana - spec: - containers: - - name: grafana - {{ if .Values.use_local_registry }} - image: k3d-iff.localhost:12345/{{ .Values.imagePrefix }}/grafana:{{ .Values.tag }} - {{ else }} - image: {{ .Values.imagePrefix }}/grafana:{{ .Values.tag }} - {{ end }} - ports: - - containerPort: 3000 - env: - - name: GF_SERVER_DOMAIN - value: frontend - - name: GF_SERVER_ROOT_URL - value: "%(protocol)s://%(domain)s:%(http_port)s/ui/grafana" - - name: GF_SERVER_HTTP_PORT - value: "3000" - - name: GF_SECURITY_ADMIN_USER - value: {{ .Values.grafana.admin }} - - name: GF_SECURITY_ADMIN_PASSWORD - valueFrom: - configMapKeyRef: - name: oisp-config - key: grafana-admin-password - - name: DATASOURCE_URL - value: http://frontend:4003 - resources: - {{ if .Values.less_resources }} - limits: - cpu: 50m - requests: - cpu: 50m - {{ else }} - limits: - cpu: 100m - requests: - cpu: 100m - {{ end }} - - imagePullSecrets: - - name: dockercred diff --git a/kubernetes/templates/redis.yaml b/kubernetes/templates/redis.yaml deleted file mode 100644 index 218ea74a..00000000 --- a/kubernetes/templates/redis.yaml +++ /dev/null @@ -1,67 +0,0 @@ -apiVersion: v1 -kind: Service -metadata: - name: redis - labels: - app: redis -spec: - ports: - - name: "6379" - port: 6379 - selector: - app: redis ---- -apiVersion: apps/v1 -kind: Deployment -metadata: - labels: - app: redis - name: redis -spec: - replicas: 1 - selector: - matchLabels: - app: redis - template: - metadata: - labels: - app: redis - spec: - containers: - - image: redis:3.0 - imagePullPolicy: IfNotPresent - name: redis - resources: - {{ if .Values.less_resources }} - requests: - cpu: 50m - memory: 500M - {{ else }} - limits: - memory: 2G - cpu: 500m - requests: - memory: 1G - cpu: 500m - {{ end }} - ports: - - containerPort: 6379 - protocol: TCP - volumeMounts: - - mountPath: /data - name: redis-data - volumes: - - name: redis-data - persistentVolumeClaim: - claimName: redis-data ---- -apiVersion: v1 -kind: PersistentVolumeClaim -metadata: - name: redis-data -spec: - accessModes: - - ReadWriteOnce - resources: - requests: - storage: 2Gi diff --git a/tests/Gruntfile.js b/tests/Gruntfile.js deleted file mode 100644 index c0dfed8f..00000000 --- a/tests/Gruntfile.js +++ /dev/null @@ -1,70 +0,0 @@ -/** - * Copyright (c) 2020 Intel Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -"use strict"; -module.exports = function (grunt) { - grunt.initConfig({ - pkg: grunt.file.readJSON('package.json'), - dirs: { - jsfiles: ['Gruntfile.js', - 'oisp-prep-only.js', - 'oisp-tests.js', - 'test-backup-after.js', - 'test-backup-before.js', - 'subtests/*.js', - 'lib/*.js', - 'lib/**/*.js'] - }, - jshint: { - options: { - jshintrc: 'jshint.json', - ignores: ['lib/entropizer/*.js' ] - }, - local: { - src: ['<%= dirs.jsfiles %>'], - options: { - force: false - } - } - }, - eslint: { - local: { - options: { - configFile: 'eslint.json', - ignorePattern: [ 'lib/entropizer/*.js' ], - quiet: true - }, - fix: true, - src: ['<%= dirs.jsfiles %>'], - } - } - }); - - grunt.loadNpmTasks('grunt-contrib-jshint'); - grunt.loadNpmTasks('grunt-eslint'); - - - // Default task(s). - grunt.registerTask('default', [ - 'eslint:local', - 'jshint:local', - ]); - - grunt.registerTask('validate', [ - 'eslint:local', - 'jshint:local' - ]); -}; diff --git a/tests/eslint.json b/tests/eslint.json deleted file mode 100644 index a813bdd3..00000000 --- a/tests/eslint.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "env": { - "es2017": true, - "node": true, - "mocha": true - }, - "rules": { - "curly": "error", - "eqeqeq": "off", - "indent": ["error", 4], - "max-len": [2, {"code": 160}], - "semi": ["error", "always"] - }, - "globals": {}, - "parser": "esprima" -} diff --git a/tests/jshint.json b/tests/jshint.json deleted file mode 100644 index 7fb8b802..00000000 --- a/tests/jshint.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "curly": true, - "eqeqeq": true, - "immed": true, - "latedef": true, - "newcap": true, - "noarg": true, - "sub": true, - "undef": true, - "eqnull": true, - "mocha": true, - "unused": true, - "node": true, - "esversion": 8, - "globals": {} -} diff --git a/tests/lib/cfenv/reader.js b/tests/lib/cfenv/reader.js deleted file mode 100644 index 4109d30d..00000000 --- a/tests/lib/cfenv/reader.js +++ /dev/null @@ -1,24 +0,0 @@ -/** - * Copyright (c) 2014 Intel Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -'use strict'; -var cfenv = require('cfenv'), - appEnv = cfenv.getAppEnv(), - vcap_services = appEnv.getServices(); - -exports.getServiceCredentials = function (name){ - var credentials = vcap_services[name] ? vcap_services[name].credentials || {} : {}; - return credentials; -}; \ No newline at end of file diff --git a/tests/lib/common.js b/tests/lib/common.js deleted file mode 100644 index 2e34dea3..00000000 --- a/tests/lib/common.js +++ /dev/null @@ -1,187 +0,0 @@ -class Data { - constructor(value, expectedActuation, expectedEmailReason) { - this.value = value; - this.expectedActuation = expectedActuation; - this.expectedEmailReason = expectedEmailReason; - this.ts = null; - } -} - -class Rule { - constructor(name, op, value, actions) { - this.name = name; - this.basicConditionOperator = op; - this.basicConditionValue = value.toString(); - this.actions = []; - if ( actions ) { - this.actions = actions; - } - this.id = null; - this.cid = null; - } - - addAction(type, target) { - for(var action of this.actions) { - if ( action.type === type ) { - action.target.push(target); - return; - } - } - - action = {}; - action.type = type; - action.target = []; - action.target.push(target); - this.actions.push(action); - } -} - -class Component { - constructor(name, dataType, format, unit, display, min, max, rules, getDataFn, checkDataFn) { - this._name = name; - this.catalog = {}; - this.catalog.dimension = name; - this.catalog.version = "1.0"; - this.catalog.type = "sensor"; - this.catalog.dataType = dataType; - this.catalog.format = format; - if ( min != null ) { - this.catalog.min = min; - } - if ( max != null ) { - this.catalog.max = max; - } - this.catalog.measureunit = unit; - this.catalog.display = display; - - this.rules = []; - if ( rules ) { - this.rules = rules; - } - this.data = []; - if ( getDataFn ) { - var values = getDataFn(this.name, this, function(obj, value) { - obj.data.push(value); - }); - if ( values ) { - this.data = values; - } - } - this.checkDataFn = checkDataFn; - this.dataIndex = 0; - this.next = null; - this.prev = null; - this.alerts = []; - } - - get name() { - return this._name + "-" + this.catalog.type; - } - - get type() { - return this._name + ".v" + this.catalog.version; - } - - get cId() { - return this.catalog.dimension + ".v" + this.catalog.version; - } - - reset() { - if ( this.data ) { - for (var i = 0; i < this.data.length; i++) { - this.data[i].ts = null; - } - } - this.dataIndex = 0; - } - - upgradeVersion() { - var version = this.catalog.version.split("."); - if ( version.length === 2 ) { - this.catalog.version = version[0] + "." + (parseInt(version[1]) + 1); - return true; - } - else { - return false; - } - } - - checkData(data) { - if ( data && this.checkDataFn ) { - return this.checkDataFn(this.data, data); - } - - return "Cannot check data"; - } - - alertsNumber() { - var nb = 0; - this.data.forEach(function(data) { - if ( data.expectedActuation != null ) { - nb++; - } - }); - return nb; - } - - checkAlert(value, condition ) { - for (var i=0; i 0 ) { - this.list[this.list.length-1].next = component; - component.prev = this.list[this.list.length-1]; - } - - this.list.push(component); - } - - get size() { - return this.list.length; - } - - reset() { - for (var i=0; i 0 ) { - return this.list[0]; - } - else { - return null; - } - } - get last() { - if ( this.list.length > 0 ) { - return this.list[this.list.length-1]; - } - else { - return null; - } - } -} - -module.exports = { - Data, - Rule, - Component, - Components -}; diff --git a/tests/lib/helpers/accounts.js b/tests/lib/helpers/accounts.js deleted file mode 100644 index 81da7869..00000000 --- a/tests/lib/helpers/accounts.js +++ /dev/null @@ -1,207 +0,0 @@ -/** - * Copyright (c) 2017 Intel Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -"use strict"; - -var chai = require('chai'); -var assert = chai.assert; - -var config = require("../../test-config.json"); -var oispSdk = require("@open-iot-service-platform/oisp-sdk-js"); -var api = oispSdk(config).api.rest; - - - -function createAccount(name, userToken, cb) { - if (!cb) { - throw "Callback required"; - } - - var data = { - userToken: userToken, - body: { - name: name - } - }; - - api.accounts.createAccount(data, function(err, response) { - if (!err) { - assert.isString(response.id, "Account id not returned"); - cb(null, response); - } - else { - cb(err); - } - }); -} - -function getAccountInfo(accountId, userToken, cb) { - if (!cb) { - throw "Callback required"; - } - - var data = { - userToken: userToken, - accountId: accountId - }; - - api.accounts.getAccountInfo(data, function(err, response) { - if (!err) { - assert.notEqual(response, null, 'response is null'); - cb(null, response); - } - else { - cb(err); - } - }); -} - -function updateAccount(accountId, userToken, newAccountInfo, cb) { - if (!cb) { - throw "Callback required"; - } - - var data = { - userToken: userToken, - accountId: accountId, - body: newAccountInfo - }; - - api.accounts.updateAccount(data, function(err, response) { - if (!err) { - assert.notEqual(response, null, 'response is null'); - cb(null, response); - } - else { - cb(err); - } - }); -} - -function getAccountActivationCode(accountId, userToken, cb) { - if (!cb) { - throw "Callback required"; - } - - var data = { - userToken: userToken, - accountId: accountId - }; - - api.accounts.getAccountActivationCode(data, function(err, response) { - if(!err){ - assert.notEqual(response.activationCode, null ,'activation code is null'); - cb(null,response); - } - else{ - cb(err); - } - }); -} - -function refreshAccountActivationCode(accountId, userToken, cb) { - if (!cb) { - throw "Callback required"; - } - - var data = { - userToken: userToken, - accountId: accountId - }; - - api.accounts.refreshAccountActivationCode(data, function(err, response) { - if(!err){ - assert.notEqual(response.activationCode, null ,'activation code is null'); - cb(null,response); - } - else{ - cb(err); - } - }); -} - -function getAccountUsers(accountId, userToken, cb) { - if (!cb) { - throw "Callback required"; - } - - var data = { - userToken: userToken, - accountId: accountId - }; - - api.accounts.getAccountUsers(data, function(err, response) { - assert.notEqual(response, null ,'user list is null'); - cb(err, response); - }); -} - -function changeAccountUser(accountId, userToken, userId, cb) { - if (!cb) { - throw "Callback required"; - } - - - var data = { - userToken: userToken, - accountId: accountId, - userId: userId, - body:{ - id: userId, - accounts:{} - } - }; - - data.body.accounts[accountId] = 'admin'; - - api.accounts.changeAccountUser(data, function(err, response) { - assert.notEqual(response, null, 'response is null'); - cb(err, response); - }); -} - -function deleteAccount(userToken, accountId, cb) { - if (!cb) { - throw "Callback required"; - } - - var data = { - userToken: userToken, - accountId: accountId - }; - - api.accounts.deleteAccount(data, function(err, response) { - if (!err) { - assert.notEqual(response, null, 'response is null'); - cb(null,response); - } - else { - cb(err); - } - }); -} - -module.exports = { - getAccountActivationCode: getAccountActivationCode, - refreshAccountActivationCode: refreshAccountActivationCode, - getAccountUsers: getAccountUsers, - changeAccountUser: changeAccountUser, - createAccount: createAccount, - getAccountInfo: getAccountInfo, - updateAccount: updateAccount, - deleteAccount: deleteAccount -}; diff --git a/tests/lib/helpers/alerts.js b/tests/lib/helpers/alerts.js deleted file mode 100644 index 4b2fa986..00000000 --- a/tests/lib/helpers/alerts.js +++ /dev/null @@ -1,177 +0,0 @@ -/** - * Copyright (c) 2017 Intel Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -"use strict"; - -var chai = require('chai'); -var assert = chai.assert; - -var config = require("../../test-config.json"); -var oispSdk = require("@open-iot-service-platform/oisp-sdk-js"); -var api = oispSdk(config).api.rest; - - - -function getListOfAlerts(userToken, accountId, cb) { - if (!cb) { - throw "Callback required"; - } - - var data = { - userToken: userToken, - accountId: accountId, - }; - - api.alerts.getListOfAlerts(data, function(err, response) { - if (err) { - cb(err, null); - } - else { - assert.notEqual(response, null, 'response is null'); - cb(null, response); - } - }); -} - -function getAlertDetails(userToken, accountId, alertId, cb) { - if (!cb) { - throw "Callback required"; - } - - var data = { - userToken: userToken, - accountId: accountId, - alertId: alertId - }; - - api.alerts.getAlertDetails(data, function(err, response) { - if (err) { - cb(err, null); - } - else { - assert.notEqual(response, null, 'response is null'); - cb(null, response); - } - }); -} - - -function closeAlert(userToken, accountId, alertId, cb) { - if (!cb) { - throw "Callback required"; - } - - var data = { - userToken: userToken, - accountId: accountId, - alertId: alertId - }; - - api.alerts.closeAlert(data, function(err) { - if (err) { - cb(err, null); - } - else { - getListOfAlerts(userToken, accountId, function(err,response){ - assert.notEqual(response, null, 'response is null'); - cb(null, response); - }); - } - }); -} - -function updateAlertStatus(userToken, accountId, alertId, status, cb) { - if (!cb) { - throw "Callback required"; - } - - var data = { - userToken: userToken, - accountId: accountId, - alertId: alertId, - statusName: status - }; - - api.alerts.updateAlertStatus(data, function(err) { - if (err) { - cb(err, null); - } - else { - getAlertDetails(userToken, accountId, alertId, function(err,response){ - if (err) { - cb(err, null); - } - else { - cb(null, response); - } - }); - } - }); -} - -function addCommentsToAlert(userToken, accountId, alertId, comments, cb) { - if (!cb) { - throw "Callback required"; - } - - var data = { - userToken: userToken, - accountId: accountId, - alertId: alertId, - body: [] - }; - - data.body.push(comments); - - api.alerts.addCommentsToAlert(data, function(err, response) { - if (err) { - cb(err, null); - } - else { - cb(null, response); - } - }); -} - - -function deleteAlert(userToken, accountId, alertId){ - var data = { - userToken: userToken, - accountId: accountId, - alertId: alertId - }; - - return new Promise((resolve, reject) => { - api.alerts.deleteAlert(data, function(err, response){ - if (err){ - reject(err); - } - else { - resolve(response); - } - }); - }); -} - -module.exports = { - getListOfAlerts: getListOfAlerts, - getAlertDetails: getAlertDetails, - closeAlert: closeAlert, - updateAlertStatus: updateAlertStatus, - addCommentsToAlert: addCommentsToAlert, - deleteAlert: deleteAlert -}; diff --git a/tests/lib/helpers/auth.js b/tests/lib/helpers/auth.js deleted file mode 100644 index 03bed7f8..00000000 --- a/tests/lib/helpers/auth.js +++ /dev/null @@ -1,112 +0,0 @@ -/** - * Copyright (c) 2017 Intel Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -"use strict"; - -var chai = require('chai'); -var assert = chai.assert; - -var config = require("../../test-config.json"); -var oispSdk = require("@open-iot-service-platform/oisp-sdk-js"); -var api = oispSdk(config).api.rest; - - -function login(username, password, cb) { - if (!cb) { - throw "Callback required"; - } - - var data = { - body: { - username: username, - password: password - } - }; - - api.auth.getAuthToken(data, function(err, response) { - var grant = {}; - - if (!err) { - assert.isString(response.token, "no access token retrieved"); - assert.isString(response.refreshToken, "no refresh token retrieved"); - assert.isString(response.idToken, "no id token retrieved"); - grant.token = response.token; - grant.refreshToken = response.refreshToken; - grant.idToken = response.idToken; - } - cb(err, grant); - }); -} - - -function tokenInfo(token, cb) { - if (!cb) { - throw "Callback required"; - } - - var data = { - userToken:token - }; - - api.auth.getAuthTokenInfo(data, function(err, response) { - if (!err) { - assert.equal(response.header.typ,'JWT', "response header type error"); - } - cb(err, response); - }); -} - -function userInfo(token, cb) { - if (!cb) { - throw "Callback required"; - } - - var data = { - userToken:token - }; - - api.auth.getAuthUserInfo(data, function(err, response) { - if (!err) { - assert.isString(response.id, "no access token retrieved"); - } - cb(err, response); - }); -} - -function refreshAuthToken(oldToken, refreshToken, cb) { - if (!cb) { - throw "Callback required"; - } - - var data = { - token: oldToken, - body: { - refreshToken: refreshToken - } - }; - - api.auth.refreshAuthToken(data, function(err, response) { - cb(err, response); - }); -} - -module.exports = { - login: login, - refreshAuthToken: refreshAuthToken, - userInfo: userInfo, - tokenInfo: tokenInfo -}; diff --git a/tests/lib/helpers/cmpcatalog.js b/tests/lib/helpers/cmpcatalog.js deleted file mode 100644 index fa354cb9..00000000 --- a/tests/lib/helpers/cmpcatalog.js +++ /dev/null @@ -1,123 +0,0 @@ -/** - * Copyright (c) 2017 Intel Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -"use strict"; - -var chai = require('chai'); -var assert = chai.assert; - -var config = require("../../test-config.json"); -var oispSdk = require("@open-iot-service-platform/oisp-sdk-js"); -var api = oispSdk(config).api.rest; - - -function getCatalog(userToken, accountId, cb){ - if (!cb) { - throw "Callback required"; - } - - var data = { - userToken: userToken, - accountId: accountId, - body: { - full: true - } - }; - - api.cmpcatalog.getCatalog(data, function(err, response) { - assert.notEqual(response, null, 'response is null'); - if (err) { - cb(err); - } else { - cb(null, response); - } - }); -} - - -function createCatalog(userToken, accountId, options, cb){ - if (!cb) { - throw "Callback required"; - } - - var data = { - userToken: userToken, - accountId: accountId, - body: options - }; - - api.cmpcatalog.createCatalog(data, function(err, response) { - assert.notEqual(response, null, 'response is null'); - if (err) { - cb(err); - } else { - cb(null, response); - } - }); -} - -function getCatalogDetail(userToken, accountId, cid, cb){ - if (!cb) { - throw "Callback required"; - } - - var data = { - userToken: userToken, - accountId: accountId, - componentId: cid - }; - - api.cmpcatalog.getCatalogDetail(data, function(err, response) { - assert.notEqual(response, null, 'response is null'); - if (err) { - cb(err); - } else { - cb(null, response); - } - }); -} - - -function updateCatalog(userToken, accountId, cid, newmin, newmax, cb){ - if (!cb) { - throw "Callback required"; - } - - var data = { - userToken: userToken, - accountId: accountId, - componentId: cid, - body:{ - "min": newmin, - "max": newmax - } - }; - - api.cmpcatalog.updateCatalog(data, function(err, response) { - assert.notEqual(response, null, 'response is null'); - if (err) { - cb(err); - } else { - cb(null, response); - } - }); -} - -module.exports={ - getCatalog: getCatalog, - createCatalog: createCatalog, - getCatalogDetail: getCatalogDetail, - updateCatalog: updateCatalog -}; \ No newline at end of file diff --git a/tests/lib/helpers/connector.js b/tests/lib/helpers/connector.js deleted file mode 100644 index 638bccd5..00000000 --- a/tests/lib/helpers/connector.js +++ /dev/null @@ -1,83 +0,0 @@ -/** - * Copyright (c) 2017 Intel Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -"use strict"; - -//------------------------------------------------------------------------------------------------------- -// Helper Functions -//------------------------------------------------------------------------------------------------------- - -var WebSocket = require('ws'); -var config = require("../../test-config.json"); - -function wsConnect(connector, deviceToken, deviceId, cb) { - if (!cb) { - throw "Callback required"; - } - - var deviceInfo = { - device_id: deviceId, - device_token: deviceToken - }; - - connector.updateDeviceInfo(deviceInfo); - - var data = { - deviceId: deviceId - }; - - connector.controlCommandListen(data, cb, function() {}); -} - -var sockets = {}; - -function openWsConnection(deviceToken, deviceId, cb, address, protocols, options) { - // Returns a raw ws socket without authentication if the address is specified. - // The socket must be handled manually by the caller. - if (address) { - return new WebSocket(address, protocols, options); - } else { - address = config.connector.ws.host + ':' + config.connector.ws.port; - if (config.connector.ws.secure) { - address = 'wss://' + address; - } else { - address = 'ws://' + address; - } - var socket = new WebSocket(address, 'echo-protocol'); - socket.on('open', () => { - var deviceInfo = { - type: 'device', - deviceId: deviceId, - deviceToken: deviceToken - }; - socket.send(JSON.stringify(deviceInfo)); - }); - socket.on('message', (message) => { - cb(JSON.parse(message).content); - }); - sockets[deviceId] = socket; - return socket; - } -} - -function closeWsConnection(deviceId) { - return sockets[deviceId].close(); -} - -module.exports={ - wsConnect: wsConnect, - openWsConnection: openWsConnection, - closeWsConnection: closeWsConnection -}; diff --git a/tests/lib/helpers/control.js b/tests/lib/helpers/control.js deleted file mode 100644 index 4d2adc26..00000000 --- a/tests/lib/helpers/control.js +++ /dev/null @@ -1,141 +0,0 @@ -/** - * Copyright (c) 2017 Intel Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -"use strict"; - -//------------------------------------------------------------------------------------------------------- -// Helper Functions -//------------------------------------------------------------------------------------------------------- - -var chai = require('chai'); -var assert = chai.assert; - -var config = require("../../test-config.json"); -var oispSdk = require("@open-iot-service-platform/oisp-sdk-js"); -var api = oispSdk(config).api.rest; - - -function sendActuationCommand(paramName, value, userToken, accountId, actuatorId, deviceId, cb){ - if (!cb) { - throw "Callback required"; - } - - var data = { - userToken: userToken, - accountId: accountId, - body: { - commands: [{ - componentId: actuatorId, - transport: "ws", - parameters: [{ - name: paramName, - value: value.toString() - }] - }], - complexCommands: [] - }, - }; - - api.control.sendActuationCommand(data, function(err, response) { - assert.notEqual(response, null, 'response is null'); - if (err) { - cb(err); - } else { - cb(null, response); - } - }); -} - -function pullActuations(parameters, deviceToken, accountId, deviceId, cid, cb) { - if (!cb) { - throw "Callback required"; - } - - var data = { - from: parameters.from, - to: parameters.to, - deviceToken: deviceToken, - accountId: accountId, - deviceId: deviceId - }; - - api.control.pullActuations(data, function(err, response) { - if (err) { - cb(err); - } else { - cb(null, response); - } - }); - -} - -function saveComplexCommand(name, paramName, value, userToken, accountId, deviceId, actId, cb) { - if (!cb) { - throw "Callback required"; - } - - var data = { - userToken: userToken, - accountId: accountId, - commandName: name, - body: { - commands: [{ - componentId: actId, - transport: "ws", - parameters: [{ - name: paramName, - value: value.toString() - }] - }] - }, - deviceId: deviceId - }; - - api.control.saveComplexCommand(data, function(err, response) { - assert.notEqual(response, null, 'response is null: ' + err); - if (err) { - cb(err); - } else { - cb(null, response); - } - }); -} - - -function deleteComplexCommand(name, userToken, accountId) { - - var data = { - userToken: userToken, - accountId: accountId, - commandName: name, - }; - - return new Promise((resolve, reject) => { - api.control.deleteComplexCommand(data, function(err, response) { - if (err) { - reject(err); - } else { - resolve(response); - } - }); - }); -} - -module.exports={ - saveComplexCommand: saveComplexCommand, - pullActuations: pullActuations, - sendActuationCommand: sendActuationCommand, - deleteComplexCommand: deleteComplexCommand -}; diff --git a/tests/lib/helpers/data.js b/tests/lib/helpers/data.js deleted file mode 100644 index 94283341..00000000 --- a/tests/lib/helpers/data.js +++ /dev/null @@ -1,293 +0,0 @@ -/** - * Copyright (c) 2017 Intel Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -"use strict"; - -//------------------------------------------------------------------------------------------------------- -// Helper Functions -//------------------------------------------------------------------------------------------------------- - -var chai = require('chai'); -var assert = chai.assert; - -var config = require("../../test-config.json"); -var oispSdk = require("@open-iot-service-platform/oisp-sdk-js"); -var api = oispSdk(config).api.rest; - - - - -function getObservation(ts, userToken, accountId, deviceId, cid, cb) { - if (!cb) { - throw "Callback required"; - } - - var data = { - userToken: userToken, - accountId: accountId, - body: { - from: ts, - targetFilter: { - deviceList: [deviceId] - }, - metrics: [{ - id: cid - }] - } - }; - api.data.searchData(data, function(err, response) { - var found = false; - if (err) { - cb(err); - } else { - if (response.series) { - for (var i = 0; i < response.series.length; i++) { - for (var j = 0; j < response.series[i].points.length; j++) { - if (response.series[i].points[j].ts === ts) { - found = true; - cb(null, ts, parseInt(response.series[i].points[j].value)); - break; - } - } - } - } - - if (!found) { - cb(null, ts, null); - } - } - }); -} - -function searchDataMaxItems(from, to, userToken, accountId, deviceId, cids, queryMeasureLocation, targetFilter, maxItems, orders, aggregators, cb) { - if (!cb) { - throw "Callback required"; - } - if (!Array.isArray(cids)) { - cids = [cids]; - } - - var metrics = cids.map((element) => { - var metric = {"id": element}; - if (orders && orders[element] !== undefined && orders[element] !== null) { - metric.order = orders[element]; - } - if (aggregators && aggregators[element] !== undefined && aggregators[element] !== null) { - metric.aggregator = aggregators[element]; - } - return metric; - }); - - if (targetFilter === undefined) { - targetFilter = {}; - } - if (targetFilter.deviceList === undefined) { - targetFilter.deviceList = [deviceId]; - } else { - if (targetFilter.deviceList.indexOf(deviceId) === -1) { - targetFilter.deviceList.push(deviceId); - } - } - - var data = { - userToken: userToken, - accountId: accountId, - body: { - from: from, - targetFilter: targetFilter, - metrics: metrics, - queryMeasureLocation: queryMeasureLocation - } - }; - - if (maxItems != null) { - data.body.maxItems = maxItems; - } - if (to !== undefined && to > 0) { - data.body.to = to; - } - api.data.searchData(data, function(err, response) { - if (err) { - cb(err); - } else { - cb(null, response); - } - }); -} - -function searchData(from, to, userToken, accountId, deviceId, cid, queryMeasureLocation, targetFilter, cb) { - searchDataMaxItems(from, to, userToken, accountId, deviceId, cid, queryMeasureLocation, targetFilter, null, null, null, cb); -} - -function submitData(value, deviceToken, accountId, deviceId, cid, cb) { - if (!cb) { - throw "Callback required"; - } - var ts = new Date().getTime(); - - var data = { - userToken: deviceToken, - deviceId: deviceId, - body: { - accountId: accountId, - on: ts, - data: [{ - componentId: cid, - value: Buffer.isBuffer(value) ? value : value.toString(), - on: ts - }] - } - }; - - api.data.submitData(data, function(err, response) { - if (err) { - cb(err); - } else { - if (response) { - cb(null, response); - } - } - }); -} - -function submitDataList(valueList, deviceToken, accountId, deviceId, cidList, cb) { - if (!cb) { - throw "Callback required"; - } - - var data = { - userToken: deviceToken, - deviceId: deviceId, - body: { - accountId: accountId, - on: valueList[0].ts, - data: [] - } - }; - - valueList.forEach(function(element){ - var toPush = { - componentId: cidList[element.component], - value: (typeof element.value === 'string' || Buffer.isBuffer(element.value)) ? element.value : element.value.toString(), - on: element.ts - }; - if (element.loc) { - toPush.loc = element.loc; - } - if (element.attributes !== undefined){ - toPush.attributes = element.attributes; - } - data.body.data.push(toPush); - }); - api.data.submitData(data, function(err, response) { - if (err) { - cb(err); - } else { - if (response) { - cb(null, response); - } - } - }); -} - -function submitDataListAsUser(valueList, userToken, accountId, deviceId, cidList, cb) { - if (!cb) { - throw "Callback required"; - } - - var data = { - userToken: userToken, - accountId: accountId, - deviceId: deviceId, - body: { - accountId: accountId, - on: valueList[0].ts, - data: [] - } - }; - - valueList.forEach(function(element){ - var toPush = { - componentId: cidList[element.component], - value: (typeof element.value === 'string' || Buffer.isBuffer(element.value)) ? element.value : element.value.toString(), - on: element.ts - }; - if (element.loc) { - toPush.loc = element.loc; - } - if (element.attributes !== undefined){ - toPush.attributes = element.attributes; - } - data.body.data.push(toPush); - }); - api.data.submitDataAsUser(data, function(err, response) { - if (err) { - cb(err); - } else { - if (response) { - cb(null, response); - } - } - }); -} - -function searchDataAdvanced(from, to, userToken, accountId, deviceIds, cidList, showMeasureLocation, returnedMeasureAttributes, aggregations, countOnly, cb) { - if (!cb) { - throw "Callback required"; - } - - var data = { - userToken: userToken, - accountId: accountId, - body: { - deviceIds: deviceIds, - from: from, - showMeasureLocation: showMeasureLocation, - componentIds: cidList - } - }; - - if (returnedMeasureAttributes !== undefined && returnedMeasureAttributes !== []) { - data.body.returnedMeasureAttributes = returnedMeasureAttributes; - } - if (aggregations !== undefined && aggregations !== "") { - data.body.aggregations = aggregations; - } - if (countOnly !== undefined) { - data.body.countOnly = countOnly; - } - if (to !== undefined) { - data.body.to = to; - } - - api.data.searchDataAdvanced(data, function(err, response) { - if (err) { - cb(err); - } else { - assert.notEqual(response, null, 'response is null'); - cb(null, response); - } - }); -} - -module.exports={ - getObservation: getObservation, - searchData: searchData, - searchDataMaxItems: searchDataMaxItems, - submitData: submitData, - submitDataList: submitDataList, - submitDataListAsUser: submitDataListAsUser, - searchDataAdvanced: searchDataAdvanced -}; diff --git a/tests/lib/helpers/devices.js b/tests/lib/helpers/devices.js deleted file mode 100644 index 0f44588a..00000000 --- a/tests/lib/helpers/devices.js +++ /dev/null @@ -1,412 +0,0 @@ -/** - * Copyright (c) 2017 Intel Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -"use strict"; - -var uuid = require('uuid/v4'); - -var chai = require('chai'); -var assert = chai.assert; - -var config = require("../../test-config.json"); -var oispSdk = require("@open-iot-service-platform/oisp-sdk-js"); -var api = oispSdk(config).api.rest; - - -function createDevice(name, deviceId, userToken, accountId, cb) { - if (!cb) { - throw "Callback required"; - } - - var data = { - userToken: userToken, - accountId: accountId, - body: { - name: name, - deviceId: deviceId, - gatewayId: "00-11-22-33-44-55", - tags: ["tag-a", "tag-b"], - attributes: { - os: "linux" - } - } - }; - - api.devices.createDevice(data, function(err, response) { - if (err) { - cb(err, null); - } - else { - assert.notEqual(response, null, 'response is null'); - cb(null, response); - } - }); -} - -function getDevices(userToken, accountId, cb) { - if (!cb) { - throw "Callback required"; - } - - var data = { - userToken: userToken, - accountId: accountId, - }; - - api.devices.getDevices(data, function(err, response) { - if (err) { - cb(err, null); - } - else { - assert.notEqual(response, null, 'response is null'); - cb(null, response); - } - }); -} - -function getDeviceDetails(userToken, accountId, deviceId, cb) { - if (!cb) { - throw "Callback required"; - } - - var data = { - userToken: userToken, - accountId: accountId, - deviceId: deviceId - }; - - api.devices.getDeviceDetails(data, function(err, response) { - if (err) { - cb(err, null); - } - else { - assert.notEqual(response, null, 'response is null'); - cb(null, response); - } - }); -} - -function updateDeviceDetails(userToken, accountId, deviceId, deviceInfo, cb) { - if (!cb) { - throw "Callback required"; - } - - var data = { - userToken: userToken, - accountId: accountId, - deviceId: deviceId, - body:deviceInfo - }; - - api.devices.updateDeviceDetails(data, function(err, response) { - if (err) { - cb(err, null); - } - else { - assert.notEqual(response, null, 'response is null'); - cb(null, response); - } - }); -} - -function getAccountActivationCode(accountId, userToken, cb) { - var data = { - userToken: userToken, - accountId: accountId - }; - - api.accounts.getAccountActivationCode(data, function(err, response) { - if(!err){ - assert.notEqual(response.activationCode, null ,'activation code is null'); - cb(null,response.activationCode); - } - else{ - cb(err); - } - }); -} - -function activateDevice(userToken, accountId, deviceId, cb) { - if (!cb) { - throw "Callback required"; - } - - getAccountActivationCode(accountId, userToken, function(err, activationCode) { - if (err) { - cb(err); - } else { - var data = { - userToken: userToken, - accountId: accountId, - deviceId: deviceId, - body: { - activationCode: activationCode - } - }; - - api.devices.activateDevice(data, function(err, response) { - if (err) { - cb(err); - } else { - assert.notEqual(response, null, 'response is null'); - cb(null, response); - } - }); - } - }); -} - -function activateDeviceWithoutToken(activationCode, deviceId, cb) { - if (!cb) { - throw "Callback required"; - } - var data = { - deviceId: deviceId, - body: { - activationCode: activationCode - } - }; - api.devices.registerDevice(data, function(err, response) { - if (err) { - cb(err); - } else { - assert.notEqual(response, null, 'response is null'); - cb(null, response); - } - }); -} - -function createComponentId() { - return uuid(); -} - -function addDeviceComponent(name, type, userToken, accountId, deviceId, cb) { - if (!cb) { - throw "Callback required"; - } - - var cid = createComponentId(); - - var data = { - userToken: userToken, - accountId: accountId, - deviceId: deviceId, - body: { - name: name, - type: type, - cid: cid - } - }; - - api.devices.addDeviceComponent(data, function(err, response) { - if (err) { - cb(err); - } else { - assert.notEqual(response, null, 'response is null'); - cb(null, response.cid); - } - }); -} - -function submitData(value, deviceToken, accountId, deviceId, cid, cb) { - if (!cb) { - throw "Callback required"; - } - - var ts = new Date().getTime(); - - var data = { - deviceToken: deviceToken, - deviceId: deviceId, - body: { - accountId: accountId, - on: ts, - data: [{ - componentId: cid, - value: Buffer.isBuffer(value) ? value : value.toString(), - on: ts - }] - } - }; - api.devices.submitData(data, function(err) { - if (err) { - cb(err); - } else { - cb(null, ts); - } - }); - -} - - - -function deleteDeviceComponent (userToken, accountId,deviceId, cid , cb) { - if (!cb) { - throw "Callback required"; - } - - var data = { - userToken: userToken, - accountId: accountId, - deviceId: deviceId, - cid: cid - }; - - api.devices.deleteDeviceComponent(data, function(err, response) { - if (err) { - cb(err); - } else { - cb(null, response); - } - }); - -} - -function deleteDevice (userToken, accountId, deviceId, cb) { - if (!cb) { - throw "Callback required"; - } - - var data = { - userToken: userToken, - accountId: accountId, - deviceId: deviceId - }; - - api.devices.deleteDevice(data, function(err, response) { - if (err) { - cb(err); - } else { - cb(null, response); - } - }); - -} - -function getDeviceTags (userToken, accountId, cb) { - if (!cb) { - throw "Callback required"; - } - - var data = { - userToken: userToken, - accountId: accountId - }; - - api.devices.getDeviceTags(data, function(err, response) { - if (err) { - cb(err); - } else { - cb(null, response); - } - }); - -} - -function getDeviceAttributes (userToken, accountId, cb) { - if (!cb) { - throw "Callback required"; - } - - var data = { - userToken: userToken, - accountId: accountId - }; - - api.devices.getDeviceAttributes(data, function(err, response) { - if (err) { - cb(err); - } else { - cb(null, response); - } - }); - -} - -function countDevices (userToken, accountId, cb) { - if (!cb) { - throw "Callback required"; - } - - var data = { - userToken: userToken, - accountId: accountId, - body:{ - "status":{ - "operator":"OR" - }, - "components":{ - "operator":"OR" - } - } - }; - - api.devices.countDevices(data, function(err, response) { - if (err) { - cb(err); - } else { - cb(null, response); - } - }); - -} - -function searchDevices (userToken, accountId, cb) { - if (!cb) { - throw "Callback required"; - } - - var data = { - userToken: userToken, - accountId: accountId, - limit: 10, - skip: 0, - body:{ - "status":{ - "operator":"OR" - }, - "components":{ - "operator":"OR" - } - } - }; - - api.devices.searchDevices(data, function(err, response) { - if (err) { - cb(err); - } else { - cb(null, response); - } - }); -} - -module.exports = { - createDevice: createDevice, - getDevices: getDevices, - getDeviceDetails: getDeviceDetails, - updateDeviceDetails: updateDeviceDetails, - activateDevice: activateDevice, - activateDeviceWithoutToken: activateDeviceWithoutToken, - addDeviceComponent: addDeviceComponent, - submitData: submitData, - deleteDevice: deleteDevice, - deleteDeviceComponent: deleteDeviceComponent, - getDeviceTags: getDeviceTags, - getDeviceAttributes: getDeviceAttributes, - countDevices: countDevices, - searchDevices: searchDevices -}; diff --git a/tests/lib/helpers/errors.js b/tests/lib/helpers/errors.js deleted file mode 100644 index 471435e6..00000000 --- a/tests/lib/helpers/errors.js +++ /dev/null @@ -1,233 +0,0 @@ -/** - * Copyright (c) 2020 Intel Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -'use strict'; - -module.exports = { - Generic: { - InvalidRequest: {code: 400, status: 400, message: "Invalid request"}, - NotAuthorized: {code: 401, status: 401, message: "Not Authorized"}, - RateLimit: {code: 429, status: 429, message: "Too many requests"}, - InternalServerError: {code: 500, status: 500, message: "Internal Server Error"}, - AnalyticsError: {code: 999, status: 502, message: "Error contacting backend service"} - }, - Device: { - InvalidData: {code: 1400, status: 400, message: "Device has some invalid data"}, - NotFound: {code: 1404, status: 404, message: "Device not found in IoT cloud. Try initializing and activating the device once again."}, - AlreadyExists: {code: 1409, status: 409, message: "Device already exists"}, - InvalidActivationCode: {code: 1410, status: 400, message: "Invalid Activation Code"}, - Component: { - AlreadyExists: {code: 1411, status: 409, message: "At least one of Components already exist"}, - NotFound: {code: 1412, status: 404, message: "Component Not Found"}, - TypeNotFound: {code: 1511, status: 404, message: "Component Types Not Found: "}, - IdsNotUnique: {code: 1413, status: 409, message: "Component Ids in provided array are not unique: "}, - DeviceNotActive: {code: 1414, status: 400, message: "Can not add component to not active device"}, - NotExists: {code: 1412, status: 404, message: "Device has no registered components"}, - AddingError: {code: 1501, status: 500, message: "Adding component for device failed"}, - DeleteError: {code: 1502, status: 500, message: "Delete device component failed"} - }, - SavingError: {code: 1500, status: 500, message: "Error Saving Device"}, - ActivationError: {code: 1510, status: 500, message: "Error during activation"}, - RegistrationError: {code: 1513, status: 500, message: "Error during registration"}, - DeletionError: {code: 1512, status: 500, message: "Device deletion failed"} - }, - ComplexCommand: { - AlreadyExists: {code: 1409, status: 409, message: "Complex command with this name already exists"}, - DoesNotExist: {code: 1404, status: 404, message: "Complex command does not exist"} - }, - User: { - InvalidData: {code: 2400, status: 400, message: "User has some invalid Data"}, - WeakPassword: {code: 2401, status: 400, message: "Password too Weak"}, - EmailNotVerified: {code: 2402, status: 401, message: "User's email not verified"}, - AccountLocked: {code: 2403, status: 403, message: "Account locked"}, - NotFound: {code: 2404, status: 404, message: "User Not Found"}, - TermsAndConditionsError: {code: 2405, status: 400, message: "Terms and Conditions are not accepted"}, - InvalidInteractionToken: {code: 2406, status: 400, message: "Invalid interaction token"}, - AlreadyExists: {code: 2409, status: 409, message: "User already exists"}, - Setting: { - NotFound: {code: 2414, status: 404, message: "User Setting Not Found"}, - AlreadyExists: {code: 2419, status: 409, message: "User setting already exists"}, - SavingError: {code: 2504, status: 500, message: "Error saving settings"} - }, - AlreadyInvited: {code: 2420, status: 409, message: "User is already invited"}, - SavingError: {code: 2500, status: 500, message: "Error Saving User"}, - CannotSendActivationEmail: {code: 2501, status: 500, message: "Could not send activation email"}, - SavingErrorAA: {code: 2502, status: 500, message: "Error Saving User"}, - DeleteErrorAA: {code: 2502, status: 500, message: "Error deleting user"}, - CannotReduceAdminPrivileges: {code: 2503, status: 500, message: "Admin privileges cannot be reduced"}, - Activation: { - CannotUpdate: {code: 2600, status: 500, message: "Could not activate user"}, - FindByEmailError: {code: 2601, status: 500, message: "Could not activate user"}, - TokenError: {code: 2602, status: 500, message: "Could not activate user"} - }, - CannotRemove: { - IsOnlyAdmin: {code:2421, status: 403, message: "User cannot be removed, he is the only admin for some accounts" } - }, - SocialLoginNotConfigured: {code:2422, status: 404, message: "Social login configuration not provided"} - }, - Account: { - InvalidData: {code: 3400, status: 400, message: "Account has some invalid data"}, - CannotChangeTrackSensor: {code: 3401, status: 400, message: "Cannot modify settings.trackSensorHealth"}, - NotFound: {code: 3404, status: 404, message: "Account not found"}, - AlreadyExists: {code: 3409, status: 409, message: "Account already exists"}, - SavingError: {code: 3500, status: 500, message: "Error saving Account"}, - SavingErrorAddOrUpdate: {code: 3510, status: 500, message: "Error saving Account"}, - DeletionError: {code: 3511, status: 500, message: "Error deleting Account locally"}, - DeletionErrorAA: {code: 3512, status: 500, message: "Error deleting Account on AA Proxy"}, - MaximumAccountsLimitReached: {code: 3513, status: 400, message: "User has reached maximum amount of accounts"}, - LeavingError : { - IsSoleAdminForAccount :{ code: 3601, status: 401, message: "Could not leave Account"} - } - }, - Group: { - SavingError: {code: 4500, status: 500, message: "Error saving Group"} - }, - Component: { - InvalidData: {code: 5400, status: 400, message: "Component has some invalid data"}, - NotFound: {code: 5404, status: 404, message: "Component not found"}, - AlreadyExists: {code: 5409, status: 409, message: "Component already exists"}, - SearchProcessingError: {code: 5410, status: 400, message: "Error processing search criteria"}, - InvalidParameterName: {code: 5411, status: 400, message: "Invalid parameter name"}, - InvalidParameterValues: {code: 5412, status: 400, message: "Invalid parameter values"} - }, - Data: { - InvalidData: {code: 6400, status: 400, message: "Invalid data for Target Filter"}, - PartialDataProcessed: {code: 6402, status: 404, message: "Only part of the data has been submitted successfully"}, - FormatError: {code: 6500, status: 500, message: "Format not accepted"}, - OffsetAndLimitBothOrNoneRequired:{code:6504, status:404, message:"offset and limit must be specified both or none"}, - WrongResponseCodeFromAA: {code: 6506, status: 500, message: "Could not send data."}, - SubmissionError: {code: 6505, status: 500, message: "Could not send data."}, - SendByEmail: { - NoRecipientsProvided: {code: 6401, status: 400, message: "No email recipients were provided."} - } - }, - Rule: { - InvalidData: {code: 7400, status: 400, message: "Rule has some invalid data"}, - PropertyMissing : {code: 7401, status: 401, message:"Please select at least one characteristic - name, tag or property."}, - NotFound: {code: 7404, status: 404, message: "Rule not found"}, - AlreadyExists: {code: 7409, status: 404, message: "Rule already exists"}, - NotFoundFromProxy: {code: 7444, status: 404, message: "Rule not found"}, - InternalError: { - SavingError: {code: 7550, status: 500, message: "Error saving rule"}, - UpdatingError: {code: 7553, status: 500, message: "Error updating rule"}, - SavingNonDraftError: {code: 7554, status: 500, message: "Error saving rule. Saving rule other then draft is forbidden"}, - // error getting drafted rules - GettingDraftedError: {code: 7556, status: 500, message: "Internal server error"} - }, - // error getting drafted rules - DeletionError: {code: 7557, status: 500, message: "Cannot delete draft rule"}, - // error deleting rule - ActivatedRuleDeletionError: {code: 7558, status: 500, message: "Cannot delete rule"}, - // error as developer tried to use this API for a drafted rule - CannotUseAPI: {code: 7600, status: 400, message: "Cannot use this API for updating a drafted rule"}, - InvalidSynchronizationStatus: {code: 7402, status: 400, message: "Invalid rule synchronization status"}, - Validation : { - PopulationItemRequired: {code: 7710, status: 401, message:"At least one population item is required: name, ids, tags or attributes"}, - ConditionsOperatorRequired: {code: 7711, status: 401,message:"Conditions operator is required if more than one conditions values are sent"}, - ChangeDetection:{ - ConditionsNumberExceeded:{code: 7712, status: 401, - message:"Automatic change detection must be on the only condition in the condition set when used"}, - InvalidResetType:{code: 7713, status: 401,message:"Automatic change detection supports manual reset only"}, - BadOperator:{code: 7714, status: 401,message:"Automatic change detection takes only Equal operator"}, - ValuesNumberExceeded:{code: 7715, status: 401,message:"Automatic change detection takes only one value'"}, - InvalidValue:{code: 7716, status: 401,message:"Automatic change detection takes the following value: High, Medium or Low"} - }, - TimeLimitRequired:{code: 7717, status: 401,message:"Timebased conditions take timeLimit parameter as required"}, - NonNumericMeasures: { - InvalidCondition: {code: 7718, status: 401,message: "Conditions on non-numeric measures may only be of Basic condition or Timebased condition"}, - InvalidOperator:{code: 7719, status: 401,message:"Conditions on a non-numeric measure can use the Equal, Not Equal and Like operators"} - }, - NumericMeasures:{ - InvalidOperator:{code: 7720, status: 401, - message:"Conditions on a numeric measure can use the >, >=, <, <=, Equal, Not Equal, Between and Not Between operators"} - }, - MultipleValues:{ - InvalidOperator:{code: 7721, status: 401, - message:"Multiple Values are only supported by the Equal, Not Equal, Like, Between and Not Between operators"} - }, - BetweenOperators:{ - TwoValuesExpected:{code: 7722, status: 401,message:'Conditions with "Between" or "Not Between" operator is expected to have 2 values'} - }, - Statistics:{ - BaseLineSecondsBackRequired:{code: 7723, status: 401, - message:"Statistics Based Conditions take baselineSecondsBack parameter as required"}, - GtPositiveValueExpected:{code: 7724, status: 401, - message:'It is expected that for ">" or ">=" operators a positive value be sent when using Statistics Based Conditions'}, - BetweenNegativeValueExpected:{code: 7725, status: 401, - message:'It is expected that for "Between" or "Not Between" operators a negative value be sent when using Statistics Based Conditions'}, - EqualityOperatorsNotSupported:{code: 7726, status: 401, - message:"All operators except Equal, Not Equal can be used with Statistics Based Conditions"}, - BaseLineCalculationLevelRequired:{code: 7727, status: 401, - message:"Statistics Based Conditions take baselineCalculationLevel parameter as required"}, - LtNegativeValueExpected:{code: 7728, status: 401, - message:'It is expected that for "<" or "<=" operators a negative value be sent when using Statistics Based Conditions'}, - BaseLineMinimalInstancesRequired:{code: 7729, status: 401, - message:"Statistics Based Conditions take baselineMinimalInstances parameter as required"}, - BetweenPositiveValueExpected:{code: 7726, status: 401, - message:'It is expected that for "Between" or "Not Between" operators a positive value be sent when using Statistics Based Conditions'} - }, - DeviceComponents:{ - NotFound: {code: 7731, status: 404,message:"One device for rule has no components"}, - NotInDevice: {code: 7732, status: 404,message:"One of components is not in list of devices"}, - NotUsed: {code: 7730, status: 404, message: "One of devices is not used in the rule"} - } - } - }, - Alert: { - RuleNotFound: {code: 8401, status: 400, message: "Rule associated to this alert was not found"}, - AccountNotFound: {code: 8402, status: 400, message: "Account associated to this alert was not found"}, - DeviceNotFound: {code: 8403, status: 400, message: "Device associated to this alert was not found"}, - NotFound: {code: 8404, status: 404, message: "Alert not found"}, - WrongAlertStatus: {code:8405, status: 400, message: "Wrong alert status"}, - RuleNotActive: {code:8406, status: 400, message: "Rule is not active."}, - AlreadyExists: {code: 8409, status: 409, message: "Alert already Exists"}, //Duplicate Alert - SavingErrorAA: {code: 8500, status: 500, message: "Error saving Alert"}, //Error saving in Advanced Analytics Backend - SavingError: {code: 8501, status: 500, message: "Error saving Alert"}, //Error saving locally - SavingErrorComments: {code: 8502, status: 500, message: "Error saving Alert Comments"} //Error saving locally - }, - ComponentCommands: { - InvalidFilter: {code: 9400, status: 400, message: "Invalid Components Filter"}, - NotFound: {code: 9404, status: 404, message: "Component not found"}, - InvalidValue: {code: 9600, status: 400, message: "Invalid value"} - }, - SensorHealth:{ - ComponentIdOrDeviceIdRequired:{code:10404, status:404,message:"At least one component ID or device ID is required."} - }, - InteractionToken: { - NotFound: {code: 11404, status: 404, message: "Interaction token not found"} - }, - Actuation: { - SearchError: {code: 12500, status: 500, message: "Error searching actuation commands."}, - SavingError: {code: 12501, status: 500, message: "Error saving actuation command."}, - DeviceNotFound: {code: 12404, status: 404, message: "Device not found in IoT cloud."} - }, - Captcha: { - InvalidCaptcha: {code: 13422, status: 422, message: "Invalid captcha"}, - MissingCaptcha: {code: 13423, status: 422, message: "Missing 'challenge' and 'response' fields"} - }, - Time: { - DateReceiveError: {code: 14500, status: 500, message: "Did not received date from system."} - }, - Invite: { - NotFound: {code:10404, status: 404, message: "Invitation not found"}, - DeleteError: {code:10500, status: 500, message: "Invitation deletion failed"} - }, - RefreshToken: { - RefreshError: {code: 15000, status: 500, message: "Error Refreshing Access Token"}, - ExpireError: {code: 15001, status: 401, message: "Refresh token has expired"}, - InvalidToken: {code: 15001, status: 401, message: "Refresh token does not exist"} - }, -}; diff --git a/tests/lib/helpers/index.js b/tests/lib/helpers/index.js deleted file mode 100644 index 4a8eb4c4..00000000 --- a/tests/lib/helpers/index.js +++ /dev/null @@ -1,39 +0,0 @@ -/** - * Copyright (c) 2017 Intel Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -"use strict"; - -//------------------------------------------------------------------------------------------------------- -// Helper Functions -//------------------------------------------------------------------------------------------------------- - -module.exports = { - auth: require('./auth'), - accounts: require('./accounts'), - devices: require('./devices'), - users: require('./users'), - control: require('./control'), - alerts: require('./alerts'), - data: require('./data'), - connector: require('./connector'), - rules: require('./rules'), - cmpcatalog: require('./cmpcatalog'), - invitation: require('./invitation'), - mail: require('./mail'), - mqtt: require('./mqtt'), - errors: require('./errors') -}; diff --git a/tests/lib/helpers/invitation.js b/tests/lib/helpers/invitation.js deleted file mode 100644 index 6f3a34fa..00000000 --- a/tests/lib/helpers/invitation.js +++ /dev/null @@ -1,139 +0,0 @@ -/** - * Copyright (c) 2017 Intel Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -"use strict"; - -var chai = require('chai'); -var assert = chai.assert; - -var config = require("../../test-config.json"); -var oispSdk = require("@open-iot-service-platform/oisp-sdk-js"); -var api = oispSdk(config).api.rest; - - -function createInvitation(userToken, accountId, receiveremail, cb){ - if (!cb) { - throw "Callback required"; - } - - var data = { - userToken: userToken, - accountId: accountId, - body: { - email: receiveremail - } - }; - - api.invitation.createInvitation(data, function(err, response) { - assert.notEqual(response, null, 'response is null'); - if (err) { - cb(err); - } else { - cb(null, response); - } - }); -} - - -function getAllInvitations(userToken, accountId, cb){ - if (!cb) { - throw "Callback required"; - } - - var data = { - userToken: userToken, - accountId: accountId - }; - - api.invitation.getAllInvitations(data, function(err, response) { - assert.notEqual(response, null, 'response is null'); - if (err) { - cb(err); - } else { - cb(null, response); - } - }); -} - -function getInvitations(userToken, accountId, email, cb){ - if (!cb) { - throw "Callback required"; - } - - var data = { - userToken: userToken, - accountId: accountId, - email: email - }; - - api.invitation.getInvitations(data, function(err, response) { - if (err) { - cb(err); - } else { - cb(null, response); - } - }); -} - -function acceptInvitation(userToken, accountId, inviteId, cb){ - if (!cb) { - throw "Callback required"; - } - - var data = { - userToken: userToken, - accountId: accountId, - inviteId: inviteId, - body: { - accept: true - } - }; - - api.invitation.acceptInvitation(data, function(err, response) { - if (err) { - cb(err); - } else { - cb(null, response); - } - }); -} - -function deleteInvitations(userToken, accountId, receiveremail, cb){ - if (!cb) { - throw "Callback required"; - } - - var data = { - userToken: userToken, - accountId: accountId, - email: receiveremail - }; - - api.invitation.deleteInvitations(data, function(err, response) { - if (err) { - cb(err); - } else { - cb(null, response); - } - }); -} - -module.exports={ - createInvitation: createInvitation, - getAllInvitations: getAllInvitations, - getInvitations: getInvitations, - acceptInvitation: acceptInvitation, - deleteInvitations: deleteInvitations -}; diff --git a/tests/lib/helpers/mail.js b/tests/lib/helpers/mail.js deleted file mode 100644 index c27f864d..00000000 --- a/tests/lib/helpers/mail.js +++ /dev/null @@ -1,59 +0,0 @@ -/** - * Copyright (c) 2017-2019 Intel Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -"use strict"; - -//------------------------------------------------------------------------------------------------------- -// Helper Functions -//----------------------------------p--------------------------------------------------------------------- - -// This module reads mails from a local fake-smtp-server -// See https://www.npmjs.com/package/fake-smtp-server - -var request = require("sync-request"); - -const MAIL_URL="http://localhost:1080/api/emails"; - - -function waitForNewEmail(num, to, done, timeout = 5000) { - var mails = []; - var startTime = new Date().getTime(); - var mailFilter = function(mail) { - return mail.to.value.address === to; - }; - while (mails.length < num) { - var currTime = new Date().getTime(); - if (currTime - startTime >= timeout) { - return done(new Error("Timeout waiting for emails at email index: " + mails.length), + ", expected " + num + " emails"); - } - mails = JSON.parse(request("GET", MAIL_URL).getBody("utf-8"), { socketTimeout: timeout, timeout: timeout }); - if (to != null) { - mails = mails.filter(mailFilter); - } - } -} - -function getAllEmailMessages(to=null, timeout = 60 * 1000) { - var mails = JSON.parse(request("GET", MAIL_URL).getBody("utf-8"), { socketTimeout: timeout, timeout: timeout }); - if (to != null) { - mails = mails.filter(mail => mail.to.text === to); - } - return mails.map(mail => mail.text.replace("<", "<").replace(">", ">")); -} - -module.exports ={ - getAllEmailMessages: getAllEmailMessages, - waitForNewEmail: waitForNewEmail -}; diff --git a/tests/lib/helpers/mqtt.js b/tests/lib/helpers/mqtt.js deleted file mode 100644 index a5a230aa..00000000 --- a/tests/lib/helpers/mqtt.js +++ /dev/null @@ -1,175 +0,0 @@ -/** - * Copyright (c) 2019 Intel Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -"use strict"; - -//------------------------------------------------------------------------------------------------------- -// Helper Functions -//------------------------------------------------------------------------------------------------------- - -var mqtt = require('mqtt'); -var config = require("../../test-config-mqtt.json"); - -function setCredential(connector, deviceToken, deviceId, cb) { - if (!cb) { - throw "Callback required"; - } - - connector.setCredential(deviceId, deviceToken); - cb(null, "OK"); -} - -function submitData(connector, value, deviceToken, accountId, deviceId, cid, cb) { - if (!cb) { - throw "Callback required"; - } - var ts = new Date().getTime(); - - var data = { - deviceId: deviceId, - body: { - accountId: accountId, - on: ts, - data: [{ - componentId: cid, - value: Buffer.isBuffer(value.value) ? value.value : value.value.toString(), - on: value.ts - }] - } - }; - - //the next few lines are needed as workaround to work with current sdk - //once SDK has been updated this can be removed ... - data.convertToMQTTPayload = function(){ - delete this.convertToMQTTPayload; - return this; - }; - data.did = data.deviceId; - data.accountId = data.body.accountId; - // ...until here - - connector.data(data, function(err, response) { - if (err) { - cb(err); - } else { - if (response) { - cb(null, response); - } - } - }); -} - -function submitDataList(connector, valueList, deviceToken, accountId, deviceId, cidList, cb) { - if (!cb) { - throw "Callback required"; - } - - var data = { - userToken: deviceToken, - deviceId: deviceId, - body: { - accountId: accountId, - on: valueList[0].ts, - data: [] - } - }; - - valueList.forEach(function(element){ - var toPush = { - componentId: cidList[element.component], - value: (typeof element.value === 'string' || Buffer.isBuffer(element.value)) ? element.value : element.value.toString(), - on: element.ts - }; - if (element.loc) { - toPush.loc = element.loc; - } - if (element.attributes !== undefined){ - toPush.attributes = element.attributes; - } - data.body.data.push(toPush); - }); - //the next few lines are needed as workaround to work with current sdk - //once SDK has been updated this can be removed ... - data.convertToMQTTPayload = function(){ - delete this.convertToMQTTPayload; - return this; - }; - data.did = data.deviceId; - data.accountId = data.body.accountId; - // ...until here - - connector.data(data, function(err, response) { - if (err) { - cb(err); - } else { - if (response) { - cb(null, response); - } - } - }); -} - -var clients = {}; - -function closeMqttConnection(deviceId) { - clients[deviceId].end(); - clients[deviceId] = null; -} - -function openMqttConnection(deviceToken, deviceId, topics, cbManager, cb, address, options) { - if (clients[deviceId]) { - closeMqttConnection(deviceId); - } - - if (!options) { - options = {}; - } - options.username = deviceId; - options.password = deviceToken; - if (!address) { - address = config.connector.mqtt.host + ":" + config.connector.mqtt.port; - if (config.connector.mqtt.secure) { - address = "mqtts://" + address; - options.rejectUnauthorized = false; - } else { - address = "mqtt://" + address; - } - } - - var client = mqtt.connect(address, options); - client.on('connect', function() { - client.subscribe(topics, function(err, t) { - if (err) { - cb(err); - return; - } - cb(); - }); - }); - - client.on('message', function(topic, message) { - cbManager.cb(message, topic); - }); - - clients[deviceId] = client; -} - -module.exports={ - openMqttConnection: openMqttConnection, - closeMqttConnection: closeMqttConnection, - setCredential: setCredential, - submitData: submitData, - submitDataList: submitDataList -}; diff --git a/tests/lib/helpers/rules.js b/tests/lib/helpers/rules.js deleted file mode 100644 index fc5e0604..00000000 --- a/tests/lib/helpers/rules.js +++ /dev/null @@ -1,477 +0,0 @@ -/** - * Copyright (c) 2017 Intel Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -"use strict"; - -//------------------------------------------------------------------------------------------------------- -// Helper Functions -//------------------------------------------------------------------------------------------------------- -var config = require("../../test-config.json"); -var oispSdk = require("@open-iot-service-platform/oisp-sdk-js"); -var api = oispSdk(config).api.rest; - - -function getRules(userToken, accountId, cb) { - if (!cb) { - throw "Callback required"; - } - var data = { - userToken: userToken, - accountId: accountId - }; - - api.rules.getRules(data, function(err, response) { - if (err) { - cb(err); - } else { - cb(null,response); - } - }); -} - -function getRuleDetails(userToken, accountId, ruleId, cb) { - if (!cb) { - throw "Callback required"; - } - var data = { - userToken: userToken, - accountId: accountId, - ruleId: ruleId - }; - - api.rules.getRuleDetails(data, function(err, response) { - if (err) { - cb(err); - } else { - if ( response.id === ruleId ) { - { - cb(null, response.synchronizationStatus === "Sync" ? true : false); - } - } - else { - cb("rule "+ruleId + " not found "); - } - } - }); -} - -function createRule(ruleConfig, userToken, accountId, deviceId, resetType, cb) { - if (!cb) { - throw "Callback required"; - } - - var data = { - userToken: userToken, - accountId: accountId, - - body: { - name: ruleConfig.name, - description: "OISP testing rule", - priority: "Medium", - type: "Regular", - status: "Active", - resetType: resetType, - synchronizationStatus: "NotSync", - - actions: ruleConfig.actions, - - population: { - ids: [deviceId], - attributes: null, - tags: null - }, - - conditions: { - operator: "OR", - values: [{ - component: { - dataType: "Number", - name: ruleConfig.conditionComponent, - cid: ruleConfig.cid - }, - type: "basic", - values: [ruleConfig.basicConditionValue.toString()], - operator: ruleConfig.basicConditionOperator - }] - } - } - }; - - - api.rules.createRule(data, function(err, response) { - if (err) { - cb(err); - } else { - var ruleId = response.id; - var syncInterval = setInterval( function() { - getRuleDetails(userToken, accountId, ruleId, function(err, status) { - if (err) { - clearInterval(syncInterval); - cb(err); - } - else { - if ( status === true ) { - clearInterval(syncInterval); - cb(null, ruleId); - } - } - }); - }, 500); - } - }); - -} - -function createStatisticRule(ruleConfig, userToken, accountId, deviceId, cb) { - if (!cb) { - throw "Callback required"; - } - - var data = { - userToken: userToken, - accountId: accountId, - - body: { - name: ruleConfig.name, - description: "OISP testing rule", - priority: "Medium", - type: "Regular", - status: "Active", - resetType: "Automatic", - synchronizationStatus: "NotSync", - - actions: ruleConfig.actions, - - population: { - ids: [deviceId], - attributes: null, - tags: null - }, - - conditions: { - operator: "OR", - values: [{ - component: { - dataType: "Number", - name: ruleConfig.conditionComponent, - cid: ruleConfig.cid - }, - type: "statistics", - values: [ruleConfig.statisticConditionValue.toString()], - operator: ruleConfig.statisticConditionOperator, - baselineCalculationLevel: "Device level", - baselineMinimalInstances: ruleConfig.statisticMinimalInstances, - baselineSecondsBack: ruleConfig.statisticSecondsBack - }] - } - } - }; - - api.rules.createRule(data, function(err, response) { - if (err) { - cb(err); - } else { - var ruleId = response.id; - var syncInterval = setInterval( function() { - getRuleDetails(userToken, accountId, ruleId, function(err, status) { - if (err) { - clearInterval(syncInterval); - cb(err); - } - else { - if ( status === true ) { - clearInterval(syncInterval); - cb(null, ruleId); - } - } - }); - }, 500); - - } - }); - -} - - -function createTbRule(ruleConfig, userToken, accountId, deviceId, cb) { - if (!cb) { - throw "Callback required"; - } - - var data = { - userToken: userToken, - accountId: accountId, - - body: { - name: ruleConfig.name, - description: "TB OISP testing rule", - priority: "Medium", - type: "Regular", - status: "Active", - resetType: "Automatic", - synchronizationStatus: "NotSync", - - actions: ruleConfig.actions, - - population: { - ids: [deviceId], - attributes: null, - tags: null - }, - - conditions: { - operator: "OR", - values: [{ - component: { - dataType: "Number", - name: ruleConfig.tbComponent, - cid: ruleConfig.cid - }, - type: "time", - values: [ruleConfig.tbConditionValue.toString()], - operator: ruleConfig.tbConditionOperator, - timeLimit: ruleConfig.tbTimelimit, - }] - } - } - }; - - api.rules.createRule(data, function(err, response) { - if (err) { - cb(err); - } else { - var ruleId = response.id; - var syncInterval = setInterval(function() { - getRuleDetails(userToken, accountId, ruleId, function(err, status) { - if (err) { - clearInterval(syncInterval); - cb(err); - } - else { - if ( status === true ) { - clearInterval(syncInterval); - cb(null, ruleId); - } - } - }); - }, 500); - } - }); -} - -function updateRule(ruleConfig, userToken, accountId, ruleId, cb) { - if (!cb) { - throw "Callback required"; - } - - var data = { - userToken: userToken, - accountId: accountId, - ruleId: ruleId, - body: { - name: ruleConfig.name, - description: "OISP testing rule new", - priority: "Medium", - type: "Regular", - status: "Active", - resetType: "Automatic", - synchronizationStatus: ruleConfig.synchronizationStatus, - - actions: [{ - type: "actuation", - target: [ - ruleConfig.actuationCmd - ] - }], - - - population: { - ids: ['00-11-22-33-44-55'], - attributes: null, - tags: null - }, - - conditions: { - operator: "OR", - values: [{ - component: { - dataType: "Number", - name: ruleConfig.conditionComponent, - cid: ruleConfig.cid - }, - type: "basic", - values: [ruleConfig.basicConditionValue.toString()], - operator: ruleConfig.basicConditionOperator - }] - } - } - }; - - - api.rules.updateRule(data, function(err, response) { - if (err) { - cb(err); - } else { - cb(null,response); - } - }); -} - - -function updateRuleStatus(userToken, accountId, ruleId, status, cb) { - if (!cb) { - throw "Callback required"; - } - - var data = { - userToken: userToken, - accountId: accountId, - ruleId: ruleId, - body:{ - status:status - } - }; - - api.rules.updateRuleStatus(data, function(err, response) { - if (err) { - cb(err, null); - } - else { - cb(null,response); - } - }); -} - - -function createDraftRule (draftname, userToken, accountId, cb) { - if (!cb) { - throw "Callback required"; - } - - var data = { - userToken: userToken, - accountId: accountId, - - body: { - priority: null, - type: null, - resetType: null, - name: draftname, - synchronizationStatus: "NotSync", - - actions:[{ - type:"mail", - target:[] - }], - population:{ - name:null, - ids:[], - tags:[], - attributes:null - }, - conditions: { - operator: null, - values: [] - } - } - }; - - api.rules.createDraftRule(data, function(err, response) { - if (err) { - cb(err); - } else { - cb(null, response); - } - }); - -} - - -function cloneRule (userToken, accountId, ruleId , cb) { - if (!cb) { - throw "Callback required"; - } - - var data = { - userToken: userToken, - accountId: accountId, - ruleId: ruleId - }; - - api.rules.cloneRule(data, function(err, response) { - if (err) { - cb(err); - } else { - cb(null, response); - } - }); - -} - -function deleteDraftRule (userToken, accountId,ruleId , cb) { - if (!cb) { - throw "Callback required"; - } - - var data = { - userToken: userToken, - accountId: accountId, - ruleId: ruleId - }; - - api.rules.deleteDraftRule(data, function(err, response) { - if (err) { - cb(err); - } else { - cb(null, response); - } - }); - -} - -function deleteRule (userToken, accountId,ruleId , cb) { - if (!cb) { - throw "Callback required"; - } - - var data = { - userToken: userToken, - accountId: accountId, - ruleId: ruleId - }; - - api.rules.deleteRule(data, function(err, response) { - if (err) { - cb(err); - } else { - cb(null, response); - } - }); - -} - -module.exports={ - createRule:createRule, - createStatisticRule:createStatisticRule, - createTbRule:createTbRule, - getRules: getRules, - getRuleDetails: getRuleDetails, - updateRule: updateRule, - updateRuleStatus: updateRuleStatus, - createDraftRule: createDraftRule, - cloneRule: cloneRule, - deleteDraftRule: deleteDraftRule, - deleteRule: deleteRule -}; diff --git a/tests/lib/helpers/users.js b/tests/lib/helpers/users.js deleted file mode 100644 index c8839899..00000000 --- a/tests/lib/helpers/users.js +++ /dev/null @@ -1,241 +0,0 @@ -/** - * Copyright (c) 2017 Intel Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -"use strict"; - -var chai = require('chai'); -var assert = chai.assert; - -var config = require("../../test-config.json"); -var oispSdk = require("@open-iot-service-platform/oisp-sdk-js"); -var api = oispSdk(config).api.rest; - - -function addUser(userToken, email, password, cb) { - if (!cb) { - throw "Callback required"; - } - - var data = { - userToken: userToken, - body: { - email: email, - password: password - } - }; - - api.users.addUser(data, function(err, response) { - if (!err) { - assert.notEqual(response, null, 'response is null'); - cb(null,response); - } - else { - cb(err); - } - }); -} - -function getUserInfo(userToken, userId, cb) { - if (!cb) { - throw "Callback required"; - } - - var data = { - userToken: userToken, - userId: userId - }; - - api.users.getUserInfo(data, function(err, response) { - if (!err) { - assert.notEqual(response, null, 'response is null'); - cb(null,response); - } - else { - cb(err); - } - }); -} - -function updateUserInfo(userToken, userId, userInfo, cb) { - if (!cb) { - throw "Callback required"; - } - - var data = { - userToken: userToken, - userId: userId, - body: userInfo - }; - - api.users.updateUserInfo(data, function(err, response) { - if (!err) { - assert.notEqual(response, null, 'response is null'); - cb(null,response); - } - else { - cb(err); - } - }); -} - -function requestUserPasswordChange(username, cb) { - if (!cb) { - throw "Callback required"; - } - - var data = { - body: { - "email":username - } - }; - - api.users.requestUserPasswordChange(data, function(err, response) { - if (!err) { - assert.notEqual(response, null, 'response is null'); - cb(null,response); - } - else { - cb(err); - } - }); -} - -function updateUserPassword(token, password, cb) { - if (!cb) { - throw "Callback required"; - } - - var data = { - body:{ - token: token, - password: password - } - }; - - api.users.updateUserPassword(data, function(err, response) { - if (!err) { - assert.notEqual(response, null, 'response is null'); - cb(null,response); - } - else { - cb(err); - } - }); -} - -function changeUserPassword(userToken, username, oldPasswd, newPasswd, cb) { - if (!cb) { - throw "Callback required"; - } - - var data = { - username: username, - userToken: userToken, - body: { - "currentpwd": oldPasswd, - "password": newPasswd - } - }; - - api.users.changeUserPassword(data, function(err, response) { - if (!err) { - assert.notEqual(response, null, 'response is null'); - cb(null,response); - } - else { - cb(err); - } - }); -} - -function requestUserActivation(username, cb) { - if (!cb) { - throw "Callback required"; - } - - var data = { - body:{ - email: username, - } - }; - - api.users.requestUserActivation(data, function(err, response) { - if (!err) { - assert.notEqual(response, null, 'response is null'); - cb(null,response); - } - else { - cb(err); - } - }); -} - -function activateUser(token, cb) { - if (!cb) { - throw "Callback required"; - } - - var data = { - body:{ - token: token - } - }; - - api.users.activateUser(data, function(err, response) { - if (!err) { - assert.notEqual(response, null, 'response is null'); - cb(null,response); - } - else { - cb(err); - } - }); -} - - -function deleteUser(userToken, userId, cb) { - if (!cb) { - throw "Callback required"; - } - - var data = { - userToken: userToken, - deleteUserId: userId - }; - - api.users.deleteUser(data, function(err, response) { - if (!err) { - assert.notEqual(response, null, 'response is null'); - cb(null,response); - } - else { - cb(err); - } - }); -} - -module.exports={ - addUser: addUser, - getUserInfo: getUserInfo, - updateUserInfo: updateUserInfo, - requestUserPasswordChange: requestUserPasswordChange, - updateUserPassword: updateUserPassword, - changeUserPassword: changeUserPassword, - requestUserActivation: requestUserActivation, - activateUser: activateUser, - deleteUser: deleteUser -}; diff --git a/tests/oisp-prep-only.js b/tests/oisp-prep-only.js deleted file mode 100644 index 5ebf3c50..00000000 --- a/tests/oisp-prep-only.js +++ /dev/null @@ -1,191 +0,0 @@ -/** - * Copyright (c) 2017 Intel Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -"use strict"; - -var chai = require('chai'); -var assert = chai.assert; -var colors = require('colors'); // jshint ignore:line -var fs = require('fs'); - -var helpers = require("./lib/helpers"); -var promtests = require('./subtests/promise-wrap'); - - -var accountName = "oisp-tests"; - -var userToken; -var accountId; -var deviceId; -var activationCode; -var userId; -var username = process.env.USERNAME; -var password = process.env.PASSWORD; - -var getNewUserTokens = function(done) { - - return promtests.authGetToken(username, password).then(grant => { - userToken = grant.token; - done(); - }).catch(err => { - done(err); - }); -}; -//------------------------------------------------------------------------------------------------------- -// Tests -//------------------------------------------------------------------------------------------------------- -process.stdout.write("_____________________________________________________________________\n".bold); -process.stdout.write(" \n"); -process.stdout.write(" OISP TEST PREP \n".green.bold); -process.stdout.write("_____________________________________________________________________\n".bold); - -describe("get authorization and manage user ...\n".bold, function() { - before(function(done) { - userToken = null; - accountId = null; - deviceId = "00-11-22-33-44-55"; - done(); - }); - - it('Shall authenticate', function(done) { - var username = process.env.USERNAME; - var password = process.env.PASSWORD; - - assert.isNotEmpty(username, "no username provided"); - assert.isNotEmpty(password, "no password provided"); - - getNewUserTokens(done); - }).timeout(10000); - - it('Shall get token info', function (done) { - helpers.auth.tokenInfo(userToken, function (err, response) { - if (err) { - done(new Error("Cannot get token info: " + err)); - } else { - assert.equal(response.header.typ, 'JWT', 'response type error' ); - if (response.payload.sub == null){ - done(new Error("get null user id")); - } - else { - userId = response.payload.sub; - } - - done(); - } - }); - }); - - it('Shall get user information', function(done) { - helpers.users.getUserInfo(userToken, userId, function(err, response) { - if (err) { - done(new Error("Cannot get user information : " + err)); - } else { - assert.isString(response.id); - done(); - } - }); - }); - - it('Shall update user information', function(done) { - var newuserInfo = { - attributes:{ - "phone":"12366666666", - "another_attribute":"another_value", - "new":"next_string_value" - } - }; - - helpers.users.updateUserInfo(userToken, userId, newuserInfo, function(err, response) { - if (err) { - done(new Error("Cannot update user information : " + err)); - } else { - assert.equal(response.status, 'OK', 'status error'); - done(); - } - }); - }); -}); - -describe("Creating account and device ...\n".bold, function() { - - var accountInfo; - - it('Shall create account', function(done) { - assert.notEqual(userToken, null, "Invalid user token"); - helpers.accounts.createAccount(accountName, userToken, function(err, response) { - if (err) { - done(new Error("Cannot create account: " + err)); - } else { - assert.equal(response.name, accountName, "accounts name is wrong"); - accountId = response.id; - getNewUserTokens(done); - } - }); - }).timeout(10000); - - it('Shall get account info', function (done) { - helpers.accounts.getAccountInfo(accountId, userToken, function (err, response) { - if (err) { - done(new Error("Cannot get account info: " + err)); - } else { - accountInfo = response; - done(); - } - }); - }); - - it('Shall update an account', function (done) { - - accountInfo.attributes = { - "phone":"123456789", - "another_attribute":"another_value", - "new":"next_string_value" - }; - - helpers.accounts.updateAccount(accountId, userToken, accountInfo, function (err, response) { - if (err) { - done(new Error("Cannot update account: " + err)); - } else { - assert.deepEqual(response.attributes, accountInfo.attributes, 'new attributes not being updated'); - done(); - } - }); - }); - - it('Shall get account activation code', function (done) { - - helpers.accounts.getAccountActivationCode(accountId, userToken, function (err, response) { - if (err) { - done(new Error("Cannot get account activation code: " + err)); - } else { - activationCode = response.activationCode; - done(); - } - }); - }); - - it('Shall create prep config', function(done) { - - var prepConf = { - "username": username, - "password": password, - "userToken": userToken, - "accountId": accountId, - "activationCode": activationCode - }; - fs.writeFileSync("oisp-prep-only.conf", JSON.stringify(prepConf)); - done(); - }); -}); diff --git a/tests/oisp-tests.js b/tests/oisp-tests.js deleted file mode 100644 index bd7b73d9..00000000 --- a/tests/oisp-tests.js +++ /dev/null @@ -1,1510 +0,0 @@ -/** - * Copyright (c) 2017 Intel Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -'use strict'; - -const chai = require('chai'); -const assert = chai.assert; -const colors = require('colors'); // jshint ignore:line - -const config = require('./test-config.json'); -const mqttConfig = require('./test-config-mqtt.json'); -const oispSdk = require('@open-iot-service-platform/oisp-sdk-js'); -const proxyConnector = oispSdk(config).lib.proxies.getControlConnector('ws'); -const mqttConnector = oispSdk(mqttConfig).lib.proxies.getProxyConnector('mqtt'); -const helpers = require('./lib/helpers'); -const promtests = require('./subtests/promise-wrap'); -const {Data, Component, Components} = require('./lib/common'); - -const accountName = 'oisp-tests'; -const deviceName = 'oisp-tests-device'; -const gatewayId = "00-11-22-33-44-55"; - -const actuatorName = 'powerswitch-actuator'; -const actuatorType = 'powerswitch.v1.0'; - -const switchOnCmdName = 'switch-on'; -const switchOffCmdName = 'switch-off'; - - -const emailRecipient = 'test.receiver@streammyiot.com'; - -const imap_username = process.env.IMAP_USERNAME; -const imap_password = process.env.IMAP_PASSWORD; - -const BACKEND_DELAY = 5000; -const BACKEND_TIMEOUT = 12000; -const GENERIC_TIMEOUT = 15000; -const TIMEOUT_FACTOR = 2; -// Use this to keep track of received mails and wait for new ones -// instead of deleting old mails -let nr_mails = helpers.mail.getAllEmailMessages().length; - -// @description Checks whether variables are set. returns true if one of the -// variables are set -// @params skipifset []string array of case names in test-config.json under skip. -// The last one set to "true" or "false" preceeds, so the order should be from general -// to specific. -const checkTestCondition = function(skipifset) { - let found = false; - skipifset.forEach(function(caseName) { - if (config.skip[caseName] === 'true') { - found = true; - } else if (config.skip[caseName] === 'false') { - found = false; - } else if (config.skip[caseName] !== '') { - console.error('config.skip.' + caseName + ' must be "true", "false" or ""'); - process.exit(1); - } - }); - return found; -}; - -function boolData() { - const data = [ - new Data('1', null, null), - new Data('0', null, null), - new Data('1', null, null), - ]; - return data; -} - -function boolCheckData(sentData, receivedData) { - var i = 0; - if ( sentData.length === receivedData.length) { - for (i = 0; i < sentData.length; i++) { - if (sentData[i].ts === receivedData[i].ts && sentData[i].value === receivedData[i].value) { - sentData[i].ts = null; - } - } - } - - let err = null; - for (i = 0; i < sentData.length; i++) { - if (sentData[i].ts !== null) { - err += '[' + i + ']=' + sentData[i].value + ' '; - } - } - if (err) { - err = 'Got wrong data for ' + err; - } - return err; -} - -function stringData() { - const data = [ - new Data('{}', null, null), - new Data('{value: "hello world"}', null, null), - new Data('{meta: "Camera1", enabled: true, numObjects: 23, calibration: 1.4}', null, null), - ]; - return data; -} - -function stringCheckData(sentData, receivedData) { - var i = 0; - if ( sentData.length === receivedData.length) { - for (i = 0; i < sentData.length; i++) { - if (sentData[i].ts === receivedData[i].ts && sentData[i].value === receivedData[i].value) { - sentData[i].ts = null; - } - } - } - - let err = null; - for (i = 0; i < sentData.length; i++) { - if (sentData[i].ts !== null) { - err += '[' + i + ']=' + sentData[i].value + ' '; - } - } - if (err) { - err = 'Got wrong data for ' + err; - } - return err; -} - -function temperatureData(componentName) { - const data = [ - new Data(-15, true, componentName + ' <= 15'), - new Data( -5, true, componentName + ' <= 15'), - new Data( 5, true, componentName + ' <= 15'), - new Data( 15, true, componentName + ' <= 15'), - new Data( 25, null, null), - new Data( 30, false, componentName + ' > 25'), - new Data( 20, null, null), - new Data( 14, true, componentName + ' <= 15'), - new Data( 20, null, null), - new Data( 28, false, componentName + ' > 25'), - ]; - - return data; -} - -function temperatureCheckData(sentData, receivedData) { - var i = 0; - if ( sentData.length === receivedData.length) { - for (i = 0; i < sentData.length; i++) { - if (sentData[i].ts === receivedData[i].ts && sentData[i].value === receivedData[i].value) { - sentData[i].ts = null; - } - } - } - - let err = null; - for (i = 0; i < sentData.length; i++) { - if (sentData[i].ts !== null) { - err += '[' + i + ']=' + sentData[i].value + ' '; - } - } - if (err) { - err = 'Got wrong data for ' + err; - } - - return err; -} - -// ------------------------------------------------------------------------------------------------------- -// Components -// ------------------------------------------------------------------------------------------------------- -const components = new Components(); - -components.add( new Component('temperatures', 'Number', 'float', 'Degress Celsius', 'timeSeries', -150, 150, - [], - temperatureData, temperatureCheckData), -); - -components.add(new Component('metaData', 'String', 'JSON', 'text', 'binaryDataRenderer', null, null, - [], - stringData, stringCheckData), -); - -components.add(new Component('binaryState', 'Boolean', 'state', 'bool', 'timeSeries', null, null, - [], - boolData, boolCheckData), -); - -// ------------------------------------------------------------------------------------------------------- -// Tests -// ------------------------------------------------------------------------------------------------------- -let userToken; -let userToken2; -let receiverToken; -let receiveruserId; -let receiveraccountId; -let userId; -let userId2; -let accountId; -let deviceId; -let deviceToken; -let actuatorId; -let componentParamName; -let firstObservationTime; - -const getNewUserTokens = function(done) { - const username = process.env.USERNAME; - const password = process.env.PASSWORD; - const username2 = process.env.USERNAME2; - const password2 = process.env.PASSWORD2; - return promtests.authGetToken(username, password).then((grant) => { - userToken = grant.token; - return promtests.authGetToken(username2, password2); - }).then((grant) => { - userToken2 = grant.token; - done(); - }).catch((err) => { - done(err); - }); -}; - -process.stdout.write('_____________________________________________________________________\n'.bold); -process.stdout.write(' \n'); -process.stdout.write(' OISP E2E TESTING \n'.green.bold); -process.stdout.write('_____________________________________________________________________\n'.bold); - -const CbManager = function() { - let mqttCB = () => {}; - return { - cb: function(message) { - mqttCB(message); - }, - set: function(newCB) { - mqttCB = newCB; - }, - }; -}; - -// Callback for WSS -const cbManager = new CbManager(); - -describe('get authorization and manage user ...\n'.bold, function() { - before(function(done) { - userToken = null; - userToken2 = null; - accountId = null; - deviceId = '00-11-22-33-44-55'; - deviceToken = null; - actuatorId = null; - componentParamName = 'LED'; - firstObservationTime = null; - - done(); - }); - it('Shall authenticate', function(done) { - const username = process.env.USERNAME; - const password = process.env.PASSWORD; - - const username2 = process.env.USERNAME2; - const password2 = process.env.PASSWORD2; - - assert.isNotEmpty(username, 'no username provided'); - assert.isNotEmpty(password, 'no password provided'); - assert.isNotEmpty(username2, 'no username2 provided'); - assert.isNotEmpty(password2, 'no password2 provided'); - - getNewUserTokens(done); - }).timeout(10000); - - it('Shall get token info', function(done) { - helpers.auth.tokenInfo(userToken, function(err, response) { - if (err) { - done(new Error('Cannot get token info: ' + err)); - } else { - assert.equal(response.header.typ, 'JWT', 'response type error' ); - if (response.payload.sub == null) { - done(new Error('get null user id')); - } else { - userId = response.payload.sub; - } - helpers.auth.tokenInfo(userToken2, function(err, response) { - if (err) { - return done(err); - } - userId2 = response.payload.sub; - done(); - }); - } - }); - }); - - it('Shall get user information', function(done) { - helpers.users.getUserInfo(userToken, userId, function(err, response) { - if (err) { - done(new Error('Cannot get user information : ' + err)); - } else { - assert.isString(response.id); - done(); - } - }); - }); - - it('Shall update user information', function(done) { - const newuserInfo = { - attributes: { - 'phone': '12366666666', - 'another_attribute': 'another_value', - 'new': 'next_string_value', - }, - }; - - helpers.users.updateUserInfo(userToken, userId, newuserInfo, function(err, response) { - if (err) { - done(new Error('Cannot update user information : ' + err)); - } else { - assert.equal(response.status, 'OK', 'status error'); - done(); - } - }); - }); -}); - -describe('Creating account and device ...\n'.bold, function() { - let accountInfo; - - it('Shall create account', function(done) { - assert.notEqual(userToken, null, 'Invalid user token'); - helpers.accounts.createAccount(accountName, userToken, function(err, response) { - if (err) { - done(new Error('Cannot create account: ' + err)); - } else { - assert.equal(response.name, accountName, 'accounts name is wrong'); - accountId = response.id; - getNewUserTokens(done); - } - }); - }).timeout(15000); - - it('Shall get account info', function(done) { - helpers.accounts.getAccountInfo(accountId, userToken, function(err, response) { - if (err) { - done(new Error('Cannot get account info: ' + err)); - } else { - accountInfo = response; - done(); - } - }); - }); - - it('Shall update an account', function(done) { - accountInfo.attributes = { - 'phone': '123456789', - 'another_attribute': 'another_value', - 'new': 'next_string_value', - }; - - helpers.accounts.updateAccount(accountId, userToken, accountInfo, function(err, response) { - if (err) { - done(new Error('Cannot update account: ' + err)); - } else { - assert.deepEqual(response.attributes, accountInfo.attributes, 'new attributes not being updated'); - done(); - } - }); - }); - - it('Shall get account activation code', function(done) { - helpers.accounts.getAccountActivationCode(accountId, userToken, function(err) { - if (err) { - done(new Error('Cannot get account activation code: ' + err)); - } else { - done(); - } - }); - }); - - it('Shall refresh account activation code', function(done) { - helpers.accounts.refreshAccountActivationCode(accountId, userToken, function(err) { - if (err) { - done(new Error('Cannot refresh account activation code: ' + err)); - } else { - done(); - } - }); - }); - - it('Shall list all users for account', function(done) { - helpers.accounts.getAccountUsers(accountId, userToken, function(err) { - if (err) { - done(new Error('Cannot list users for account: ' + err)); - } else { - done(); - } - }); - }); - - it('Shall create device', function(done) { - assert.notEqual(accountId, null, 'Invalid account id'); - - helpers.devices.createDevice(deviceName, deviceId, userToken, accountId, function(err, response) { - if (err) { - done(new Error('Cannot create device: ' + err)); - } else { - assert.equal(response.deviceId, deviceId, 'incorrect device id'); - assert.equal(response.name, deviceName, 'incorrect device name'); - done(); - } - }); - }); - - it('Shall get a list of all devices', function(done) { - helpers.devices.getDevices(userToken, accountId, function(err, response) { - if (err) { - done(new Error('Cannot get list of devices: ' + err)); - } else { - assert.equal(response[0].deviceId, deviceId, 'incorrect device id'); - done(); - } - }); - }); - - it('Shall update info of a device', function(done) { - const deviceInfo = { - gatewayId: deviceId, - name: deviceName, - loc: [45.12345, -130.654321, 121.1], - tags: ['tag001', 'tag002'], - attributes: { - vendor: 'intel', - platform: 'x64', - os: 'linux', - }, - }; - helpers.devices.updateDeviceDetails(userToken, accountId, deviceId, deviceInfo, function(err, response) { - if (err) { - done(new Error('Cannot update device info: ' + err)); - } else { - assert.notEqual(response, null, 'response is null'); - assert.deepEqual(response.attributes, deviceInfo.attributes, 'device info is not updated'); - done(); - } - }); - }); - - it('Shall list all tags for device', function(done) { - helpers.devices.getDeviceTags(userToken, accountId, function(err, response) { - if (err) { - done(new Error('Cannot list all tags for device ' + err)); - } else { - assert.equal(response.length, 2, 'error tag numbers'); - done(); - } - }); - }); - - it('Shall list all attributes for device', function(done) { - const attributes = { - vendor: ['intel'], - platform: ['x64'], - os: ['linux'], - }; - helpers.devices.getDeviceAttributes(userToken, accountId, function(err, response) { - if (err) { - done(new Error('Cannot list all attributes for device ' + err)); - } else { - assert.deepEqual(response, attributes, 'get wrong device attributes'); - done(); - } - }); - }); - - it('Shall count devices based on filter', function(done) { - helpers.devices.countDevices(userToken, accountId, function(err, response) { - if (err) { - done(new Error('Cannot count devices ' + err)); - } else { - assert.equal(response.device.total, 1, 'count devices wrong'); - done(); - } - }); - }); - - it('Shall search devices based on filter', function(done) { - helpers.devices.searchDevices(userToken, accountId, function(err, response) { - if (err) { - done(new Error('Cannot search devices ' + err)); - } else { - assert.equal(response[0].deviceId, deviceId, 'search wrong device'); - done(); - } - }); - }); - - it('Shall activate device', function(done) { - assert.notEqual(deviceId, null, 'Invalid device id'); - - helpers.devices.activateDevice(userToken, accountId, deviceId, function(err, response) { - if (err) { - done(new Error('Cannot activate device ' + err)); - } else { - assert.isString(response.deviceToken, 'device token is not string'); - deviceToken = response.deviceToken; - var topic = mqttConfig.connector.mqtt.topic.actuation; - topic = topic.replace("{accountid}", accountId); - topic = topic.replace("{gatewayId}", deviceId); - topic = topic.replace("{deviceid}", deviceId); - var topics = [topic]; - helpers.mqtt.openMqttConnection(deviceToken, deviceId, topics, cbManager, done); - } - }); - }).timeout(30000); - - it('Shall get detail of one device', function(done) { - helpers.devices.getDeviceDetails(userToken, accountId, deviceId, function(err, response) { - if (err) { - done(new Error('Cannot get detail of device: ' + err)); - } else { - assert.equal(response.deviceId, deviceId, 'incorrect device id'); - assert.deepEqual(response.attributes, - {'vendor': 'intel', 'platform': 'x64', 'os': 'linux'}, - 'incorrect device attributes' ); - done(); - } - }); - }); -}); - -describe('Device Activation Subtests'.bold, function() { - let test; - const descriptions = require('./subtests/device-activation-tests').descriptions; - it(descriptions.prepareSetup, function(done) { - test = require('./subtests/device-activation-tests').test(userToken, accountId); - test.prepareSetup(done); - }).timeout(10000); - it(descriptions.activateExistingDeviceWithoutToken, function(done) { - test.activateExistingDeviceWithoutToken(done); - }).timeout(10000); - it(descriptions.activateAnotherDeviceWithSameIdInAnotherAccount, function(done) { - test.activateAnotherDeviceWithSameIdInAnotherAccount(done); - }).timeout(10000); - it(descriptions.activateNotExistingDeviceWithoutToken, function(done) { - test.activateNotExistingDeviceWithoutToken(done); - }).timeout(10000); - it(descriptions.cleanup, function(done) { - test.cleanup(done); - }).timeout(10000); -}); - - -describe('Refresh Token Subtests'.bold, function() { - let test; - const descriptions = require('./subtests/refresh-token-tests').descriptions; - it(descriptions.getRefreshTokensForDeviceAndUser, function(done) { - test = require('./subtests/refresh-token-tests') - .test(process.env.USERNAME, process.env.PASSWORD, userToken, accountId, deviceId); - test.getRefreshTokensForDeviceAndUser(done); - }).timeout(10000); - it(descriptions.refreshTokensForDeviceAndUser, function(done) { - test.refreshTokensForDeviceAndUser(done); - }).timeout(10000); -}); - - -describe('Managing components catalog ... \n'.bold, function() { - it('Shall create new custom Components Types', function(done) { - var createCatalog = function(component) { - if ( component ) { - helpers.cmpcatalog.createCatalog(userToken, accountId, component.catalog, function(err) { - if (err) { - done(new Error('Cannot create component: ' + err)); - } else { - // component.cId = response.id; - // assert.equal(response.id, component.cId, 'cannot create new component type') - createCatalog(component.next); - } - }); - } else { - done(); - } - }; - createCatalog(components.first); - }).timeout(10000); - - it('Shall list all component types for account', function(done) { - helpers.cmpcatalog.getCatalog(userToken, accountId, function(err, response) { - if (err) { - done(new Error('Cannot create component: ' + err)); - } else { - assert.equal(response.length, components.size + 3, 'get wrong number of components '); - done(); - } - }); - }).timeout(10000); - - it('Shall get component type details', function(done) { - var getCatalogDetail = function(component) { - if ( component ) { - if ( component.catalog.max ) { - helpers.cmpcatalog.getCatalogDetail(userToken, accountId, component.cId, function(err, response) { - if (err) { - done(new Error('Cannot get component type details ' + err)); - } else { - assert.equal(response.id, component.cId, 'cannot get component '+component.name); - assert.equal(response.max, component.catalog.max); - getCatalogDetail(component.next); - } - }); - } else { - getCatalogDetail(component.next); - } - } else { - done(); - } - }; - getCatalogDetail(components.first); - }).timeout(10000); - - it('Shall update a component type', function(done) { - var updateCatalog = function(component) { - if ( component ) { - if ( component.catalog.min != null && - component.catalog.max != null ) { - const newmin = 10; - const newmax = 1000; - - helpers.cmpcatalog.updateCatalog(userToken, accountId, component.cId, newmin, newmax, function(err, response) { - if (err) { - done(new Error('Cannot get component type details ' + err)); - } else { - if ( component.upgradeVersion() === false ) { - done(new Error('Cannot upgrade version for component ' + component.name)); - } - assert.equal(response.id, component.cId, 'cannot update '+component.name+' component to '+component.catalog.version); - assert.equal(response.max, newmax); - updateCatalog(component.next); - } - }); - } else { - updateCatalog(component.next); - } - } else { - done(); - } - }; - updateCatalog(components.first); - }).timeout(10000); -}); - -describe('Creating and getting components ... \n'.bold, function() { - it('Shall add device a component', function(done) { - var addDeviceComponent = function(component) { - if ( component ) { - helpers.devices.addDeviceComponent(component.name, component.type, userToken, accountId, deviceId, function(err, id) { - if (err) { - done(new Error('Cannot create component ' + component + ' : ' +err)); - } else { - if ( id ) { - component.id = id; - addDeviceComponent(component.next); - } else { - done(new Error('Wrong id for component ' + component )); - } - } - }); - } else { - done(); - } - }; - addDeviceComponent(components.first); - }).timeout(10000); - - it('Shall not add device a component with the name that a component of the device already has, or crash', function(done) { - var addDeviceComponent = function(component) { - if ( component ) { - helpers.devices.addDeviceComponent(component.name, component.type, userToken, accountId, deviceId, function(err, id) { - if (err) { - addDeviceComponent(component.next); - } else { - done(new Error('No error is thrown and the component is added successfully: ' + id)); - } - }); - } else { - done(); - } - }; - addDeviceComponent(components.first); - }).timeout(10000); - - it('Shall add device an actuator', function(done) { - helpers.devices.addDeviceComponent(actuatorName, actuatorType, userToken, accountId, deviceId, function(err, id) { - if (err) { - done(new Error('Cannot create actuator: ' + err)); - } else { - actuatorId = id; - done(); - } - }); - }).timeout(10000); - - it('Shall create switch-on actuation command', function(done) { - assert.notEqual(actuatorId, null, 'Invalid actuator id'); - - helpers.control.saveComplexCommand(switchOnCmdName, componentParamName, 1, userToken, accountId, deviceId, actuatorId, function(err, response) { - if (err) { - done(new Error('Cannot create switch-on command: ' + err)); - } else { - assert.equal(response.status, 'OK', 'get error response status'); - done(); - } - }); - }).timeout(10000); - - it('Shall create switch-off actuation command', function(done) { - assert.notEqual(actuatorId, null, 'Invalid actuator id'); - - helpers.control.saveComplexCommand(switchOffCmdName, componentParamName, 0, userToken, accountId, deviceId, actuatorId, function(err, response) { - if (err) { - done(new Error('Cannot create switch-off command: ' + err)); - } else { - assert.equal(response.status, 'OK', 'get error response status'); - done(); - } - }); - }).timeout(10000); - - it('Shall send an actuation', function(done) { - const actuationValue = "1"; - let actuationReceived = false; - cbManager.set(function(message) { - message = JSON.parse(message); - const expectedActuationValue = true; - const componentParam = message.metrics.filter(function(metric) { - return metric.name === componentParamName; - }); - if (componentParam.length === 1) { - const param = componentParam[0]; - const paramValue = param.value; - if (paramValue !== expectedActuationValue) { - done(new Error('Param value wrong. Expected: ' + expectedActuationValue + ' Received: ' + paramValue)); - } else { - actuationReceived = true; - } - } else { - done(new Error('Did not find component param: ' + componentParamName)); - } - }); - helpers.control.sendActuationCommand(componentParamName, actuationValue, userToken, accountId, actuatorId, deviceId, function(err, response) { - if (err) { - done(new Error('Cannot send an actuation: ' + err)); - } else { - assert.equal(response.status, 'OK', 'cannot send an actuation'); - const checkActuation = function() { - if (actuationReceived) { - done(); - } else { - done(new Error('Actuation timed out after sending actuation command')); - } - }; - setTimeout(checkActuation, 10000); - } - }); - }).timeout(15000); - - it('Shall get list of actuations', function(done) { - const parameters = { - from: 0, - to: undefined, - }; - - helpers.control.pullActuations(parameters, userToken, accountId, deviceId, actuatorId, function(err, response) { - if (err) { - done(new Error('get list of actuations: ' + err)); - } else { - assert.equal(response[0].componentId, actuatorId, 'pull error actuations'); - done(); - } - }); - }).timeout(20000); -}); - -describe('Sending observations\n'.bold, function() { - before(function() { - if (checkTestCondition(['non_essential', 'data_sending'])) { - this.skip(); - } - }); - - it('Shall send observations', function(done) { - assert.notEqual(proxyConnector, null, 'Invalid websocket proxy connector'); - - let curComponent = null; - components.reset(); - - var sendObservations; - - const step = function(component) { - component.dataIndex++; - if ( component.dataIndex === component.data.length) { - process.stdout.write('\n'); - component = component.next; - } - - sendObservations(component); - }; - - let actuationCounter = 0; - sendObservations = function(component) { - if ( component ) { - if ( curComponent !== component ) { - process.stdout.write('\t' + component.type.blue + '\n'); - } - curComponent = component; - if (component.dataIndex === 0) { - process.stdout.write('\t'); - } - process.stdout.write('.'.green); - const currentActuationCounter = actuationCounter; - const currentDataIndex = component.dataIndex; - helpers.devices.submitData(component.data[component.dataIndex].value, deviceToken, - accountId, deviceId, component.id, function(err, ts) { - component.data[component.dataIndex].ts = ts; - - if (err) { - done('Cannot send observation: ' + err); - } - - step(component); - }); - } else { - done(); - } - }; - - sendObservations(components.first); - }).timeout(60*4000); - - // --------------------------------------------------------------- - - it('Wait for backend synchronization', function(done) { - setTimeout(done, BACKEND_DELAY); - }).timeout(BACKEND_TIMEOUT); - - it('Shall check observations', function(done) { - var checkObservations = function(component) { - if ( component ) { - if ( component.data.length > 0 ) { - helpers.data.searchData(component.data[0].ts, component.data[component.data.length-1].ts, - userToken, accountId, deviceId, component.id, false, {}, function(err, result) { - if (err) { - done(new Error('Cannot get data: ' + err)); - } else if (result && result.series && result.series.length === 1) { - err = component.checkData(result.series[0].points); - } else { - done(new Error('Cannot get data.')); - } - - if (err) { - done(new Error(err)); - } else { - checkObservations(component.next); - } - }); - } else { - checkObservations(component.next); - } - } else { - done(); - } - }; - checkObservations(components.first); - }).timeout(BACKEND_TIMEOUT); -}); - -describe('Do data sending subtests ...'.bold, function() { - before(function() { - if (checkTestCondition(['non_essential', 'data_sending'])) { - this.skip(); - } - }); - let test; - const descriptions = require('./subtests/data-sending-tests').descriptions; - it(descriptions.sendAggregatedDataPoints, function(done) { - test = require('./subtests/data-sending-tests').test(userToken, accountId, deviceId, deviceToken, cbManager); - test.sendAggregatedDataPoints(done); - }).timeout(10000); - it(descriptions.waitForBackendSynchronization, function(done) { - test.waitForBackendSynchronization(BACKEND_DELAY, done); - }).timeout(BACKEND_TIMEOUT); - it(descriptions.receiveAggregatedDataPoints, function(done) { - test.receiveAggregatedDataPoints(done); - }).timeout(10000); - it(descriptions.sendAggregatedMultipleDataPoints, function(done) { - test.sendAggregatedMultipleDataPoints(done); - }).timeout(10000); - it(descriptions.waitForBackendSynchronization, function(done) { - test.waitForBackendSynchronization(BACKEND_DELAY, done); - }).timeout(BACKEND_TIMEOUT); - it(descriptions.receiveAggregatedMultipleDataPoints, function(done) { - test.receiveAggregatedMultipleDataPoints(done); - }).timeout(10000); - it(descriptions.sendDataPointsWithLoc, function(done) { - test.sendDataPointsWithLoc(done); - }).timeout(10000); - it(descriptions.waitForBackendSynchronization, function(done) { - test.waitForBackendSynchronization(BACKEND_DELAY, done); - }).timeout(BACKEND_TIMEOUT); - it(descriptions.receiveDataPointsWithLoc, function(done) { - test.receiveDataPointsWithLoc(done); - }).timeout(10000); - it(descriptions.sendDataPointsWithAttributes, function(done) { - test.sendDataPointsWithAttributes(done); - }).timeout(10000); - it(descriptions.waitForBackendSynchronization, function(done) { - test.waitForBackendSynchronization(BACKEND_DELAY, done); - }).timeout(BACKEND_TIMEOUT); - it(descriptions.receiveDataPointsWithAttributes, function(done) { - test.receiveDataPointsWithAttributes(done); - }).timeout(10000); - it(descriptions.receiveDataPointsWithSelectedAttributes, function(done) { - test.receiveDataPointsWithSelectedAttributes(done); - }).timeout(10000); - it(descriptions.receiveDataPointsCount, function(done) { - test.receiveDataPointsCount(done); - }).timeout(10000); - it(descriptions.receiveAggregations, function(done) { - test.receiveAggregations(done); - }).timeout(10000); - it(descriptions.receiveSubset, function(done) { - test.receiveSubset(done); - }).timeout(10000); - it(descriptions.sendMaxAmountOfSamples, function(done) { - test.sendMaxAmountOfSamples(done); - }).timeout(10000); - it(descriptions.sendPartiallyWrongData, function(done) { - test.sendPartiallyWrongData(done); - }).timeout(BACKEND_TIMEOUT * TIMEOUT_FACTOR); - it(descriptions.sendDataAsAdmin, function(done) { - test.sendDataAsAdmin(done); - }).timeout(10000); - it(descriptions.sendDataAsAdminWithWrongAccount, function(done) { - test.sendDataAsAdminWithWrongAccount(done); - }).timeout(10000); - it(descriptions.sendDataAsUser, function(done) { - test.sendDataAsUser(done); - }).timeout(10000); - it(descriptions.send8000SamplesForAutoDownsampleTest, function(done) { - test.send8000SamplesForAutoDownsampleTest(done); - }).timeout(100000); - /*it(descriptions.send8000SamplesForMultiAggregationTest,function(done) { - test.send8000SamplesForMultiAggregationTest(done); - }).timeout(100000);*/ - it(descriptions.waitForBackendSynchronization, function(done) { - // Due to low profile of test environment and the fact that Kafka/Backend is processing all the 1000s of samples - // separately, we need to give the backend more time to settle - test.waitForBackendSynchronization(BACKEND_DELAY * 2, done); - }).timeout(BACKEND_TIMEOUT * 2); - it(descriptions.receiveMaxAmountOfSamples, function(done) { - test.receiveMaxAmountOfSamples(done); - }).timeout(10000); - it(descriptions.receivePartiallySentData, function(done) { - test.receivePartiallySentData(done); - }).timeout(10000); - it(descriptions.sendDataAsDeviceToWrongDeviceId, function(done) { - test.sendDataAsDeviceToWrongDeviceId(done); - }).timeout(10000); - it(descriptions.receiveDataFromAdmin, function(done) { - test.receiveDataFromAdmin(done); - }).timeout(10000); - it(descriptions.receiveRawData, function(done) { - test.receiveRawData(done); - }).timeout(10000); - it(descriptions.receiveMaxItems, function(done) { - test.receiveMaxItems(done); - }).timeout(10000); - it(descriptions.receiveAutoAggregatedAvgData, function(done) { - test.receiveAutoAggregatedAvgData(done); - }).timeout(10000); - it(descriptions.receiveAutoAggregatedMaxData, function(done) { - test.receiveAutoAggregatedMaxData(done); - }).timeout(10000); - it(descriptions.receiveAutoAggregatedMinData, function(done) { - test.receiveAutoAggregatedMinData(done); - }).timeout(10000); - it(descriptions.receiveAutoAggregatedSumData, function(done) { - test.receiveAutoAggregatedSumData(done); - }).timeout(10000); - it(descriptions.receiveAggregatedAvgData, function(done) { - test.receiveAggregatedAvgData(done); - }).timeout(10000); - it(descriptions.receiveAggregatedAvgDataMS, function(done) { - test.receiveAggregatedAvgDataMS(done); - }).timeout(10000); - it(descriptions.receiveAggregatedAvgDataMinutes, function(done) { - test.receiveAggregatedAvgDataMinutes(done); - }).timeout(10000); - it(descriptions.receiveRawDataDesc, function(done) { - test.receiveRawDataDesc(done); - }).timeout(10000); - it(descriptions.receiveRawDataLatest, function(done) { - test.receiveRawDataLatest(done); - }).timeout(10000); - it(descriptions.receiveAggregatedDataFromMultipleComponents, function(done) { - test.receiveAggregatedDataFromMultipleComponents(done); - }).timeout(10000); - it(descriptions.cleanup, function(done) { - test.cleanup(done); - }).timeout(10000); -}); - -describe('Grafana subtests...'.bold, function() { - before(function() { - if (checkTestCondition(['non_essential', 'grafana'])) { - this.skip(); - } - }); - let test; - const descriptions = require('./subtests/grafana-tests').descriptions; - it(descriptions.prepareGrafanaTestSetup, function(done) { - test = require('./subtests/grafana-tests').test(userToken, userToken2); - test.prepareGrafanaTestSetup(done); - }).timeout(20000); - it(descriptions.checkGrafanaHeartbeat, function(done) { - test.checkGrafanaHeartbeat(done); - }).timeout(50000); - it(descriptions.authenticateGrafanaAsViewer, function(done) { - test.authenticateGrafanaAsViewer(done); - }).timeout(10000); - it(descriptions.getDataSourceId, function(done) { - test.getDataSourceId(done); - }).timeout(10000); - it(descriptions.queryUserAccountsData, function(done) { - setTimeout(test.queryUserAccountsData, 2000, done); - }).timeout(10000); - it(descriptions.tryToGetUnbelongedData, function(done) { - test.tryToGetUnbelongedData(done); - }).timeout(10000); - it(descriptions.getSuggestions, function(done) { - test.getSuggestions(done); - }).timeout(10000); - it(descriptions.tryToGetUnbelongedSuggestions, function(done) { - test.tryToGetUnbelongedSuggestions(done); - }).timeout(10000); - it(descriptions.cleanup, function(done) { - test.cleanup(done); - }).timeout(10000); -}); - -describe('TSDB Proxy subtests...'.bold, function() { - before(function() { - if (checkTestCondition(['non_essential', 'tsdbproxy'])) { - this.skip(); - } - }); - let test; - const descriptions = require('./subtests/tsdb-proxy-tests').descriptions; - it(descriptions.prepareTestSetup, function(done) { - test = require('./subtests/tsdb-proxy-tests').test(userToken); - test.prepareTestSetup(done); - }).timeout(10000); - it(descriptions.testSuggestion, function(done) { - test.testSuggestion(done); - }).timeout(10000); - it(descriptions.testQuery, function(done) { - test.testQuery(done); - }).timeout(10000); - it(descriptions.cleanup, function(done) { - test.cleanup(done); - }).timeout(10000); -}); - -describe('Do MQTT feedback subtests ...'.bold, function() { - before(function() { - if (checkTestCondition(['non_essential', 'mqtt'])) { - this.skip(); - } - }); - let test; - const descriptions = require('./subtests/mqtt-feedback-tests').descriptions; - it(descriptions.setup, function(done) { - test = require('./subtests/mqtt-feedback-tests').test(userToken, mqttConnector); - test.setup(done); - }).timeout(20000); - it(descriptions.openMqttConnection, function(done) { - test.openMqttConnection(done); - }).timeout(10000); - it(descriptions.receiveControlActuation, function(done) { - test.receiveControlActuation(done); - }).timeout(25000); - it(descriptions.cleanup, function(done) { - test.cleanup(done); - }).timeout(10000); -}); - -describe('Do MQTT data sending subtests ...'.bold, function() { - before(function() { - if (checkTestCondition(['non_essential', 'mqtt'])) { - this.skip(); - } - }); - let test; - const descriptions = require('./subtests/mqtt-data-sending-tests').descriptions; - it(descriptions.setup, function(done) { - test = require('./subtests/mqtt-data-sending-tests').test(userToken, accountId, deviceId, deviceToken, cbManager, mqttConnector); - test.setup(done); - }).timeout(10000); - it(descriptions.sendSingleDataPoint, function(done) { - test.sendSingleDataPoint(done); - }).timeout(10000); - it(descriptions.sendMultipleDataPoints, function(done) { - test.sendMultipleDataPoints(done); - }).timeout(10000); - it(descriptions.sendDataPointsWithAttributes, function(done) { - test.sendDataPointsWithAttributes(done); - }).timeout(10000); - it(descriptions.waitForBackendSynchronization, function(done) { - test.waitForBackendSynchronization(BACKEND_DELAY, done); - }).timeout(BACKEND_TIMEOUT); - it(descriptions.receiveSingleDataPoint, function(done) { - test.receiveSingleDataPoint(done); - }).timeout(10000); - it(descriptions.receiveMultipleDataPoints, function(done) { - test.receiveMultipleDataPoints(done); - }).timeout(10000); - it(descriptions.receiveDataPointsWithAttributes, function(done) { - test.receiveDataPointsWithAttributes(done); - }).timeout(10000); - it(descriptions.cleanup, function(done) { - test.cleanup(done); - }).timeout(10000); -}); - -describe('Do scale device subtests ...'.bold, function() { - before(function() { - if (checkTestCondition(['non_essential', 'scale'])) { - this.skip(); - } - }); - let test; - const descriptions = require('./subtests/scale-devices-tests').descriptions; - it(descriptions.setup, function(done) { - test = require('./subtests/scale-devices-tests').test(userToken, accountId, deviceId, deviceToken, cbManager, mqttConnector); - test.setup(done); - }).timeout(100000); - it(descriptions.sendDataToAllDevices, function(done) { - test.sendDataToAllDevices(done); - }).timeout(100000); - it(descriptions.sendDataToSingleDevice, function(done) { - test.sendDataToSingleDevice(done); - }).timeout(200000); - it(descriptions.waitForBackendSynchronization, function(done) { - test.waitForBackendSynchronization(BACKEND_DELAY, done); - }).timeout(BACKEND_TIMEOUT); - it(descriptions.countAllData, function(done) { - test.countAllData(done); - }).timeout(100000); - it(descriptions.countPartialData, function(done) { - test.countPartialData(done); - }).timeout(100000); - it(descriptions.countSingleDeviceData, function(done) { - test.countSingleDeviceData(done); - }).timeout(100000); - it(descriptions.cleanup, function(done) { - test.cleanup(done); - }).timeout(100000); -}); - -describe('Adding user and posting email ...\n'.bold, function() { - before(function() { - if (checkTestCondition(['non_essential', 'email'])) { - this.skip(); - } - }); - - it('Shall add a new user and post email', function(done) { - assert.isNotEmpty(imap_username, 'no email provided'); - nr_mails = helpers.mail.getAllEmailMessages().length; - assert.isNotEmpty(imap_password, 'no password provided'); - helpers.users.addUser(userToken, imap_username, imap_password, function(err, response) { - if (err) { - done(new Error('Cannot create new user: ' + err)); - } else { - assert.equal(response.email, imap_username, 'add wrong user'); - done(); - } - }); - }); - - it('Shall activate user with token', function(done) { - helpers.mail.waitForNewEmail(nr_mails+1, null, done, 60 * 1000); - const message = helpers.mail.getAllEmailMessages(imap_username)[0]; - const regexp = /token=\w*/; - const activationToken = message.match(regexp).toString().split('=')[1]; - helpers.users.activateUser(activationToken, function(err, response) { - if (err) { - done(new Error('Cannot activate user (token ' + activationToken + ') : ' + err)); - } else { - assert.equal(response.status, 'OK', 'cannot activate user'); - helpers.auth.login(imap_username, imap_password, function(err, grant) { - if (err) { - done(new Error('Cannot authenticate receiver: ' + err)); - } else { - receiverToken = grant.token; - done(); - } - }); - } - }); - }).timeout(60 * 1000); - - it('Shall create receiver account', function(done) { - assert.notEqual(receiverToken, null, 'Invalid user token'); - helpers.accounts.createAccount('receiver', receiverToken, function(err, response) { - if (err) { - done(new Error('Cannot create account: ' + err)); - } else { - assert.equal(response.name, 'receiver', 'accounts name is wrong'); - receiveraccountId = response.id; - helpers.auth.login(imap_username, imap_password, function(err, grant) { - if (err) { - done(new Error('Cannot authenticate receiver: ' + err)); - } else { - receiverToken = grant.token; - done(); - } - }); - } - }); - }); -}); - -describe('Invite receiver ...\n'.bold, function() { - before(function() { - if (checkTestCondition(['non_essential', 'email'])) { - this.skip(); - } - }); - let inviteId = null; - - it('Shall create invitation', function(done) { - // a mail will be sent to receiver - nr_mails = helpers.mail.getAllEmailMessages(imap_username).length; - helpers.invitation.createInvitation(userToken, accountId, imap_username, function(err, response) { - if (err) { - done(new Error('Cannot create invitation: ' + err)); - } else { - assert.equal(response.email, imap_username, 'send invite to wrong name'); - done(); - } - }); - }).timeout( 30 * 1000); - - - it('Shall get all invitations', function(done) { - helpers.invitation.getAllInvitations(userToken, accountId, function(err, response) { - if (err) { - done(new Error('Cannot get invitation: ' + err)); - } else { - assert.equal(response[0], imap_username, 'send invite to wrong name'); - done(); - } - }); - }); - - it('Shall delete invitation and send again', function(done) { - helpers.invitation.deleteInvitations(userToken, accountId, imap_username, function(err) { - if (err) { - done(new Error('Cannot delete invitation: ' + err)); - } else { - nr_mails = helpers.mail.getAllEmailMessages().length; - helpers.invitation.createInvitation(userToken, accountId, imap_username, function(err, response) { - // when send invitation, the receiver will receive an email said he should login to accept the invitation - if (err) { - done(new Error('Cannot create invitation: ' + err)); - } else { - assert.equal(response.email, imap_username, 'send invite to wrong name'); - helpers.mail.waitForNewEmail(nr_mails + 1, null, done, 30 * 1000); - done(); - } - }); - } - }); - }).timeout(30 * 1000); - - it('Shall get specific invitations', function(done) { - var getInvitation = function(cb) { - helpers.auth.login(imap_username, imap_password, function(err, grant) { - if (err) { - done(new Error('Cannot authenticate: ' + err)); - } else { - receiverToken = grant.token; - helpers.invitation.getInvitations(receiverToken, receiveraccountId, imap_username, function(err, response) { - if (err) { - cb(err, null); - } else { - if (response != null) { - cb(null, response); - } else { - process.stdout.write('.'); - setTimeout(function() { - getInvitation(cb); - }, 500); - } - } - }); - } - }); - }; - getInvitation(function(err, response) { - assert.equal(err, null, 'get invitation error'); - inviteId = response[0]._id; - done(); - }); - }).timeout(2 * 60 * 1000); - - it('Shall accept specific invitations', function(done) { - helpers.invitation.acceptInvitation(receiverToken, accountId, inviteId, function(err, response) { - if (err) { - done(new Error('cannot accept invitetion :' + err)); - } else { - assert.equal(response.accountName, accountName, 'accept wrong invitation'); - done(); - } - }); - }); - - it('Shall not accept non-existing invitations, or crash', function(done) { - inviteId = 0; - helpers.invitation.acceptInvitation(receiverToken, accountId, inviteId, function(err, response) { - if (err) { - done(); - } else { - done(new Error('non-existing invitation accepted' + response)); - } - }); - }); - - it('Shall request activation', function(done) { - const username = process.env.USERNAME; - nr_mails = helpers.mail.getAllEmailMessages().length; - helpers.users.requestUserActivation(username, function(err, response) { - if (err) { - done(new Error('cannot request activation:' + err)); - } else { - assert.equal(response.status, 'OK'); - helpers.mail.waitForNewEmail(nr_mails +1, null, done, 30 * 1000); - done(); - } - }); - }).timeout( 30 * 1000); - - it('Shall get id of receiver and change privilege', function(done) { - helpers.auth.tokenInfo(receiverToken, function(err, response) { - if (err) { - done(new Error('Cannot get token info: ' + err)); - } else { - receiveruserId = response.payload.sub; - helpers.accounts.changeAccountUser(accountId, userToken, receiveruserId, function(err, response) { - if (err) { - done(new Error('Cannot change another user privilege to your account: ' + err)); - } else { - assert.equal(response.status, 'OK'); - done(); - } - }); - } - }); - }); - - it('Shall list all users for account', function(done) { - helpers.accounts.getAccountUsers(accountId, userToken, function(err, response) { - if (err) { - done(new Error('Cannot list users for account: ' + err)); - } else { - assert.equal(response.length, 2, 'error account numbers'); - done(); - } - }); - }); -}); - -describe('change password and delete receiver ... \n'.bold, function() { - before(function() { - if (checkTestCondition(['non_essential', 'email'])) { - this.skip(); - } - }); - it('Shall request change receiver password', function(done) { - const username = process.env.USERNAME; - nr_mails = helpers.mail.getAllEmailMessages().length; - helpers.users.requestUserPasswordChange(username, function(err, response) { - if (err) { - done(new Error('Cannot request change password : ' + err)); - } else { - assert.equal(response.status, 'OK', 'status error'); - done(); - } - }); - }); - - it('Shall update receiver password', function(done) { - const username = process.env.USERNAME; - helpers.mail.waitForNewEmail(nr_mails+1, null, done, 2 * 60 * 1000); - const message = helpers.mail.getAllEmailMessages(username)[0]; - const regexp = /token=\w*/; - const activationToken = message.match(regexp).toString().split('=')[1]; - - if ( activationToken === null) { - done(new Error('Wrong email ' + message )); - } else { - assert.isString(activationToken, 'activationToken is not string'); - const password = 'Receiver12345'; - helpers.users.updateUserPassword(activationToken, password, function(err, response) { - if (err) { - done(new Error('Cannot update receiver password : ' + err)); - } else { - assert.equal(response.status, 'OK', 'status error'); - done(); - } - }); - } - }).timeout(2 * 60 * 1000); - - it('Shall change password', function(done) { - const username = process.env.USERNAME; - const oldPasswd = 'Receiver12345'; - const newPasswd = 'oispnewpasswd2'; - - helpers.users.changeUserPassword(userToken, username, oldPasswd, newPasswd, function(err, response) { - if (err) { - done(new Error('Cannot change password: ' + err)); - } else { - assert.equal(response.password, 'oispnewpasswd2', 'new password error'); - done(); - } - }); - }); - - it('Shall delete a component', function(done) { - var deleteComponent = function(component) { - if ( component ) { - helpers.devices.deleteDeviceComponent(userToken, accountId, deviceId, component.id, function(err, response) { - if (err) { - done(new Error('cannot delete a component ' + err)); - } else { - assert.notEqual(response, null, 'response is null'); - assert.equal(response.status, 'Done'); - deleteComponent(component.next); - } - }); - } else { - done(); - } - }; - deleteComponent(components.first); - }); - - it('Shall delete a device', function(done) { - helpers.devices.deleteDevice(userToken, accountId, deviceId, function(err, response) { - if (err) { - done(new Error('cannot delete a device ' + err)); - } else { - assert.notEqual(response, null, 'response is null'); - assert.equal(response.status, 'Done'); - done(); - } - }); - }); - - it('Shall delete an account', function(done) { - helpers.accounts.deleteAccount(userToken, accountId, function(err, response) { - if (err) { - done(new Error('cannot delete an account ' + err)); - } else { - assert.notEqual(response, null, 'response is null'); - assert.equal(response.status, 'Done'); - done(); - } - }); - }); - - it('Shall delete a user', function(done) { - helpers.users.deleteUser(userToken, userId, function(err, response) { - if (err) { - done(new Error('cannot delete a user ' + err)); - } else { - assert.notEqual(response, null, 'response is null'); - assert.equal(response.status, 'Done'); - helpers.users.deleteUser(userToken2, userId2, function(err) { - if (err) { - return done(err); - } - helpers.users.deleteUser(receiverToken, receiveruserId, function(err) { - if (err) { - return done(err); - } - done(); - }); - }); - } - }); - }); -}); diff --git a/tests/package.json b/tests/package.json deleted file mode 100644 index e86ee55b..00000000 --- a/tests/package.json +++ /dev/null @@ -1,42 +0,0 @@ -{ - "name": "test", - "version": "1.0.0", - "description": "E2E test with server", - "main": "test.js", - "scripts": { - "test": "mocha oisp-tests.js --bail --exit", - "prep-only": "mocha oisp-prep-only.js --exit", - "test-backup-before": "mocha test-backup-before.js --exit", - "test-backup-after": "mocha test-backup-after.js --exit" - }, - "author": "Intel SSG-DRD", - "license": "ISC", - "dependencies": { - "@open-iot-service-platform/oisp-sdk-js": "https://github.com/Open-IoT-Service-Platform/oisp-sdk-js.git#471318eb6dafb26608093b2d360884dfd5ee81ed", - "cbor": "^4.1.5", - "cfenv": "^1.0.0", - "chai": "^4.1.2", - "colors": "^1.2.1", - "getmac": "^1.2.1", - "gm": "^1.23.1", - "imap": "^0.8.19", - "kafka-node": "^2.4.0", - "kafkajs": "^1.15.0", - "mailparser": "^2.2.0", - "mocha": "^4.0.1", - "mqtt": "^4.2.8", - "nodemailer": "^4.6.6", - "request-promise": "^4.2.4", - "sleep": "^6.3.0", - "sync-request": "^6.1.0", - "tough-cookie": "^3.0.1", - "uuid": "^3.1.0", - "ws": "^7.3.1" - }, - "devDependencies": { - "grunt": "^1.0.3", - "grunt-cli": "^1.3.1", - "grunt-contrib-jshint": "^3.0.0", - "grunt-eslint": "^23.0.0" - } -} diff --git a/tests/subtests/data-sending-tests.js b/tests/subtests/data-sending-tests.js deleted file mode 100644 index e4e2cc9a..00000000 --- a/tests/subtests/data-sending-tests.js +++ /dev/null @@ -1,1358 +0,0 @@ -/** - * Copyright (c) 2018 Intel Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/*jshint esversion: 6 */ -/*jshint undef: true, unused: true */ -/* jshint node: true */ - -"use strict"; - -var test = function(userToken, accountId, deviceId, deviceToken) { - var chai = require('chai'); - var assert = chai.assert; - var errors = require('../lib/helpers').errors; - var componentNames = ["temperature-sensor-sdt", "humidity-sensor-sdt", "metadata-sensor-sdt", "binarystate-senosr-sdt"]; - var componentTypes = ["temperature.v1.0", "humidity.v1.0", "metaData.v1.0", "binaryState.v1.0"]; - var componentBasicTypes = ["number", "number", "string", "boolean"]; - var aggregateable = [1, 1, 0, 0]; - var promtests = require('./promise-wrap'); - var uuidv4 = require('uuid/v4'); - var componentId = []; - var dataValues1Time; - var dataValues2Time; - var dataValues3Time; - var dataValues4Time; - var dataValues5StartTime; - var dataValues5StopTime; - var dataValues6StartTime; - var dataValues6StopTime; - var accountId2; - var accountName2 = "badAccount"; - var userToken2; - var username2 = process.env.USERNAME2; - var password2 = process.env.PASSWORD2; - var newDeviceId = "d-e-v-i-c-e"; - var newComponentId; - const MIN_NUMBER = 0.0001; - const MAX_SAMPLES = 1000; - const MAX_SAMPLES_RETRIVE = 4000; - const MAX_ITEMS_TEST_SAMPLES = 1000; - const BASE_TIMESTAMP = 1000000000000; - const DOWNSAMPLE_MULT = 8; - - var dataValues1 = [ - [{ - component: 0, - value: 10.1, - ts: 1 + BASE_TIMESTAMP - }], - [{ - component: 0, - value: 11.2, - ts: 2 + BASE_TIMESTAMP - }, { - component: 0, - value: 12.3, - ts: 3 + BASE_TIMESTAMP - }], - [{ - component: 0, - value: 13.4, - ts: 4 + BASE_TIMESTAMP - }, - { - component: 0, - value: 14.5, - ts: 5 + BASE_TIMESTAMP - }, - { - component: 0, - value: 15.6, - ts: 6 + BASE_TIMESTAMP - } - ], - [{ - component: 0, - value: 16.7, - ts: 7 + BASE_TIMESTAMP - }, - { - component: 0, - value: 17.8, - ts: 8 + BASE_TIMESTAMP - }, - { - component: 0, - value: 18.9, - ts: 9 + BASE_TIMESTAMP - }, - { - component: 0, - value: 20.0, - ts: 10 + BASE_TIMESTAMP - } - ], - [{ - component: 0, - value: 21.1, - ts: 11 + BASE_TIMESTAMP - }, - { - component: 0, - value: 22.2, - ts: 12 + BASE_TIMESTAMP - }, - { - component: 0, - value: 23.3, - ts: 13 + BASE_TIMESTAMP - }, - { - component: 0, - value: 24.4, - ts: 14 + BASE_TIMESTAMP - }, - { - component: 0, - value: 25.5, - ts: 15 + BASE_TIMESTAMP - } - - ] - ]; - - - var dataValues2 = [ - [{ - component: 0, - value: 10.1, - ts: 1000 + BASE_TIMESTAMP - }], - [{ - component: 1, - value: 10, - ts: 1020 + BASE_TIMESTAMP - }, - { - component: 0, - value: 12.3, - ts: 1030 + BASE_TIMESTAMP - } - ], - [{ - component: 0, - value: 13.4, - ts: 1040 + BASE_TIMESTAMP - }, - { - component: 1, - value: 20, - ts: 1050 + BASE_TIMESTAMP - }, - { - component: 0, - value: 15.6, - ts: 1060 + BASE_TIMESTAMP - } - ], - [{ - component: 1, - value: 30, - ts: 1070 + BASE_TIMESTAMP - }, - { - component: 0, - value: 17.8, - ts: 1070 + BASE_TIMESTAMP - }, - { - component: 0, - value: 18.9, - ts: 1090 + BASE_TIMESTAMP - }, - { - component: 1, - value: 40, - ts: 1100 + BASE_TIMESTAMP - } - ], - [{ - component: 1, - value: 50, - ts: 1170 + BASE_TIMESTAMP - }], - [{ - component: 1, - value: 50, - ts: 1200 + BASE_TIMESTAMP - }, - { - component: 2, - value: "hello", - ts: 1210 + BASE_TIMESTAMP - }, - { - component: 3, - value: "1", - ts: 1220 + BASE_TIMESTAMP - }] - ]; - - var dataValues3 = [ - [{ - component: 0, - value: 10, - ts: 10000 + BASE_TIMESTAMP, - loc: [99.12345, 12.3456, 456.789] - }], - [{ - component: 0, - value: 11, - ts: 20000 + BASE_TIMESTAMP, - loc: [9.8765, 432.1, 9.876] - }], - [{ - component: 0, - value: 12, - ts: 30000 + BASE_TIMESTAMP, - }], - [{ - component: 0, - value: 13, - ts: 40000 + BASE_TIMESTAMP, - loc: [0.0, 0.0, 0.0] - }], - [{ - component: 0, - value: 14, - ts: 50000 + BASE_TIMESTAMP, - loc: [200.345, 300.21] - }] - ]; - - var dataValues4 = [ - [{ - component: 1, - value: 99, - ts: 100000 + BASE_TIMESTAMP, - loc: [1.2444, 10.987, 456.789], - attributes: { - "key1": "value1" - } - }], - [{ - component: 1, - value: 98, - ts: 200000 + BASE_TIMESTAMP, - attributes: { - "key1": "value1", - "key2": "value2", - "key3": "value3" - } - }], - [{ - component: 1, - value: 97, - ts: 300000 + BASE_TIMESTAMP, - attributes: { - "key3": "value1", - "key4": "value2" - } - }], - [{ - component: 1, - value: 96, - ts: 400000 + BASE_TIMESTAMP, - loc: [0.0, 0.0, 0.0] - }], - [{ - component: 1, - value: 95, - ts: 500000 + BASE_TIMESTAMP, - loc: [200.345, 300.21], - attributes: { - "key5": "key1" - } - }], - [{ - component: 2, - value: "test123", - ts: 600000 + BASE_TIMESTAMP, - loc: [210.345, 260.21], - attributes: { - "key6": "value6" - } - }], - [{ - component: 3, - value: "1", - ts: 700000 + BASE_TIMESTAMP, - loc: [100.12, 300.12], - attributes: { - "key5": "value6", - "key1": "value1" - } - }] - ]; - - var dataValues5 = [ - [{ - component: componentNames.length, - value: 10.1, - ts: 1100000000 + BASE_TIMESTAMP - }], - [{ - component: 0, - value: 10, - ts: 1100020000 + BASE_TIMESTAMP - }, - { - component: componentNames.length, - value: 12.3, - ts: 1100030000 + BASE_TIMESTAMP - } - ], - [{ - component: 0, - value: 13.4, - ts: 1100040000 + BASE_TIMESTAMP - }, - { - component: 0, - value: 20, - ts: 1100050000 + BASE_TIMESTAMP - }, - { - component: componentNames.length, - value: 15.6, - ts: 1100060000 + BASE_TIMESTAMP - }] - ]; - - var dataValues6 = [ - { - component: 0, - value: 1, - ts: 1200000000 + BASE_TIMESTAMP - }, - { - component: 0, - value: 2, - ts: 1200020000 + BASE_TIMESTAMP - } - ]; - - var dataValues7 = [ - { - component: 0, - value: 101, - ts: 1200000001 + BASE_TIMESTAMP - }, - { - component: 0, - value: 102, - ts: 1200020001 + BASE_TIMESTAMP - } - ]; - - var flattenArray = function(array) { - var results = array.map(function(element) { - return element; - }); - results = results - .reduce(function(acc, cur) { - return acc.concat(cur); - }) - .filter((elem) => elem.component < componentId.length); - return results; - }; - - var findMapping = function(foundComponentMap, componentIds, series) { - var mapping = {}; - Object.keys(foundComponentMap).forEach(function(i) { - mapping[i] = series.findIndex( - element => componentIds[i] === element.componentId - ); - }); - return mapping; - }; - - //flatten sent array and provide numComponents - var prepareValues = function(dataValues, keys) { - //First get a flat array of aggregated points - var flattenedDataValues = flattenArray(dataValues, keys); - var numComponents = {}; - flattenedDataValues.forEach(function(element){ - numComponents[element.component] = element.component; - }); - var listOfExpectedResults = []; - //Get elements sorted by componentId - Object.values(numComponents).forEach(function(i){ - listOfExpectedResults[i] = flattenedDataValues.filter( - (element) => (element.component === i) - ); - }); - return { - flattenedDataValues: flattenedDataValues, - numComponents: numComponents, - listOfExpectedResults: listOfExpectedResults - }; - }; - - var aggregation = { - MAX: 0, - MIN: 1, - COUNT: 2, - SUM: 3, - SUMOFSQUARES: 4 - }; - - var createObjectFromData = function(sample, sampleHeader) { - var o = {}; - sample.forEach(function(element, index) { - if (element !== "") { - var key = sampleHeader[index]; - if (key === "Value") { - key = "value"; - } else if (key === "Timestamp") { - key = "ts"; - } - o[key] = element; - } - }); - return o; - }; - - var locEqual = function(dataValue, element, onlyExistingAttr) { - if (onlyExistingAttr) { - if (element.lat === undefined && element.long === undefined) { - return true; - } - } - if (dataValue.loc === undefined) { - if ((element.lat === undefined || element.lat === "") && (element.lat === undefined || - element.lon === "") && (element.alt === undefined || element.alt === "")) { - return true; - } else { - return false; - } - } - if ((dataValue.loc[0] === undefined || (Math.abs(dataValue.loc[0] - Number(element.lat))) <= MIN_NUMBER) && - (dataValue.loc[1] === undefined || (Math.abs(dataValue.loc[1].toString() - Number(element.lon))) <= MIN_NUMBER) && - (dataValue.loc[2] === undefined || (Math.abs(dataValue.loc[2].toString() - Number(element.alt))) <= MIN_NUMBER)) { - return true; - } else { - return false; - } - }; - - var attrEqual = function(dataValue, element, onlyExistingAttr) { - var result = true; - if (dataValue.attributes !== undefined) { - Object.keys(dataValue.attributes).forEach(function(el) { - if (!onlyExistingAttr && element[el] !== dataValue.attributes[el]) { - result = false; - } else { - if (element[el] !== undefined && element[el] !== dataValue.attributes[el]) { - result = false; - } - } - }); - } - return result; - }; - - var pointsEqual = function(element, expected){ - - if (componentBasicTypes[expected.component] === "string") { - return element.value === expected.value; - } else if (componentBasicTypes[expected.component] === "number") { - var diff = Math.abs(element.value - expected.value); - return diff < MIN_NUMBER; - } else if (componentBasicTypes[expected.component] === "bytearray") { - return (element.value.equals(expected.value)); - } else if (componentBasicTypes[expected.component] === "boolean") { - return element.value === expected.value; - } - return false; - }; - - var comparePoints = function(dataValues, points, onlyExistingAttributes) { - var result = true; - var reason = ""; - var onlyExistingAttr = onlyExistingAttributes === undefined ? false : onlyExistingAttributes; - if (points.length !== dataValues.length) { - return "Wrong number of returned points"; - } - points.forEach(function(element, index) { - if ((element.ts !== dataValues[index].ts) || - !pointsEqual(element, dataValues[index]) || - !locEqual(dataValues[index], element, onlyExistingAttr) || - !attrEqual(dataValues[index], element, onlyExistingAttr)) { - result = false; - reason = "Point " + JSON.stringify(element) + " does not fit to expected value " + - JSON.stringify(dataValues[index]); - } - }); - if (result === true) {return true;} - else {return reason;} - }; - - var calcAggregationsPerComponent = function(flattenedArray) { - - return flattenedArray.reduce(function(acc, val) { - if (aggregateable[val.component] === 0) { - return acc; - } - if (val.value > acc[val.component][aggregation.MAX]) { - acc[val.component][aggregation.MAX] = val.value; - } - if (val.value < acc[val.component][aggregation.MIN]) { - acc[val.component][aggregation.MIN] = val.value; - } - acc[val.component][aggregation.COUNT]++; - acc[val.component][aggregation.SUM] += val.value; - acc[val.component][aggregation.SUMOFSQUARES] += val.value * val.value; - return acc; - }, [[Number.MIN_VALUE, Number.MAX_VALUE, 0, 0, 0], [Number.MIN_VALUE, Number.MAX_VALUE, 0, 0, 0]]); - }; - - //********************* Main Object *****************// - //---------------------------------------------------// - return { - "sendAggregatedDataPoints": function(done) { - //To be independent of main tests, own sensors, actuators, and commands have to be created - promtests.addComponent(componentNames[0], componentTypes[0], userToken, accountId, deviceId) - .then((id) => { - componentId[0] = id; - }) - .then(() => promtests.addComponent(componentNames[1], componentTypes[1], userToken, accountId, deviceId)) - .then((id) => { - componentId[1] = id; - }) - .then(() => promtests.addComponent(componentNames[2], componentTypes[2], userToken, accountId, deviceId)) - .then((id) => { - componentId[2] = id; - }) - .then(() => promtests.addComponent(componentNames[3], componentTypes[3], userToken, accountId, deviceId)) - .then((id) => { - componentId[3] = id; - }) - .then(() => { - var proms = []; - dataValues1Time = 0 + BASE_TIMESTAMP; - dataValues1.forEach(function(element) { - proms.push(promtests.submitDataList(element, deviceToken, accountId, deviceId, componentId)); - }); - return Promise.all(proms); - }) - .then(() => { - done(); - }) - .catch((err) => { - done(err); - }); - }, - "receiveAggregatedDataPoints": function(done) { - var listOfExpectedResults = flattenArray(dataValues1); - promtests.searchData(dataValues1Time, -1, userToken, accountId, deviceId, componentId[0], false, {}) - .then((result) => { - if (result.series.length !== 1) {return done("Wrong number of point series!");} - var comparisonResult = comparePoints(listOfExpectedResults, result.series[0].points); - if (comparisonResult === true) { - done(); - } else { - done(comparisonResult); - } - }) - .catch((err) => { - done(err); - }); - }, - "sendAggregatedMultipleDataPoints": function(done) { - var proms = []; - dataValues2Time = dataValues2[0][0].ts; - dataValues2.forEach(function(element) { - proms.push(promtests.submitDataList(element, deviceToken, accountId, deviceId, componentId, {})); - }); - Promise.all(proms) - .then(() => { - done(); - }) - .catch((err) => { - done(err); - }); - }, - "receiveAggregatedMultipleDataPoints": function(done) { - var pValues = prepareValues(dataValues2); - var foundComponentsMap = pValues.numComponents; - var listOfExpectedResults = pValues.listOfExpectedResults; - - promtests.searchData(dataValues2Time, -1, userToken, accountId, deviceId, componentId, false, {}) - .then((result) => { - if (result.series.length !== componentId.length) { - return done("Wrong number of point series!"); - } - //Mapping is needed because the results are not in sending order - // e.g. component[0] could be now be in series[3] - var err = 0; - var mapping = findMapping(foundComponentsMap, componentId, result.series); - Object.entries(mapping).forEach(function(element){ - var comparisonResult = comparePoints(listOfExpectedResults[element[0]], result.series[element[1]].points); - if (comparisonResult !== true) { - err = 1 ; - done(comparisonResult); - } - }); - if (!err) { - done(); - } - }) - .catch((err) => { - done(err); - }); - }, - "sendDataPointsWithLoc": function(done) { - var proms = []; - dataValues3Time = dataValues3[0][0].ts; - dataValues3.forEach(function(element) { - proms.push(promtests.submitDataList(element, deviceToken, accountId, deviceId, componentId)); - }); - Promise.all(proms) - .then(() => { - done(); - }) - .catch((err) => { - done(err); - }); - }, - "receiveDataPointsWithLoc": function(done) { - var flattenedDataValues = flattenArray(dataValues3); - promtests.searchData(dataValues3Time, -1, userToken, accountId, deviceId, componentId[0], true, {}) - .then((result) => { - if (result.series.length !== 1) {return done("Wrong number of point series!");} - var comparisonResult = comparePoints(flattenedDataValues, result.series[0].points); - if (comparisonResult !== true) { - done(comparisonResult); - } else { - done(); - } - }) - .catch((err) => { - done(err); - }); - - }, - "sendDataPointsWithAttributes": function(done) { - var proms = []; - dataValues4Time = dataValues4[0][0].ts; - dataValues4.forEach(function(element) { - proms.push(promtests.submitDataList(element, deviceToken, accountId, deviceId, componentId)); - }); - Promise.all(proms) - .then(() => { - done(); - }) - .catch((err) => { - done(err); - }); - }, - "receiveDataPointsWithAttributes": function(done) { - var pValues = prepareValues(dataValues4); - var foundComponentMap = pValues.numComponents; - var flattenedDataValues = pValues.flattenedDataValues; - promtests.searchDataAdvanced(dataValues4Time, -1, userToken, accountId, deviceId, componentId, true, undefined, undefined, undefined) - .then((result) => { - var mapping = findMapping(foundComponentMap, componentId, result.data[0].components); - if (result.data[0].components.length !== componentId.length) { - return done("Wrong number of point series!"); - } - var err = false; - var resultObjects = Object.entries(mapping).reduce((accum, mappingElem) => { - var testresult = - result.data[0].components[mappingElem[1]].samples.reduce((accum_inner, comp) => { - accum_inner.push(createObjectFromData(comp, - result.data[0].components[mappingElem[1]].samplesHeader)); - return accum_inner; - }, []); - return accum.concat(testresult); - }, []); - var comparisonResult = comparePoints(flattenedDataValues, resultObjects); - if (comparisonResult !== true) { - err = 1; - return done(comparisonResult); - } - if (!err) { - return done(); - } - }) - .catch((err) => { - done(err); - }); - - }, - "receiveDataPointsWithSelectedAttributes": function(done) { - var keys = ["key1"]; - var pValues = prepareValues(dataValues4); - var foundComponentMap = pValues.numComponents; - var flattenedDataValues = flattenArray(dataValues4); - promtests.searchDataAdvanced(dataValues4Time, -1, userToken, accountId, deviceId, componentId, false, keys, undefined, undefined) - .then((result) => { - if (result.data[0].components.length !== componentId.length) { - return done("Wrong number of point series!"); - } - var mapping = findMapping(foundComponentMap, componentId, result.data[0].components); - - var err = false; - var resultObjects = Object.entries(mapping).reduce((accum, mappingElem) => { - if (mappingElem[1] < 0) { - return accum; - } - var testresult = - result.data[0].components[mappingElem[1]].samples.reduce((accum_inner, comp) => { - accum_inner.push(createObjectFromData(comp, - result.data[0].components[mappingElem[1]].samplesHeader)); - return accum_inner; - }, []); - return accum.concat(testresult); - }, []); - var comparisonResult = comparePoints(flattenedDataValues, resultObjects, true); - if (comparisonResult !== true) { - err = 1; - return done(comparisonResult); - } else if (!err){ - return done(); - } - }) - .catch((err) => { - done(err); - }); - }, - "receiveDataPointsCount": function(done) { - var expectedRowCount = flattenArray(dataValues1).length + - flattenArray(dataValues2).length + - flattenArray(dataValues3).length + - flattenArray(dataValues4).length; - promtests.searchDataAdvanced(dataValues1Time, -1, userToken, accountId, deviceId, componentId, false, undefined, undefined, true) - .then((result) => { - if (result.data[0].components.length !== componentId.length) { - return done("Wrong number of point series!"); - } - - assert.equal(result.rowCount, expectedRowCount); - done(); - }) - .catch((err) => { - done(err); - }); - }, - "receiveAggregations": function(done) { - var foundComponentMap = {0: 0, 1: 1}; // Only component 1 and 2 are numbers and can aggregate - var aggr1 = calcAggregationsPerComponent(flattenArray(dataValues1)); - var aggr2 = calcAggregationsPerComponent(flattenArray(dataValues2)); - var aggr3 = calcAggregationsPerComponent(flattenArray(dataValues3)); - var aggr4 = calcAggregationsPerComponent(flattenArray(dataValues4)); - var allAggregation = [aggr1, aggr2, aggr3, aggr4].reduce(function(acc, val) { - [0, 1].forEach(function(index) { - if (acc[index][aggregation.MAX] < val[index][aggregation.MAX]) { - acc[index][aggregation.MAX] = val[index][aggregation.MAX]; - } - if (val[index][aggregation.COUNT] && acc[index][aggregation.MIN] > val[index][aggregation.MIN]) { - acc[index][aggregation.MIN] = val[index][aggregation.MIN]; - } - acc[index][aggregation.COUNT] += val[index][aggregation.COUNT]; - acc[index][aggregation.SUM] += val[index][aggregation.SUM]; - acc[index][aggregation.SUMOFSQUARES] += val[index][aggregation.SUMOFSQUARES]; - }); - return acc; - }, [[Number.MIN_VALUE, Number.MAX_VALUE, 0, 0, 0], [Number.MIN_VALUE, Number.MAX_VALUE, 0, 0, 0]]); - - promtests.searchDataAdvanced(dataValues1Time, -1, userToken, accountId, deviceId, componentId, false, undefined, "only", false) - .then((result) => { - if (result.data[0].components.length !== componentId.length) { - return done("Wrong number of point series!"); - } - var mapping = findMapping(foundComponentMap, componentId, result.data[0].components); - [0, 1].forEach(function(index) { - assert.closeTo(allAggregation[index][aggregation.MAX], result.data[0].components[mapping[index]].max, MIN_NUMBER); - assert.closeTo(allAggregation[index][aggregation.MIN], result.data[0].components[mapping[index]].min, MIN_NUMBER); - assert.closeTo(allAggregation[index][aggregation.COUNT], result.data[0].components[mapping[index]].count, MIN_NUMBER); - assert.closeTo(allAggregation[index][aggregation.SUM], result.data[0].components[mapping[index]].sum, MIN_NUMBER); - assert.closeTo(allAggregation[index][aggregation.SUMOFSQUARES], result.data[0].components[mapping[index]].sumOfSquares, MIN_NUMBER); - }); - done(); - }) - .catch((err) => { - done(err); - }); - }, - "receiveSubset": function(done) { - promtests.searchDataAdvanced(dataValues2Time + 30, dataValues2Time + 60, - userToken, accountId, deviceId, [componentId[0]], false, undefined, undefined, false) - .then((result) => { - if (result.data[0].components.length !== 1) {done("Wrong number of point series!");} - assert.equal(result.rowCount, 3); - done(); - }) - .catch((err) => { - done(err); - }); - }, - "sendMaxAmountOfSamples": function(done) { - var dataList = []; - - for (var i = 0; i < MAX_SAMPLES; i++) { - var ts = (i + 1) * 1000000 + BASE_TIMESTAMP; - var obj = { - component: 0, - ts: ts, - value: i - }; - dataList.push(obj); - } - promtests.submitDataList(dataList, deviceToken, accountId, deviceId, componentId) - .then(() => { - done(); - }) - .catch((err) => { - done(err); - }); - }, - "receiveMaxAmountOfSamples": function(done) { - promtests.searchDataAdvanced(BASE_TIMESTAMP + 1000000, MAX_SAMPLES * 1000000 + BASE_TIMESTAMP, - userToken, accountId, deviceId, [componentId[0]], false, undefined, undefined, false) - .then((result) => { - if (result.data[0].components.length !== 1) {return done("Wrong number of point series!");} - assert.equal(result.rowCount, MAX_SAMPLES); - var samples = result.data[0].components[0].samples; - samples.forEach(function(element, i) { - assert.equal(element[1], i); - assert.equal(element[0], (i + 1) * 1000000 + BASE_TIMESTAMP); - }); - done(); - }) - .catch((err) => { - done(err); - }); - }, - "waitForBackendSynchronization": function(delay, done) { - setTimeout(done, delay); - - }, - "sendPartiallyWrongData": function(done) { - var proms = []; - dataValues5StartTime = dataValues5[0][0].ts; - var dataValues5lastElement = dataValues5[dataValues5.length - 1]; - var dataValues5lastLength = dataValues5[dataValues5.length - 1].length; - dataValues5StopTime = dataValues5lastElement[dataValues5lastLength - 1].ts; - var wrongId = uuidv4(); // 6th id is random - dataValues5.forEach(function(element) { - proms.push(promtests.submitDataList(element, deviceToken, accountId, deviceId, componentId.concat(wrongId), {})); - }); - Promise.all(proms.map(p => p.catch(e => e))) - .then(results => { - var parsedResults = results.map( (result) => { - //some results are string, some others objects - //Therefore if parsing fails, it must be an object already - try { - return JSON.parse(result); - } catch (e) { - return result; - } - }); - assert.equal(parsedResults[0].code, 1412); - assert.equal(parsedResults[1].code, 6402); - assert.equal(parsedResults[2].code, 6402); - done(); - }) - .catch(err => done(err)); - - }, - "receivePartiallySentData": function(done) { - var listOfExpectedResults = flattenArray(dataValues5) - .filter((elem) => elem.component !== 2); - promtests.searchData(dataValues5StartTime, dataValues5StopTime, userToken, accountId, deviceId, componentId[0], false, {}) - .then((result) => { - if (result.series.length !== 1) { - return done("Wrong number of point series!"); - } - var comparisonResult = comparePoints(listOfExpectedResults, result.series[0].points); - if (comparisonResult === true) { - done(); - } else { - done(comparisonResult); - } - }) - .catch((err) => { - done(err); - }); - }, - "sendDataAsAdmin": function(done) { - dataValues6StartTime = dataValues6[0].ts; - dataValues6StopTime = dataValues6[1].ts; - var username = process.env.USERNAME; - var password = process.env.PASSWORD; - assert.isNotEmpty(username, "no username provided"); - assert.isNotEmpty(password, "no password provided"); - promtests.authGetToken(username, password) - .then((grant) => promtests.submitDataListAsUser(dataValues6, grant.token, accountId, deviceId, componentId, {})) - .then(() => { - done(); - }) - .catch((err) => { - done(new Error(err)); - }); - }, - "sendDataAsUser": function(done) { - var username = process.env.USERNAME; - var password = process.env.PASSWORD; - var username2 = process.env.USERNAME2; - var password2 = process.env.PASSWORD2; - var admin2Token; - var inviteId; - assert.isNotEmpty(username, "no username provided"); - assert.isNotEmpty(password, "no password provided"); - assert.isNotEmpty(username2, "no username provided"); - assert.isNotEmpty(password2, "no password provided"); - //First create a user for the account, accept the invitation and try to send data - promtests.authGetToken(username, password) - .then((grant) => {return promtests.createInvitation(grant.token, accountId, username2);}) - .then((result) => {inviteId = result._id; return promtests.authGetToken(username2, password2);}) - .then((grant) => promtests.acceptInvitation(grant.token, accountId, inviteId)) - .then(() => promtests.authGetToken(username2, password2)) - .then((grant) => admin2Token = grant.token) - .then(() => promtests.submitDataListAsUser(dataValues7, - admin2Token, accountId, deviceId, componentId, {}).catch(e => e)) - .then((result) => { - result = JSON.parse(result); - assert.equal(result.code, errors.Generic.NotAuthorized.code); - assert.equal(result.status, errors.Generic.NotAuthorized.status); - assert.equal(result.message, errors.Generic.NotAuthorized.message); - done(); - }) - .catch((err) => { - done(err); - }); - }, - "sendDataAsAdminWithWrongAccount": function(done) { - assert.isNotEmpty(username2, "no username provided"); - assert.isNotEmpty(password2, "no password provided"); - promtests.authGetToken(username2, password2) - .then((grant) => { - return promtests.createAccount(accountName2, grant.token); - }) - .then(() => promtests.authGetToken(username2, password2)) - .then((grant) => userToken2 = grant.token) - .then(() => promtests.authTokenInfo(userToken2)) - .then((tokenInfo) => { - accountId2 = tokenInfo.payload.accounts[0].id; - return accountId2;}) - .then((accountId2) => - promtests.submitDataListAsUser(dataValues7, - userToken2, accountId2, deviceId, componentId, {}).catch(e => e)) - .then((result) => { - var parsedResult = JSON.parse(result); - assert.equal(parsedResult.code, 401); - done(); - }) - .catch((err) => { - done(err); - }); - }, - "receiveDataFromAdmin": function(done) { - var listOfExpectedResults = dataValues6; - promtests.searchData(dataValues6StartTime, dataValues6StopTime, userToken, accountId, deviceId, componentId[0], false, {}) - .then((result) => { - if (result.series.length !== 1) {return done("Wrong number of point series!");} - var comparisonResult = comparePoints(listOfExpectedResults, result.series[0].points); - if (comparisonResult === true) { - done(); - } else { - done(comparisonResult); - } - }) - .catch((err) => { - done(err); - }); - }, - "sendDataAsDeviceToWrongDeviceId": function(done) { - var username = process.env.USERNAME; - var password = process.env.PASSWORD; - var newDeviceName = "innocentDevice"; - var componentName = "evilDeviceComponent"; - var componentType = componentTypes[0]; - assert.isNotEmpty(username, "no username provided"); - assert.isNotEmpty(password, "no password provided"); - //First create a user for the account, accept the invitation and try to send data - promtests.authGetToken(username, password) - .then((grant) => promtests.createDevice(newDeviceName, newDeviceId, grant.token, accountId)) - .then(() => promtests.activateDevice(userToken, accountId, newDeviceId)) - .then(() => { - return promtests.addComponent(componentName, componentType, userToken, accountId, newDeviceId); - }) - .then((id) => {newComponentId = id;}) - .then(() => promtests.submitDataList(dataValues7, - deviceToken, accountId, newDeviceId, newComponentId, {}).catch(e => e)) - .then((result) => { - var parsedResult = JSON.parse(result); - assert.equal(parsedResult.code, 401); - done(); - }) - .catch((err) => { - done(err); - }); - }, - "send8000SamplesForAutoDownsampleTest": function(done) { - var dataList = [ [], [], [], [], [], [], [], [] ]; - for (var j = 0; j < DOWNSAMPLE_MULT; j++) { - for (var i = MAX_SAMPLES * j; i < MAX_SAMPLES * (j + 1); i++) { - var ts = i * 1000 + BASE_TIMESTAMP + 1000000; - var obj = { - component: 1, - ts: ts, - value: i - }; - dataList[j].push(obj); - } - } - promtests.submitDataList(dataList[0], deviceToken, accountId, deviceId, componentId) - .then(() => promtests.submitDataList(dataList[1], deviceToken, accountId, deviceId, componentId)) - .then(() => promtests.submitDataList(dataList[2], deviceToken, accountId, deviceId, componentId)) - .then(() => promtests.submitDataList(dataList[3], deviceToken, accountId, deviceId, componentId)) - .then(() => promtests.submitDataList(dataList[4], deviceToken, accountId, deviceId, componentId)) - .then(() => promtests.submitDataList(dataList[5], deviceToken, accountId, deviceId, componentId)) - .then(() => promtests.submitDataList(dataList[6], deviceToken, accountId, deviceId, componentId)) - .then(() => promtests.submitDataList(dataList[7], deviceToken, accountId, deviceId, componentId)) - .then(() => { - done(); - }) - .catch((err) => { - done(err); - }); - }, - "receiveRawData": function(done) { - promtests.searchData(BASE_TIMESTAMP + 1000000, MAX_SAMPLES * DOWNSAMPLE_MULT * 1000 + 1000000 + BASE_TIMESTAMP, - userToken, accountId, deviceId, componentId[1], false, {}) - .then((result) => { - if (result.series.length !== 1) {return done("Wrong number of point series!");} - assert.equal(result.series[0].points.length, MAX_SAMPLES_RETRIVE); - var samples = result.series[0].points; - samples.forEach(function(element, i) { - assert.equal(element.value, i); - assert.equal(element.ts, i * 1000 + 1000000 + BASE_TIMESTAMP); - }); - done(); - }) - .catch((err) => { - done(err); - }); - }, - "receiveMaxItems": function(done) { - promtests.searchDataMaxItems(BASE_TIMESTAMP + 1000000, MAX_SAMPLES * DOWNSAMPLE_MULT * 1000 + 1000000 + BASE_TIMESTAMP, - userToken, accountId, deviceId, [componentId[1]], false, {}, MAX_ITEMS_TEST_SAMPLES) - .then((result) => { - if (result.series.length !== 1) {return done("Wrong number of point series!");} - assert.equal(result.series[0].points.length, MAX_ITEMS_TEST_SAMPLES); - var samples = result.series[0].points; - samples.forEach(function(element, i) { - assert.equal(element.value, i); - }); - done(); - }) - .catch((err) => { - done(err); - }); - }, - "receiveAutoAggregatedAvgData": function(done) { - var aggregator = {}; - aggregator[componentId[1]] = {"name": "avg"}; - promtests.searchDataMaxItems(BASE_TIMESTAMP + 1000000, MAX_SAMPLES * DOWNSAMPLE_MULT * 1000 + 1000000 + BASE_TIMESTAMP, - userToken, accountId, deviceId, [componentId[1]], false, {}, null, null, aggregator) - .then((result) => { - if (result.series.length !== 1) {return done("Wrong number of point series!");} - assert.equal(result.series[0].points.length, MAX_SAMPLES_RETRIVE); - var samples = result.series[0].points; - samples.forEach(function(element, i) { - assert.equal(element.value, (i * 2) + 0.5); - assert.equal(element.ts, (i * 2) * 1000 + 1000000 + BASE_TIMESTAMP); - }); - done(); - }) - .catch((err) => { - done(err); - }); - }, - "receiveAutoAggregatedMaxData": function(done) { - var aggregator = {}; - aggregator[componentId[1]] = {"name": "max"}; - promtests.searchDataMaxItems(BASE_TIMESTAMP + 1000000, MAX_SAMPLES * DOWNSAMPLE_MULT * 1000 + 1000000 + BASE_TIMESTAMP, - userToken, accountId, deviceId, [componentId[1]], false, {}, null, null, aggregator) - .then((result) => { - if (result.series.length !== 1) {return done("Wrong number of point series!");} - assert.equal(result.series[0].points.length, MAX_SAMPLES_RETRIVE); - var samples = result.series[0].points; - samples.forEach(function(element, i) { - assert.equal(element.value, (i * 2) + 1); - assert.equal(element.ts, (i * 2) * 1000 + 1000000 + BASE_TIMESTAMP); - }); - done(); - }) - .catch((err) => { - done(err); - }); - }, - "receiveAutoAggregatedMinData": function(done) { - var aggregator = {}; - aggregator[componentId[1]] = {"name": "min"}; - promtests.searchDataMaxItems(BASE_TIMESTAMP + 1000000, MAX_SAMPLES * DOWNSAMPLE_MULT * 1000 + 1000000 + BASE_TIMESTAMP, - userToken, accountId, deviceId, [componentId[1]], false, {}, null, null, aggregator) - .then((result) => { - if (result.series.length !== 1) {return done("Wrong number of point series!");} - assert.equal(result.series[0].points.length, MAX_SAMPLES_RETRIVE); - var samples = result.series[0].points; - samples.forEach(function(element, i) { - assert.equal(element.value, (i * 2)); - assert.equal(element.ts, (i * 2) * 1000 + 1000000 + BASE_TIMESTAMP); - }); - done(); - }) - .catch((err) => { - done(err); - }); - }, - "receiveAutoAggregatedSumData": function(done) { - var aggregator = {}; - aggregator[componentId[1]] = {"name": "sum"}; - promtests.searchDataMaxItems(BASE_TIMESTAMP + 1000000, MAX_SAMPLES * DOWNSAMPLE_MULT * 1000 + 1000000 + BASE_TIMESTAMP, - userToken, accountId, deviceId, [componentId[1]], false, {}, MAX_ITEMS_TEST_SAMPLES, null, aggregator) - .then((result) => { - if (result.series.length !== 1) {return done("Wrong number of point series!");} - assert.equal(result.series[0].points.length, MAX_ITEMS_TEST_SAMPLES); - var samples = result.series[0].points; - samples.forEach(function(element, i) { - var n = i * 8 + 8; - var sum = (n * (n - 1)) / 2; // sum of all numbers up to n - var old_sum = (n - 8) * (n - 9) / 2; // sum of previous n-8 round - assert.equal(element.value, (sum - old_sum)); - old_sum = n; - assert.equal(element.ts, (i * 8) * 1000 + 1000000 + BASE_TIMESTAMP); - }); - done(); - }) - .catch((err) => { - done(err); - }); - }, - "receiveAggregatedAvgData": function(done) { - var aggregator = {}; - aggregator[componentId[1]] = {"name": "avg", "sampling": {"unit": "seconds", "value": 3}}; - promtests.searchDataMaxItems(BASE_TIMESTAMP + 1000000, MAX_SAMPLES * DOWNSAMPLE_MULT * 1000 + 1000000 + BASE_TIMESTAMP, - userToken, accountId, deviceId, [componentId[1]], false, {}, null, null, aggregator) - .then((result) => { - if (result.series.length !== 1) {return done("Wrong number of point series!");} - var numExptectedSamples = Math.ceil(MAX_SAMPLES_RETRIVE/3.0); - assert.equal(result.series[0].points.length, numExptectedSamples); - var samples = result.series[0].points; - samples.forEach(function(element, i) { - assert.equal(element.ts, (i * 3) * 1000 + 1000000 + BASE_TIMESTAMP); - if (i < numExptectedSamples - 1) { - assert.equal(element.value, (i * 3) + 1); - } else { // exception for last sample - assert.equal(element.value, (i * 3)); - } - }); - done(); - }) - .catch((err) => { - done(err); - }); - }, - "receiveAggregatedAvgDataMS": function(done) { - var aggregator = {}; - aggregator[componentId[1]] = {"name": "avg", "sampling": {"unit": "milliseconds", "value": 1500}}; - promtests.searchDataMaxItems(BASE_TIMESTAMP + 1000000, MAX_SAMPLES * DOWNSAMPLE_MULT * 1000 + 1000000 + BASE_TIMESTAMP, - userToken, accountId, deviceId, [componentId[1]], false, {}, null, null, aggregator) - .then((result) => { - if (result.series.length !== 1) {return done("Wrong number of point series!");} - var numExptectedSamples = Math.ceil(MAX_SAMPLES_RETRIVE/1.5); - assert.equal(result.series[0].points.length, numExptectedSamples); - var samples = result.series[0].points; - samples.forEach(function(element, i) { - assert.equal(element.ts, Math.round(i * 1.5) * 1000 + 1000000 + BASE_TIMESTAMP); - if (i < numExptectedSamples - 1) { - assert.equal(element.value, (i * 1.5) + 0.5); - } else { // exception for last sample - assert.equal(element.value, (i * 1.5)); - } - }); - done(); - }) - .catch((err) => { - done(err); - }); - }, - "receiveAggregatedAvgDataMinutes": function(done) { - var aggregator = {}; - aggregator[componentId[1]] = {"name": "avg", "sampling": {"unit": "minutes", "value": 1}}; - promtests.searchDataMaxItems(BASE_TIMESTAMP + 1000000, MAX_SAMPLES * DOWNSAMPLE_MULT * 1000 + 1000000 + BASE_TIMESTAMP, - userToken, accountId, deviceId, [componentId[1]], false, {}, null, null, aggregator) - .then((result) => { - if (result.series.length !== 1) {return done("Wrong number of point series!");} - var numExptectedSamples = Math.ceil(MAX_SAMPLES_RETRIVE/60); - assert.equal(result.series[0].points.length, numExptectedSamples); - var samples = result.series[0].points; - samples.forEach(function(element, i) { - assert.equal(element.ts, Math.round(i * 60) * 1000 + 1000000 + BASE_TIMESTAMP); - if (i < numExptectedSamples - 1) { - assert.equal(element.value, (i * 60) + 29.5); - } else { // exception for last sample - assert.equal(element.value, (i * 60) + 19.5); - } - }); - done(); - }) - .catch((err) => { - done(err); - }); - }, - "receiveRawDataDesc": function(done) { - var orders = {}; - orders[componentId[1]] = "desc"; - promtests.searchDataMaxItems(BASE_TIMESTAMP + 1000000, MAX_SAMPLES * DOWNSAMPLE_MULT * 1000 + 1000000 + BASE_TIMESTAMP, - userToken, accountId, deviceId, [componentId[1]], false, {}, null, orders, null) - .then((result) => { - if (result.series.length !== 1) {return done("Wrong number of point series!");} - assert.equal(result.series[0].points.length, MAX_SAMPLES_RETRIVE); - var samples = result.series[0].points; - samples.forEach(function(element, i) { - assert.equal(element.value, 7999 - i); - assert.equal(element.ts, (7999 - i) * 1000 + 1000000 + BASE_TIMESTAMP); - }); - done(); - }) - .catch((err) => { - done(err); - }); - }, - "receiveRawDataLatest": function(done) { - var orders = {}; - orders[componentId[1]] = "desc"; - promtests.searchDataMaxItems(BASE_TIMESTAMP + 1000000, MAX_SAMPLES * DOWNSAMPLE_MULT * 1000 + 1000000 + BASE_TIMESTAMP, - userToken, accountId, deviceId, [componentId[1]], false, {}, 1, orders, null) - .then((result) => { - if (result.series.length !== 1) {return done("Wrong number of point series!");} - assert.equal(result.series[0].points.length, 1); - var samples = result.series[0].points; - var element = samples[0]; - assert.equal(element.value, 7999); - assert.equal(element.ts, (7999) * 1000 + 1000000 + BASE_TIMESTAMP); - done(); - }) - .catch((err) => { - done(err); - }); - }, - "receiveAggregatedDataFromMultipleComponents": function(done) { - var aggregator = {}; - aggregator[componentId[1]] = {"name": "avg"}; - aggregator[componentId[0]] = {"name": "max", "sampling": {"unit": "seconds", "value": 1000}}; - promtests.searchDataMaxItems(BASE_TIMESTAMP + 1000000, MAX_SAMPLES * DOWNSAMPLE_MULT * 1000 + 1000000 + BASE_TIMESTAMP, - userToken, accountId, deviceId, [componentId[1], componentId[0]], false, {}, 100, null, aggregator) - .then((result) => { - if (result.series.length !== 2) {return done("Wrong number of point series!");} - // the ordering of components in the results are non-deterministic - // so we have to permutate - var perm = {}; - if (result.series[0].componentId === componentId[0]) { - perm = {"0":0, "1":1}; - } else { - perm = {"1": 0, "0": 1}; - } - var numExptectedSamples = [9, 100]; - assert.equal(result.series[perm[0]].points.length, numExptectedSamples[0]); - assert.equal(result.series[perm[1]].points.length, numExptectedSamples[1]); - var samples = [result.series[perm[0]].points, result.series[perm[1]].points]; - samples[0].forEach(function(element, i) { - assert.equal(element.ts, ((i + 1) * 1000000) + BASE_TIMESTAMP); - assert.equal(element.value, i); - }); - samples[1].forEach(function(element, i) { - assert.equal(element.ts, (i * 1000 * 80) + 1000000 + BASE_TIMESTAMP); - assert.equal(element.value, (i * 80) + 39.5); - }); - done(); - }) - .catch((err) => { - done(err); - }); - }, - "cleanup": function(done) { - promtests.deleteComponent(userToken, accountId, deviceId, componentId[0]) - .then(() => promtests.deleteComponent(userToken, accountId, deviceId, componentId[1])) - .then(() => promtests.deleteComponent(userToken, accountId, newDeviceId, newComponentId)) - .then(() => promtests.deleteDevice(userToken, accountId, newDeviceId)) - .then(() => promtests.deleteAccount(userToken2, accountId2)) - .then(() => promtests.deleteInvite(userToken, accountId, username2)) - .then(() => { done(); }) - .catch((err) => { - done(err); - }); - } - }; -}; - -var descriptions = { - "sendAggregatedDataPoints": "Shall send multiple datapoints for one component", - "receiveAggregatedDataPoints": "Shall receive multiple datapoints for one component", - "sendAggregatedMultipleDataPoints": "Shall send multiple datapoints for 4 components", - "receiveAggregatedMultipleDataPoints": "Shall receive multiple datapoints for 4 components", - "sendDataPointsWithLoc": "Sending data points with location metadata", - "receiveDataPointsWithLoc": "Receiving data points with location metadata", - "sendDataPointsWithAttributes": "Sending data points with attributes", - "receiveDataPointsWithAttributes": "Receiving data points with all attributes", - "receiveDataPointsCount": "Receive only count of points", - "receiveAggregations": "Receive Max, Min, etc. aggregations", - "receiveSubset": "receive subset based on timestamps", - "sendMaxAmountOfSamples": "Send maximal allowed samples per request", - "receiveMaxAmountOfSamples": "Receive maximal allowed samples per request", - "receiveDataPointsWithSelectedAttributes": "Receiving data points with selected attributes", - "waitForBackendSynchronization": "Waiting maximal tolerable time backend needs to flush so that points are available", - "sendPartiallyWrongData": "Send data with partially unknown cid's", - "receivePartiallySentData": "Recieve the submitted data of the partially wrong data", - "sendDataAsAdmin": "Send test data as admin on behalf of a device", - "sendDataAsUser": "Send test data with user role and get rejected", - "sendDataAsAdminWithWrongAccount": "Send test data as admin with wrong accountId", - "receiveDataFromAdmin": "Test whether data sent from admin earlier has been stored", - "send8000SamplesForAutoDownsampleTest": "Send enough data to check auto downsample", - "sendDataAsDeviceToWrongDeviceId": "Test whether Device data submission is rejected if it goes to wrong device", - "receiveRawData": "Receive auto downsampled data", - "receiveMaxItems": "Receive max requested items", - "receiveAutoAggregatedAvgData": "Receive auto downsampled data with Avg aggregator", - "receiveAggregatedAvgData": "Receive downsampled data with Avg aggregator and explicit second sampling", - "receiveAutoAggregatedMaxData": "Receive auto downsampled data with Max aggregator", - "receiveAutoAggregatedMinData": "Receive auto downsampled data with Min aggregator", - "receiveAutoAggregatedSumData": "Receive auto downsampled data with Min aggregator", - "receiveAggregatedAvgDataMS": "Receive downsampled data with milliseconds", - "receiveAggregatedAvgDataMinutes": "Receive downsampled data with minutes", - "receiveRawDataDesc": "Receive data in desc order", - "receiveRawDataLatest": "Receive latest data", - "receiveAggregatedDataFromMultipleComponents": "Receive multiple aggregated components", - "cleanup": "Cleanup components, commands created for subtest" -}; - -module.exports = { - test: test, - descriptions: descriptions -}; diff --git a/tests/subtests/device-activation-tests.js b/tests/subtests/device-activation-tests.js deleted file mode 100644 index 33742c16..00000000 --- a/tests/subtests/device-activation-tests.js +++ /dev/null @@ -1,78 +0,0 @@ -var test = function(token, accountId1) { - var promtests = require('./promise-wrap'); - var activationCode1; - var activationCode2; - var accountId2; - var deviceId1 = "ACTIVATION-TEST1"; - var deviceId2 = "ACTIVATION-TEST2"; - var userToken = token; - - return { - "prepareSetup": function(done) { - promtests.createDevice("device1", deviceId1, userToken, accountId1) - .then(() => promtests.getAccountActivationCode(accountId1, userToken)) - .then((res) => { activationCode1 = res.activationCode; }) - .then(() => { done(); }) - .catch((err) => { done(err); }); - }, - "activateExistingDeviceWithoutToken": function(done) { - promtests.activateDeviceWithoutToken(activationCode1, deviceId1).then((res) => { - if (res.deviceToken) { - done(); - } else { - done('Cannot activate device without user token.'); - } - }).catch((err) => { - done(err); - }); - }, - "activateAnotherDeviceWithSameIdInAnotherAccount": function(done) { - promtests.createAccount("ExistingDeviceIdTest", userToken) - .then((res) => { accountId2 = res.id; }) - .then(() => promtests.authGetToken(process.env.USERNAME, process.env.PASSWORD)) - .then((grant) => { userToken = grant.token; }) - .then(() => promtests.createDevice("device1", deviceId1, userToken, accountId2)) - .then(() => promtests.getAccountActivationCode(accountId2, userToken)) - .then((res) => { activationCode2 = res.activationCode; }) - .then(() => promtests.activateDeviceWithoutToken(activationCode2, deviceId1)).then((res) => { - if (res.deviceToken) { - done(); - } else { - done('Cannot activate device with same id in another account.'); - } - }) - .catch((err) => { done(err); }); - }, - "activateNotExistingDeviceWithoutToken": function(done) { - promtests.activateDeviceWithoutToken(activationCode1, deviceId2).then((res) => { - if (res.deviceToken) { - done(); - } else { - done('Cannot activate not existing device without token'); - } - }).catch((err) => { - done(err); - }); - }, - "cleanup": function(done) { - promtests.deleteDevice(userToken, accountId1, deviceId1) - .then(() => { promtests.deleteDevice(userToken, accountId1, deviceId2); }) - .then(() => promtests.deleteAccount(userToken, accountId2)) - .then(() => { done(); }) - .catch((err) => { done(err); }); - } - }; -}; - -var descriptions = { - "prepareSetup": "Create device for subtest", - "activateExistingDeviceWithoutToken": "Shall activate a device only with activation code", - "activateAnotherDeviceWithSameIdInAnotherAccount": "Shall create and activate another device with same id in different account", - "activateNotExistingDeviceWithoutToken": "Shall create and activate device only with activation code", - "cleanup": "Cleanup devices that are created for subtest", -}; - -module.exports = { - test: test, - descriptions: descriptions -}; diff --git a/tests/subtests/grafana-tests.js b/tests/subtests/grafana-tests.js deleted file mode 100644 index e0a44b96..00000000 --- a/tests/subtests/grafana-tests.js +++ /dev/null @@ -1,374 +0,0 @@ -/** - * Copyright (c) 2019 Intel Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/*jshint esversion: 6 */ -/*jshint undef: true, unused: true */ -/* jshint node: true */ - -"use strict"; - -var test = function(userToken1, userToken2) { - - var chai = require('chai'); - var tough = require('tough-cookie'); - var assert = chai.assert; - var config = require('../test-config.json'); - var request = require('request-promise').defaults({ jar: true }); - var componentName = "temperature-sensor-srt"; - var componentType = "temperature.v1.0"; - var promtests = require('./promise-wrap'); - var apiDataSourcePath = '/api/datasources/proxy'; - var refreshedUserToken1; - var refreshedUserToken2; - var accountId1_1; - var accountId1_2; - var accountId2; - var deviceId1_1 = "11-11-22-33-44-55"; - var deviceId1_2 = "12-11-22-33-44-55"; - var deviceId2 = "20-11-22-33-44-55"; - var deviceToken1_1; - var deviceToken1_2; - var deviceToken2; - var componentId1_1_1; - var componentId1_1_2; - var componentId1_2; - var componentId2; - var componentData1_1_1 = 15; - var componentData1_1_2 = 15; - var componentData1_2 = 20; - var componentData2 = 25; - var datasourceId; - var cookiejar1; - var cookiejar2; - var startTime = new Date(); - var grafanaUrl = config.grafana.protocol + '://' + config.grafana.host + ':' + - config.grafana.port + config.grafana.subPath; - var grafanaOptions = { - strictSSL: config.grafana.strictSSL, - proxy: config.grafana.proxy.host && config.grafana.proxy.port ? - config.grafana.protocol + '://' + config.grafana.proxy.host + ':' + - config.grafana.proxy.port : undefined, - timeout: config.grafana.timeout, - resolveWithFullResponse: true, - simple: false, - jar: true - }; - - - //********************* Main Object *****************// - //---------------------------------------------------// - return { - "prepareGrafanaTestSetup": function(done) { - // To be independent of main tests, own accounts, devices and components have to be created - promtests.createAccount("acc1_1", userToken1) - .then((response) => {accountId1_1 = response.id;}) - .then(() => promtests.createAccount("acc1_2", userToken1)) - .then((response) => {accountId1_2 = response.id;}) - .then(() => promtests.authGetToken(process.env.USERNAME, process.env.PASSWORD)) - .then((grant) => { userToken1 = grant.token; }) - .then(() => promtests.createAccount("acc2", userToken2)) - .then((response) => {accountId2 = response.id;}) - .then(() => promtests.authGetToken(process.env.USERNAME2, process.env.PASSWORD2)) - .then((grant) => { userToken2 = grant.token; }) - .then(() => promtests.createDevice("device1_1", deviceId1_1, userToken1, accountId1_1)) - .then(() => promtests.createDevice("device1_2", deviceId1_2, userToken1, accountId1_2)) - .then(() => promtests.createDevice("device2", deviceId2, userToken2, accountId2)) - .then(() => promtests.activateDevice(userToken1, accountId1_1, deviceId1_1)) - .then((response) => {deviceToken1_1 = response.deviceToken;}) - .then(() => promtests.activateDevice(userToken1, accountId1_2, deviceId1_2)) - .then((response) => {deviceToken1_2 = response.deviceToken;}) - .then(() => promtests.activateDevice(userToken2, accountId2, deviceId2)) - .then((response) => {deviceToken2 = response.deviceToken;}) - .then(() => promtests.addComponent(componentName + '1', componentType, userToken1, accountId1_1, deviceId1_1)) - .then((id) => {componentId1_1_1 = id;}) - .then(() => promtests.addComponent(componentName + '2', componentType, userToken1, accountId1_1, deviceId1_1)) - .then((id) => {componentId1_1_2 = id;}) - .then(() => promtests.addComponent(componentName, componentType, userToken1, accountId1_2, deviceId1_2)) - .then((id) => {componentId1_2 = id;}) - .then(() => promtests.addComponent(componentName, componentType, userToken2, accountId2, deviceId2)) - .then((id) => {componentId2 = id;}) - .then(() => promtests.submitData(componentData1_1_1, deviceToken1_1, accountId1_1, deviceId1_1, componentId1_1_1)) - .then(() => promtests.submitData(componentData1_1_2, deviceToken1_1, accountId1_1, deviceId1_1, componentId1_1_2)) - .then(() => promtests.submitData(componentData1_2, deviceToken1_2, accountId1_2, deviceId1_2, componentId1_2)) - .then(() => promtests.submitData(componentData2, deviceToken2, accountId2, deviceId2, componentId2)) - .then(() => { - var username = process.env.USERNAME; - var password = process.env.PASSWORD; - return promtests.authGetToken(username, password); - }) - .then((grant) => { refreshedUserToken1 = grant.token; }) - .then(() => { - var username = process.env.USERNAME2; - var password = process.env.PASSWORD2; - return promtests.authGetToken(username, password); - }) - .then((grant) => { refreshedUserToken2 = grant.token; }) - .then(() => { - var cookie1 = new tough.Cookie({ - key: "jwt", - value: refreshedUserToken1, - }); - var cookie2 = new tough.Cookie({ - key: "jwt", - value: refreshedUserToken2, - }); - cookiejar1 = request.jar(); - cookiejar1.setCookie(cookie1.toString(), config.grafana.protocol + "://" + config.grafana.host); - cookiejar2 = request.jar(); - cookiejar2.setCookie(cookie2.toString(), config.grafana.protocol + '://' + config.grafana.host); - Promise.resolve(); - }) - .then(() => { done(); }) - .catch((err) => { done(err); }); - }, - "checkGrafanaHeartbeat": function(done) { - var heartbeatPath = "/api/health"; - grafanaOptions.url = grafanaUrl + heartbeatPath; - request(grafanaOptions).then(res => { - if (res.statusCode === 200) { - done(); - } else { - done("Can't get heartbeat in grafana: " + res.statusCode); - } - }).catch(err => { done(err); }); - }, - "authenticateGrafanaAsViewer": function(done) { - // this endpoint is for admins only -- see grafana api for more information - var apiKeysPath = '/api/auth/keys'; - assert.notEqual(refreshedUserToken1, null, "UserToken 1 not defined"); - - grafanaOptions.url = grafanaUrl + apiKeysPath; - grafanaOptions.jar = cookiejar1; - request(grafanaOptions).then(res => { - if (res.statusCode < 300) { - done('Authenticated as admin: ' + res.statusCode); - } else if (res.statusCode === 403) { - done(); - } else { - done('Unexpected response from Grafana: ' + res.statusCode); - } - }).catch(err => { done(err); }); - }, - "getDataSourceId": function(done) { - // can only be invoked via admin role - var datasourcesPath = '/api/datasources'; - assert.notEqual(refreshedUserToken1, null, "UserToken 1 not defined"); - - grafanaOptions.url = config.grafana.protocol + '://' + config.grafana.admin + ':' + config.grafana.password + - '@' + config.grafana.host + ':' + config.grafana.port + config.grafana.subPath + datasourcesPath; - grafanaOptions.jar = cookiejar1; - request(grafanaOptions).then(res => { - if (res.statusCode !== 200) { - done('Can\'t get datasources in grafana: ' + res.statusCode); - } else { - var datasources = JSON.parse(res.body); - if (datasources.length < 1) { - return done('No datasource found in grafana'); - } - datasourceId = datasources[0].id; - done(); - } - }).catch(err => { done(err); }); - }, - "queryUserAccountsData": function(done) { - assert.notEqual(refreshedUserToken1, null, "UserToken 1 not defined"); - assert.notEqual(datasourceId, null, "Datasource Id not defined"); - assert.notEqual(accountId1_1, null, "AccountId 1.1 not defined"); - assert.notEqual(accountId1_2, null, "AccountId 1.2 not defined"); - assert.notEqual(componentId1_1_1, null, "ComponentId 1.1.1 not defined"); - assert.notEqual(componentId1_2, null, "ComponentId 1.2 not defined"); - - var datasourceQueryBody = { - start_absolute: startTime.getTime(), - metrics: [ - { - name: accountId1_1 + '.' + componentId1_1_1 - }, - { - name: accountId1_2 + '.' + componentId1_2, - } - ] - }; - - grafanaOptions.jar = cookiejar1; - grafanaOptions.url = grafanaUrl + apiDataSourcePath + '/' + - datasourceId + config.grafana.datasourceQuery; - grafanaOptions.headers = { 'Content-Type': 'application/json', 'charset': 'utf-8' }; - grafanaOptions.method = 'POST'; - grafanaOptions.body = JSON.stringify(datasourceQueryBody); - request(grafanaOptions).then(res => { - if (res.statusCode >= 300) { - done('Can\'t authenticate to datasource'); - } else { - var metrics = JSON.parse(res.body).queries[0].results; - var dataBelongsToUser = function(metric) { - if (metric.name === accountId1_1 + '.' + componentId1_1_1) { - return metric.values.every(timestampValuePair => { - return timestampValuePair[1] < componentData1_1_1 + 1E-10 && - timestampValuePair[1] > componentData1_1_1 - 1E-10; - }); - } else if (metric.name === accountId1_2 + '.' + componentId1_2) { - return metric.values.every(timestampValuePair => { - return timestampValuePair[1] < componentData1_2 + 1E-10 && - timestampValuePair[1] > componentData1_2 - 1E-10; - }); - } else { - return false; - } - }; - if (!metrics.every(dataBelongsToUser)) { - done('Got unauthorized metric in grafana'); - } else { - done(); - } - } - }); - }, - "tryToGetUnbelongedData": function(done) { - assert.notEqual(refreshedUserToken1, null, "UserToken 1 not defined"); - assert.notEqual(datasourceId, null, "Datasource Name not defined"); - assert.notEqual(accountId1_1, null, "AccountId 1.1 not defined"); - assert.notEqual(accountId2, null, "AccountId 2 not defined"); - assert.notEqual(componentId1_1_1, null, "ComponentId 1.1.1 not defined"); - assert.notEqual(componentId2, null, "ComponentId 2 not defined"); - - var datasourceQueryBody = { - start_absolute: startTime.getTime(), - metrics: [ - { - name: accountId1_1 + '.' + componentId1_1_1, - }, - { - name: accountId2 + '.' + componentId2, - } - ] - }; - - grafanaOptions.jar = cookiejar1; - grafanaOptions.url = grafanaUrl + apiDataSourcePath + '/' + - datasourceId + config.grafana.datasourceQuery; - grafanaOptions.headers = { 'Content-Type': 'application/json', 'charset': 'utf-8' }; - grafanaOptions.method = 'POST'; - grafanaOptions.body = JSON.stringify(datasourceQueryBody); - request(grafanaOptions).then(res => { - if (res.body !== '' && JSON.parse(res.body).queries.length > 0) { - done('Expected empty result, but got some data: ' + res.body); - } else if (res.statusCode < 400) { - done('Expected 400, got: ' + res.statusCode); - } else { - done(); - } - }); - }, - "getSuggestions": function(done) { - assert.notEqual(refreshedUserToken1, null, "UserToken 1 not defined"); - assert.notEqual(datasourceId, null, "Datasource Name not defined"); - assert.notEqual(accountId1_1, null, "AccountId 1.1 not defined"); - assert.notEqual(componentId1_1_1, null, "ComponentId 1.1.1 not defined"); - assert.notEqual(componentId1_1_2, null, "ComponentId 1.1.2 not defined"); - - grafanaOptions.jar = cookiejar1; - grafanaOptions.url = grafanaUrl + apiDataSourcePath + '/' + - datasourceId + config.grafana.datasourceSuggest + '?prefix=' + accountId1_1; - grafanaOptions.headers = { 'Content-Type': 'application/json', 'charset': 'utf-8' }; - grafanaOptions.method = 'GET'; - request(grafanaOptions).then(res => { - if (res.statusCode !== 200) { - done('Can\'t authenticate to datasource'); - } else { - var suggestions = JSON.parse(res.body).results; - suggestions.forEach(suggestion => { - if (suggestion !== accountId1_1 + '.' + componentId1_1_1 && - suggestion !== accountId1_1 + '.' + componentId1_1_2) { - return done('Got unexpected suggestion: ' + suggestion); - } - }); - done(); - } - }); - }, - "tryToGetUnbelongedSuggestions": function(done) { - assert.notEqual(refreshedUserToken2, null, "UserToken 2 not defined"); - assert.notEqual(datasourceId, null, "Datasource Name not defined"); - assert.notEqual(accountId1_1, null, "AccountId 1.1 not defined"); - assert.notEqual(componentId1_1_1, null, "ComponentId 1.1.1 not defined"); - assert.notEqual(componentId1_1_2, null, "ComponentId 1.1.2 not defined"); - - grafanaOptions.jar = cookiejar2; - grafanaOptions.url = grafanaUrl + apiDataSourcePath + '/' + - datasourceId + config.grafana.datasourceSuggest + '?prefix=' + accountId1_1; - grafanaOptions.headers = { 'Content-Type': 'application/json', 'charset': 'utf-8' }; - grafanaOptions.method = 'GET'; - request(grafanaOptions).then(res => { - if (res.statusCode !== 200) { - done('Can\'t authenticate to datasource'); - } else { - var suggestions = JSON.parse(res.body).results; - if (suggestions !== undefined && suggestions.length > 0) { - done('Got unbelonged suggestions: ' + suggestions); - } else { - done(); - } - } - }); - }, - "cleanup": function(done) { - // delete accounts - promtests.deleteAccount(refreshedUserToken1, accountId1_1) - .then(() => promtests.deleteAccount(refreshedUserToken1, accountId1_2)) - .then(() => promtests.deleteAccount(refreshedUserToken2, accountId2)) - // renew user tokens - .then(() => { - var username = process.env.USERNAME; - var password = process.env.PASSWORD; - assert.isNotEmpty(username, "no username provided"); - assert.isNotEmpty(password, "no password provided"); - - promtests.authGetToken(username, password).then(grant => { - userToken1 = grant.token; - }); - }) - .then(() => { - var username = process.env.USERNAME2; - var password = process.env.PASSWORD2; - assert.isNotEmpty(username, "no username provided"); - assert.isNotEmpty(password, "no password provided"); - - promtests.authGetToken(username, password).then(grant => { - userToken2 = grant.token; - }); - }) - .then(() => { done(); }) - .catch((err) => { done(err); }); - } - }; -}; - -var descriptions = { - "prepareGrafanaTestSetup": "Create accounts, devices, components, example data for subtest", - "checkGrafanaHeartbeat": "Shall check connection to Grafana", - "authenticateGrafanaAsViewer": "Shall connect to grafana with a viewer role", - "getDataSourceId": "Shall get id of the datasource registered at Grafana", - "queryUserAccountsData": "Shall get metric values belonging to user", - "tryToGetUnbelongedData": "Shall want unbelonged data and should get nothing", - "getSuggestions": "Shall search and find metric names belonging to user", - "tryToGetUnbelongedSuggestions": "Shall want unbelonged metric name and should get none", - "cleanup": "Cleanup accounts, devices, components, example data created for subtest" -}; - -module.exports = { - test: test, - descriptions: descriptions -}; diff --git a/tests/subtests/mqtt-data-sending-tests.js b/tests/subtests/mqtt-data-sending-tests.js deleted file mode 100644 index 29526d56..00000000 --- a/tests/subtests/mqtt-data-sending-tests.js +++ /dev/null @@ -1,479 +0,0 @@ -/** - * Copyright (c) 2018 Intel Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/*jshint esversion: 6 */ -/*jshint undef: true, unused: true */ -/* jshint node: true */ - -"use strict"; - -var test = function(userToken, accountId, deviceId, deviceToken, cbManager, mqttConnector) { - var componentNames = ["temperature-sensor-sdt", "metadata-sensor-sdt", "binarystate-senosr-sdt"]; - var componentTypes = ["temperature.v1.0", "metaData.v1.0", "binaryState.v1.0"]; - var componentBasicTypes = ["number", "string", "boolean"]; - var promtests = require('./promise-wrap'); - var componentId = []; - var newDeviceId = "d-e-v-i-c-e-mqtt"; - var newDeviceName = "devicename-mqtt"; - const MIN_NUMBER = 0.0001; - const BASE_TIMESTAMP = 1000000000000; - - var dataValues1 = [ - [{ - component: 0, - value: 10.1, - ts: 1 + BASE_TIMESTAMP - }] - ]; - - - var dataValues2 = [ - [{ - component: 1, - value: "test1", - ts: 1020 + BASE_TIMESTAMP - }, - { - component: 1, - value: "test2", - ts: 1030 + BASE_TIMESTAMP - } - ], - [{ - component: 0, - value: 13.4, - ts: 1040 + BASE_TIMESTAMP - }, - { - component: 0, - value: 20, - ts: 1050 + BASE_TIMESTAMP - }], - [{ - component: 2, - value: "1", - ts: 1060 + BASE_TIMESTAMP - }, - { - component: 2, - value: "0", - ts: 1070 + BASE_TIMESTAMP - }] - ]; - - var dataValues3 = [ - [{ - component: 0, - value: 25, - ts: 100000 + BASE_TIMESTAMP, - loc: [1.2444, 10.987, 456.789], - attributes: { - "key1": "value1" - } - }], - [{ - component: 0, - value: 26, - ts: 200000 + BASE_TIMESTAMP, - attributes: { - "key1": "value1", - "key2": "value2", - "key3": "value3" - } - }], - [{ - component: 0, - value: 27.9, - ts: 300000 + BASE_TIMESTAMP, - attributes: { - "key3": "value1", - "key4": "value2" - } - }], - [{ - component: 0, - value: 28.1, - ts: 400000 + BASE_TIMESTAMP, - loc: [0.0, 0.0, 0.0] - }], - [{ - component: 0, - value: 30.12, - ts: 500000 + BASE_TIMESTAMP, - loc: [200.345, 300.21], - attributes: { - "key5": "key1" - } - }], - [{ - component: 1, - value: "test123", - ts: 600000 + BASE_TIMESTAMP, - loc: [210.345, 260.21], - attributes: { - "key6": "value6" - } - }], - [{ - component: 2, - value: "1", - ts: 700000 + BASE_TIMESTAMP, - loc: [100.12, 300.12], - attributes: { - "key5": "value6", - "key1": "value1" - } - }] - ]; - - var flattenArray = function(array) { - var results = array.map(function(element) { - return element; - }); - results = results - .reduce(function(acc, cur) { - return acc.concat(cur); - }) - .filter((elem) => elem.component < componentId.length); - return results; - }; - - var findMapping = function(foundComponentMap, componentIds, series) { - var mapping = {}; - Object.keys(foundComponentMap).forEach(function(i) { - mapping[i] = series.findIndex( - element => componentIds[i] === element.componentId - ); - }); - return mapping; - }; - - //flatten sent array and provide numComponents - var prepareValues = function(dataValues, keys) { - //First get a flat array of aggregated points - var flattenedDataValues = flattenArray(dataValues, keys); - var numComponents = {}; - flattenedDataValues.forEach(function(element){ - numComponents[element.component] = element.component; - }); - var listOfExpectedResults = []; - //Get elements sorted by componentId - Object.values(numComponents).forEach(function(i){ - listOfExpectedResults[i] = flattenedDataValues.filter( - (element) => (element.component === i) - ); - }); - return { - flattenedDataValues: flattenedDataValues, - numComponents: numComponents, - listOfExpectedResults: listOfExpectedResults - }; - }; - - /* - var aggregation = { - MAX: 0, - MIN: 1, - COUNT: 2, - SUM: 3, - SUMOFSQUARES: 4 - }; - */ - - var createObjectFromData = function(sample, sampleHeader) { - var o = {}; - sample.forEach(function(element, index) { - if (element !== "") { - var key = sampleHeader[index]; - if (key === "Value") { - key = "value"; - } else if (key === "Timestamp") { - key = "ts"; - } - o[key] = element; - } - }); - return o; - }; - - var locEqual = function(dataValue, element, onlyExistingAttr) { - if (onlyExistingAttr) { - if (element.lat === undefined && element.long === undefined) { - return true; - } - } - if (dataValue.loc === undefined) { - if ((element.lat === undefined || element.lat === "") && (element.lat === undefined || - element.lon === "") && (element.alt === undefined || element.alt === "")) { - return true; - } else { - return false; - } - } - if ((dataValue.loc[0] === undefined || (Math.abs(dataValue.loc[0] - Number(element.lat))) <= MIN_NUMBER) && - (dataValue.loc[1] === undefined || (Math.abs(dataValue.loc[1].toString() - Number(element.lon))) <= MIN_NUMBER) && - (dataValue.loc[2] === undefined || (Math.abs(dataValue.loc[2].toString() - Number(element.alt))) <= MIN_NUMBER)) { - return true; - } else { - return false; - } - }; - - var attrEqual = function(dataValue, element, onlyExistingAttr) { - var result = true; - if (dataValue.attributes !== undefined) { - Object.keys(dataValue.attributes).forEach(function(el) { - if (!onlyExistingAttr && element[el] !== dataValue.attributes[el]) { - result = false; - } else { - if (element[el] !== undefined && element[el] !== dataValue.attributes[el]) { - result = false; - } - } - }); - } - return result; - }; - - var pointsEqual = function(element, expected){ - - if (componentBasicTypes[expected.component] === "string") { - return element.value === expected.value; - } else if (componentBasicTypes[expected.component] === "number") { - var diff = Math.abs(element.value - expected.value); - return diff < MIN_NUMBER; - } else if (componentBasicTypes[expected.component] === "bytearray") { - return (element.value.equals(expected.value)); - } else if (componentBasicTypes[expected.component] === "boolean") { - return element.value === expected.value; - } - return false; - }; - - var comparePoints = function(dataValues, points, onlyExistingAttributes) { - var result = true; - var reason = ""; - var onlyExistingAttr = onlyExistingAttributes === undefined ? false : onlyExistingAttributes; - if (points.length !== dataValues.length) { - return "Wrong number of returned points"; - } - points.forEach(function(element, index) { - if ((element.ts !== dataValues[index].ts) || - !pointsEqual(element, dataValues[index]) || - !locEqual(dataValues[index], element, onlyExistingAttr) || - !attrEqual(dataValues[index], element, onlyExistingAttr)) { - result = false; - reason = "Point " + JSON.stringify(element) + " does not fit to expected value " + - JSON.stringify(dataValues[index]); - } - }); - if (result === true) {return true;} - else {return reason;} - }; - - /* - var calcAggregationsPerComponent = function(flattenedArray) { - - return flattenedArray.reduce(function(acc, val) { - if (aggregateable[val.component] === 0) { - return acc; - } - if (val.value > acc[val.component][aggregation.MAX]) { - acc[val.component][aggregation.MAX] = val.value; - } - if (val.value < acc[val.component][aggregation.MIN]) { - acc[val.component][aggregation.MIN] = val.value; - } - acc[val.component][aggregation.COUNT]++; - acc[val.component][aggregation.SUM] += val.value; - acc[val.component][aggregation.SUMOFSQUARES] += val.value * val.value; - return acc; - }, [[Number.MIN_VALUE, Number.MAX_VALUE, 0, 0, 0], [Number.MIN_VALUE, Number.MAX_VALUE, 0, 0, 0]]); - };*/ - - //********************* Main Object *****************// - //---------------------------------------------------// - return { - "setup": function(done) { - var username = process.env.USERNAME; - var password = process.env.PASSWORD; - - promtests.authGetToken(username, password) - .then((grant) => promtests.createDevice(newDeviceName, newDeviceId, grant.token, accountId)) - .then(() => promtests.activateDevice(userToken, accountId, newDeviceId)) - .then((token) => { - deviceToken = token.deviceToken; - }) - .then(() => - promtests.addComponent(componentNames[0], componentTypes[0], - userToken, accountId, newDeviceId)) - .then((id) => { componentId[0] = id; }) - .then(() => promtests.addComponent(componentNames[1], componentTypes[1], - userToken, accountId, newDeviceId)) - .then((id) => { componentId[1] = id; }) - .then(() => promtests.addComponent(componentNames[2], componentTypes[2], - userToken, accountId, newDeviceId)) - .then((id) => { componentId[2] = id; }) - .then(() => done()) - .catch((err) => { done(err); }); - }, - - "sendSingleDataPoint": function(done) { - promtests.mqttSetCredential(mqttConnector, deviceToken, newDeviceId) - .then(() => promtests.mqttSubmitData(mqttConnector, dataValues1[0][0], deviceToken, accountId, - newDeviceId, componentId[0])) - .then(() => { done(); }) - .catch((err) => { done(err); }); - }, - - "sendMultipleDataPoints": function(done) { - var proms = []; - dataValues2.forEach(function(element) { - proms.push(promtests.mqttSubmitDataList(mqttConnector, element, deviceToken, accountId, newDeviceId, componentId, {})); - }); - Promise.all(proms) - .then(() => { - done(); - }) - .catch((err) => { - done(err); - }); - }, - "sendDataPointsWithAttributes": function(done) { - var proms = []; - dataValues3.forEach(function(element) { - proms.push(promtests.mqttSubmitDataList(mqttConnector, element, deviceToken, accountId, newDeviceId, componentId)); - }); - Promise.all(proms) - .then(() => { - done(); - }) - .catch((err) => { - done(err); - }); - }, - "receiveSingleDataPoint": function(done) { - var listOfExpectedResults = flattenArray(dataValues1); - promtests.searchData(BASE_TIMESTAMP, 1 + BASE_TIMESTAMP, userToken, accountId, newDeviceId, componentId[0], false, {}) - .then((result) => { - if (result.series.length !== 1) {return done("Wrong number of point series! (Expected:1, got:" + result.series.length + ")");} - var comparisonResult = comparePoints(listOfExpectedResults, result.series[0].points); - if (comparisonResult === true) { - done(); - } else { - done(comparisonResult); - } - }) - .catch((err) => { - done(err); - }); - }, - "receiveMultipleDataPoints": function(done) { - var pValues = prepareValues(dataValues2); - var foundComponentsMap = pValues.numComponents; - var listOfExpectedResults = pValues.listOfExpectedResults; - - promtests.searchData(BASE_TIMESTAMP + 1020, BASE_TIMESTAMP + 1080, userToken, accountId, newDeviceId, componentId, false, {}) - .then((result) => { - if (result.series.length !== componentId.length) { - return done("Wrong number of point series!"); - } - //Mapping is needed because the results are not in sending order - // e.g. component[0] could be now be in series[3] - var err = 0; - var mapping = findMapping(foundComponentsMap, componentId, result.series); - Object.entries(mapping).forEach(function(element){ - var comparisonResult = comparePoints(listOfExpectedResults[element[0]], result.series[element[1]].points); - if (comparisonResult !== true) { - err = 1 ; - done(comparisonResult); - } - }); - if (!err) { - done(); - } - }) - .catch((err) => { - done(err); - }); - }, - "receiveDataPointsWithAttributes": function(done) { - var pValues = prepareValues(dataValues3); - var foundComponentMap = pValues.numComponents; - var flattenedDataValues = pValues.flattenedDataValues; - promtests.searchDataAdvanced(100000 + BASE_TIMESTAMP, 700000 + BASE_TIMESTAMP, - userToken, accountId, newDeviceId, componentId, true, undefined, undefined, undefined) - .then((result) => { - var mapping = findMapping(foundComponentMap, componentId, result.data[0].components); - if (result.data[0].components.length !== componentId.length) { - return done("Wrong number of point series!"); - } - var err = false; - var resultObjects = Object.entries(mapping).reduce((accum, mappingElem) => { - var testresult = - result.data[0].components[mappingElem[1]].samples.reduce((accum_inner, comp) => { - accum_inner.push(createObjectFromData(comp, - result.data[0].components[mappingElem[1]].samplesHeader)); - return accum_inner; - }, []); - return accum.concat(testresult); - }, []); - var comparisonResult = comparePoints(flattenedDataValues, resultObjects); - if (comparisonResult !== true) { - err = 1; - return done(comparisonResult); - } - if (!err) { - return done(); - } - }) - .catch((err) => { - done(err); - }); - - }, - "waitForBackendSynchronization": function(delay, done) { - setTimeout(done, delay); - - }, - - "cleanup": function(done) { - promtests.deleteComponent(userToken, accountId, newDeviceId, componentId[0]) - .then(() => promtests.deleteComponent(userToken, accountId, newDeviceId, componentId[1])) - .then(() => promtests.deleteComponent(userToken, accountId, newDeviceId, componentId[2])) - .then(() => promtests.deleteDevice(userToken, accountId, newDeviceId)) - .then(() => { done(); }) - .catch((err) => { done(err); }); - } - }; -}; - -var descriptions = { - "cleanup": "Cleanup components, commands created for subtest", - "sendAggregatedDataPoints": "Shall send multiple datapoints for one component", - "sendSingleDataPoint": "Send a single data point", - "sendMultipleDataPoints": "Send several data points in one message", - "sendDataPointsWithAttributes": "Send data points with attributes and location", - "receiveSingleDataPoint": "Receive single data point", - "receiveMultipleDataPoints": "Receive multiple data points", - "receiveDataPointsWithAttributes": "Receive data pints with attributes and location", - "waitForBackendSynchronization": "Waiting maximal tolerable time backend needs to flush so that points are available", - "setup": "Setup device and components for subtest" -}; - -module.exports = { - test: test, - descriptions: descriptions -}; diff --git a/tests/subtests/mqtt-feedback-tests.js b/tests/subtests/mqtt-feedback-tests.js deleted file mode 100644 index 47734cda..00000000 --- a/tests/subtests/mqtt-feedback-tests.js +++ /dev/null @@ -1,136 +0,0 @@ -/** - * Copyright (c) 2021 Intel Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/*jshint esversion: 6 */ -/*jshint undef: true, unused: true */ -/* jshint node: true */ - -"use strict"; - -var test = function(userToken, mqttConnector) { - var chai = require('chai'); - var assert = chai.assert; - var helpers = require("./../lib/helpers"); - var promtests = require('./promise-wrap'); - var mqttConfig = require('./../test-config-mqtt.json'); - - var componentName = "temperature-sensor-rat"; - var componentType = "temperature.v1.0"; - var actuatorName = "powerswitch-actuator-rat"; - var actuatorType = "powerswitch.v1.0"; - var componentParamName = "LED"; - var switchOnCmdName = "switch-on-rat"; - var deviceId = "mqttfeedbackdevice"; - var gatewayId = "00-11-22-33-44-55"; - var cbManager = { - cb: () => {} - }; - - var deviceToken; - var accountId; - var componentId; - var actuatorId; - - var temperatureValues = [ { value: 17.3 }, { value: 1 }, { value: 17 }, { value: 30.1 }, { value: 15 } ]; - const numOfActuations = 1; - - return { - setup: function(done) { - promtests.createAccount("mqtt-feedback-account", userToken) - .then(res => accountId = res.id) - .then(() => promtests.authGetToken(process.env.USERNAME, process.env.PASSWORD)) - .then(res => userToken = res.token) - .then(() => promtests.createDevice(deviceId, deviceId, userToken, accountId)) - .then(() => promtests.activateDevice(userToken, accountId, deviceId)) - .then(res => deviceToken = res.deviceToken) - .then(() => promtests.addComponent(componentName, componentType, userToken, accountId, deviceId)) - .then(id => componentId = id) - .then(() => promtests.addActuator(actuatorName, actuatorType, userToken, accountId, deviceId)) - .then(id => actuatorId = id) - .then(() => promtests.createCommand(switchOnCmdName, componentParamName, 1, userToken, accountId, deviceId, actuatorId)) - .then(() => done()) - .catch(err => done(err)); - }, - openMqttConnection: function(done) { - var topic = mqttConfig.connector.mqtt.topic.actuation; - topic = topic.replace("{accountid}", accountId); - topic = topic.replace("{gatewayId}", gatewayId); - topic = topic.replace("{deviceid}", deviceId); - var topics = [topic]; - helpers.mqtt.openMqttConnection(deviceToken, deviceId, topics, cbManager, done); - }, - receiveControlActuation: function(done) { - const actuationValue = 0; - var actuationReceived = false; - var topicCb = function(message) { - message = JSON.parse(message); - const expectedActuationValue = false; - const componentMetric = message.metrics.filter(function(metric) { - return metric.name === componentParamName && actuatorId === metric.cid; - }); - if (componentMetric.length === 1) { - const value = componentMetric[0].value; - if (value !== expectedActuationValue) { - done(new Error('Param value wrong. Expected: ' + expectedActuationValue + ' Received: ' + paramValue)); - } else { - actuationReceived++; - } - } else { - done(new Error('Did not find component param: ' + componentParamName)); - } - }; - cbManager.cb = topicCb; - var maxRetry = 10; - var retry = 0; - const checkActuation = function() { - if (retry >= maxRetry) { - done(new Error('Actuation timed out after sending actuation command')); - return; - } - if (actuationReceived === numOfActuations) { - done(); - } else { - retry++; - setTimeout(checkActuation, 2000); - } - }; - helpers.control.sendActuationCommand(componentParamName, actuationValue, userToken, accountId, actuatorId, deviceId, function(err, response) { - if (err) { - done(new Error('Cannot send an actuation: ' + err)); - } else { - assert.equal(response.status, 'OK', 'cannot send an actuation'); - setTimeout(checkActuation, 2000); - } - }); - }, - cleanup: function(done) { - promtests.deleteAccount(userToken, accountId) - .then(() => done()) - .catch(err => done(err)); - } - }; -}; - -var descriptions = { - "setup": "Create accounts, devices, components needed for this test", - "openMqttConnection": "Open MQTT connection and wait until it syncs", - "receiveControlActuation": "Shall receive actuation through control api", - "cleanup": "Cleanup accounts, devices, components created during this test" -}; - -module.exports = { - test: test, - descriptions: descriptions -}; diff --git a/tests/subtests/promise-wrap.js b/tests/subtests/promise-wrap.js deleted file mode 100644 index da0cec83..00000000 --- a/tests/subtests/promise-wrap.js +++ /dev/null @@ -1,544 +0,0 @@ -/** - * Copyright (c) 2017 Intel Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/*jshint esversion: 6 */ -/*jshint undef: true, unused: true */ -/* jshint node: true */ - -"use strict"; - - -var helpers = require("../lib/helpers"); -var colors = require('colors'); // jshint ignore:line - - -var checkObservations = function(tempValues, cid, cbManager, deviceToken, accountId, - deviceId, componentParamName, waitBetweenSendingSamples = 0, timeout = 60 * 3000) { - var firstObservationTime; - return new Promise((resolve, reject) => { - var index = 0; - var nbActuations = 0; - process.stdout.write(" "); - - tempValues.forEach((value) => { - value.ts = null; - if (value.expectedActuation !== null) { - nbActuations++; - } - }); - var step; - var actuationCounter = 0; - var sendObservationAndCheckRules = function(index) { - function sendActualObservation() { - var currentActuationCounter = actuationCounter; - helpers.devices.submitData(tempValues[index].value, deviceToken, accountId, deviceId, cid, function(err, ts) { - tempValues[index].ts = ts; - if (index === 0) { - firstObservationTime = tempValues[index].ts; - } - if (err) { - reject(err); - } - if (tempValues[index].expectedActuation === null) { - setTimeout(step, waitBetweenSendingSamples); - } else { - var checkActuation = function(currentCounter) { - if (currentCounter >= actuationCounter) { - reject(new Error("Actuation timeout by component id: " + cid + - ", data index: " + index + ", expected actuation value: " + - tempValues[index].expectedActuation.toString())); - } - }; - setTimeout(checkActuation, timeout, currentActuationCounter); - } - }); - } - process.stdout.write(".".green); - if (tempValues[index].hasOwnProperty('delay')){ - setTimeout(sendActualObservation, tempValues[index].delay); - } else { - sendActualObservation(); - } - }; - - step = function() { - index++; - if (index === tempValues.length) { - process.stdout.write("\n"); - if (nbActuations === 0) { - resolve(); - } else { - reject(new Error("Wrong number of actuations")); - } - } else { - sendObservationAndCheckRules(index); - } - }; - - var actuationCallback = function(message) { - message = JSON.parse(message); - --nbActuations; - var expectedActuationValue = tempValues[index].expectedActuation; - var componentParam = message.metrics.filter(function(metric){ - return metric.name === componentParamName; - }); - - if (componentParam.length === 1) { - var param = componentParam[0]; - var paramValue = param.value; - if (paramValue === expectedActuationValue) { - step(); - } else { - reject(new Error("Param value wrong. Expected: " + expectedActuationValue + " Received: " + paramValue)); - } - } else { - reject(new Error("Did not find component param: " + componentParamName)); - } - }; - cbManager.set(actuationCallback); - sendObservationAndCheckRules(index); - }); -}; - -var addComponent = (componentName, componentType, deviceToken, accountId, deviceId) => { - return new Promise(function(resolve, reject){ - helpers.devices.addDeviceComponent(componentName, componentType, deviceToken, accountId, deviceId, function(err, id) { - if (err) { - reject(err); - } else { - resolve(id); - } - }); - }); -}; -var addActuator = (actuatorName, actuatorType, deviceToken, accountId, deviceId) => { - return new Promise(function(resolve, reject){ - helpers.devices.addDeviceComponent(actuatorName, actuatorType, deviceToken, accountId, deviceId, function(err, id) { - if (err) { - reject(err); - } else { - resolve(id); - } - }); - }); -}; -var createCommand = (cmdName, componentParamName, onOff, userToken, accountId, deviceId, actuatorId) => { - return new Promise(function(resolve, reject){ - helpers.control.saveComplexCommand(cmdName, componentParamName, onOff, userToken, accountId, deviceId, actuatorId, function(err,response) { - if (err) { - reject(err); - } else { - if (response.status !== 'OK') { - reject(new Error("Wrong status: " + response.status)); - } - else { - resolve(); - } - } - }); - }); -}; - -var createSimpleRule = (rule, userToken, accountId, deviceId, resetType="Automatic") => { - return new Promise(function(resolve, reject){ - helpers.rules.createRule(rule, userToken, accountId, deviceId, resetType, function(err, id) { - if (err) { - reject(err); - } else { - rule.id = id; - resolve(id); - } - }); - }); -}; - -var createStatisticRule = (rule, userToken, accountId, deviceId) => { - return new Promise(function(resolve, reject){ - helpers.rules.createStatisticRule(rule, userToken, accountId, deviceId, function(err, id) { - if (err) { - reject(err); - } else { - rule.id = id; - resolve(); - } - }); - }); -}; - -var createTbRule = (rule, userToken, accountId, deviceId) => { - return new Promise(function(resolve, reject){ - helpers.rules.createTbRule(rule, userToken, accountId, deviceId, function(err, id) { - if (err) { - reject(err); - } else { - rule.id = id; - resolve(); - } - }); - }); -}; - -var deleteComponent = function(userToken, accountId, deviceId, componentId){ - return new Promise((resolve, reject) => { - helpers.devices.deleteDeviceComponent (userToken, accountId, deviceId, componentId, function(err, response){ - if (err) { - reject(err); - } else { - resolve(response); - } - }); - }); -}; -var deleteRule = function(userToken, accountId, ruleId){ - return new Promise((resolve, reject) => { - helpers.rules.deleteRule (userToken, accountId, ruleId, function(err, response){ - if (err) { - reject(err); - } else { - resolve(response); - } - }); - }); -}; - -var submitDataList = function(valueList, deviceToken, accountId, deviceId, cidList){ - return new Promise((resolve, reject) => { - helpers.data.submitDataList(valueList, deviceToken, accountId, deviceId, cidList, function(err, response){ - if (err) { - reject(err); - } else { - resolve(response); - } - }); - }); -}; - -var submitDataListAsUser = function(valueList, userToken, accountId, deviceId, cidList) { - return new Promise((resolve, reject) => { - helpers.data.submitDataListAsUser(valueList, userToken, accountId, deviceId, cidList, function(err, response) { - if (err) { - reject(err); - } else { - resolve(response); - } - }); - }); -}; - - -var submitData = function(value, deviceToken, accountId, deviceId, cid){ - return new Promise((resolve, reject) => { - helpers.data.submitData(value, deviceToken, accountId, deviceId, cid, function(err, response){ - if (err) { - reject(err); - } else { - resolve(response); - } - }); - }); -}; - - -var searchData = function(from, to, userToken, accountId, deviceId, cid, queryMeasureLocation, targetFilter){ - return new Promise((resolve, reject) => { - helpers.data.searchData(from, to, userToken, accountId, deviceId, cid, queryMeasureLocation, targetFilter, function(err, response){ - if (err) { - reject(err); - } else { - resolve(response); - } - }); - }); -}; - -var searchDataMaxItems = function(from, to, userToken, accountId, deviceId, cids, queryMeasureLocation, targetFilter, maxItems, order, aggregators){ - return new Promise((resolve, reject) => { - helpers.data.searchDataMaxItems(from, to, userToken, accountId, deviceId, cids, - queryMeasureLocation, targetFilter, maxItems, order, aggregators, function(err, response){ - if (err) { - reject(err); - } else { - resolve(response); - } - }); - }); -}; - - -var searchDataAdvanced = function(from, to, userToken, accountId, deviceIds, cidList, showMeasureLocation, returnedMeasureAttributes, aggregations, countOnly){ - return new Promise((resolve, reject) => { - if (!Array.isArray(deviceIds)){ - deviceIds = [deviceIds]; - } - helpers.data.searchDataAdvanced(from, to, userToken, accountId, deviceIds, cidList, - showMeasureLocation, returnedMeasureAttributes, aggregations, countOnly, function(err, response){ - if (err) { - reject(err); - } else { - resolve(response); - } - }); - }); -}; - -var authGetToken = (username, password) => { - return new Promise(function(resolve, reject){ - helpers.auth.login(username, password, function(err, tokens) { - if (err) { - reject(err); - } else { - resolve(tokens); - } - }); - }); -}; - -var refreshAuthToken = (oldToken, refreshToken) => { - return new Promise(function(resolve, reject) { - helpers.auth.refreshAuthToken(oldToken, refreshToken, function(err, response) { - if (err) { - reject(err); - } else { - resolve(response); - } - }); - }); -}; - -var invitationCreate = (userToken, accountId, receiverEmail) => { - return new Promise(function(resolve, reject){ - helpers.invitation.createInvitation(userToken, accountId, receiverEmail, function(err, response) { - if (err) { - reject(err); - } else { - resolve(response); - } - }); - }); -}; - -var invitationAccept = (userToken, accountId, inviteId) => { - return new Promise(function(resolve, reject){ - helpers.invitation.acceptInvitation(userToken, accountId, inviteId, function(err, response) { - if (err) { - reject(err); - } else { - resolve(response); - } - }); - }); -}; - -var authTokenInfo = (userToken) => { - return new Promise(function(resolve, reject){ - helpers.auth.tokenInfo(userToken, function(err, response) { - if (err) { - reject(err); - } else { - resolve(response); - } - }); - }); -}; - -var accountCreate = (name, userToken) => { - return new Promise(function(resolve, reject){ - helpers.accounts.createAccount(name, userToken, function(err, response) { - if (err) { - reject(err); - } else { - resolve(response); - } - }); - }); -}; - -var accountDelete = (userToken, accountId) => { - return new Promise(function(resolve, reject){ - helpers.accounts.deleteAccount(userToken, accountId, function(err, response) { - if (err) { - reject(err); - } else { - resolve(response); - } - }); - }); -}; - -var inviteDelete = (userToken, accountId, email) => { - return new Promise(function(resolve, reject){ - helpers.invitation.deleteInvitations(userToken, accountId,email, function(err, response) { - if (err) { - reject(err); - } else { - resolve(response); - } - }); - }); -}; - -var createDevice = (name, deviceId, userToken, accountId) => { - return new Promise(function(resolve, reject){ - helpers.devices.createDevice(name, deviceId, userToken, accountId, function(err, response) { - if (err) { - reject(err); - } else { - resolve(response); - } - }); - }); -}; - -var deleteDevice = (userToken, accountId, deviceId) => { - return new Promise(function(resolve, reject){ - helpers.devices.deleteDevice(userToken, accountId, deviceId, function(err, response) { - if (err) { - reject(err); - } else { - resolve(response); - } - }); - }); -}; - -var activateDevice = (userToken, accountId, deviceId) => { - return new Promise(function(resolve, reject){ - helpers.devices.activateDevice(userToken, accountId, deviceId, function(err, response) { - if (err) { - reject(err); - } else { - resolve(response); - } - }); - }); -}; - -var activateDeviceWithoutToken = (activationCode, deviceId) => { - return new Promise(function(resolve, reject){ - helpers.devices.activateDeviceWithoutToken(activationCode, deviceId, function(err, response) { - if (err) { - reject(err); - } else { - resolve(response); - } - }); - }); -}; - -var getAccountActivationCode = (accountId, userToken) => { - return new Promise(function(resolve, reject){ - helpers.accounts.getAccountActivationCode(accountId, userToken, function(err, response) { - if (err) { - reject(err); - } else { - resolve(response); - } - }); - }); -}; -var mqttSetCredential = (connector, userToken, deviceId) => { - return new Promise(function(resolve, reject) { - helpers.mqtt.setCredential(connector, userToken, deviceId, function(err, response) { - if (err) { - reject(err); - } else { - resolve(response); - } - }); - }); -}; - -var mqttSubmitData = (connector, value, deviceToken, accountId, deviceId, cid) => { - return new Promise(function(resolve, reject) { - helpers.mqtt.submitData(connector, value, deviceToken, accountId, deviceId, cid, function(err) { - if (err && err.status === 0) { - resolve("OK"); - } else { - reject("wrong status"); - } - }); - }); -}; -var mqttSubmitDataList = (connector, valueList, deviceToken, accountId, deviceId, cid) => { - return new Promise(function(resolve, reject) { - helpers.mqtt.submitDataList(connector, valueList, deviceToken, accountId, deviceId, cid, function(err) { - if (err && err.status === 0) { - resolve("OK"); - } else { - reject("wrong status"); - } - }); - }); -}; - -var getAlerts = (userToken, accountId) => { - return new Promise(function(resolve, reject){ - helpers.alerts.getListOfAlerts(userToken, accountId, function(err, response) { - if (err) { - reject(new Error("Cannot get list of alerts: " + err)); - } else { - resolve(response); - } - }); - }); -}; - -var updateAlert = (userToken, accountId, alertId, status) => { - return new Promise(function(resolve, reject) { - helpers.alerts.updateAlertStatus(userToken, accountId, alertId, status, function(err) { - if (err) { - reject(new Error("Cannot update alert status " + err)); - } else { - resolve(); - } - }); - }); -}; - -module.exports = { - getAccountActivationCode: getAccountActivationCode, - checkObservations: checkObservations, - addComponent: addComponent, - addActuator: addActuator, - createCommand: createCommand, - createStatisticRule: createStatisticRule, - createSimpleRule: createSimpleRule, - createTbRule: createTbRule, - deleteComponent: deleteComponent, - deleteRule: deleteRule, - submitDataList: submitDataList, - submitDataListAsUser: submitDataListAsUser, - submitData: submitData, - searchData: searchData, - searchDataMaxItems: searchDataMaxItems, - searchDataAdvanced: searchDataAdvanced, - authGetToken: authGetToken, - refreshAuthToken: refreshAuthToken, - createInvitation: invitationCreate, - acceptInvitation: invitationAccept, - authTokenInfo: authTokenInfo, - createAccount: accountCreate, - deleteAccount: accountDelete, - deleteInvite: inviteDelete, - createDevice: createDevice, - deleteDevice: deleteDevice, - activateDevice: activateDevice, - activateDeviceWithoutToken: activateDeviceWithoutToken, - mqttSetCredential: mqttSetCredential, - mqttSubmitData: mqttSubmitData, - mqttSubmitDataList: mqttSubmitDataList, - getAlerts: getAlerts, - updateAlert: updateAlert -}; diff --git a/tests/subtests/refresh-token-tests.js b/tests/subtests/refresh-token-tests.js deleted file mode 100644 index 4a165003..00000000 --- a/tests/subtests/refresh-token-tests.js +++ /dev/null @@ -1,82 +0,0 @@ -/** - * Copyright (c) 2019 Intel Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/*jshint esversion: 6 */ -/*jshint undef: true, unused: true */ -/* jshint node: true */ - -"use strict"; - -var test = function(username, password, userToken, accountId, deviceId) { - - var chai = require('chai'); - var assert = chai.assert; - var promtests = require('./promise-wrap'); - - var oldUserToken; - var oldDeviceToken; - var userRefreshToken; - var newUserToken; - var deviceRefreshToken; - var newDeviceToken; - - return { - "getRefreshTokensForDeviceAndUser": function(done) { - promtests.authGetToken(username, password) - .then(response => { - userRefreshToken = response.refreshToken; - oldUserToken = response.token; - assert.notEqual(userRefreshToken, null, "Cannot get user refresh token."); - }).then(() => promtests.activateDevice(oldUserToken, accountId, deviceId)) - .then(response => { - deviceRefreshToken = response.refreshToken; - oldDeviceToken = response.deviceToken; - assert.notEqual(deviceRefreshToken, null, "Cannot get device refresh token."); - }).then(() => { done(); }) - .catch((err) => { done(err); }); - }, - "refreshTokensForDeviceAndUser": function(done) { - promtests.refreshAuthToken(oldUserToken, userRefreshToken) - .then(response => { - newUserToken = response.jwt; - return promtests.authTokenInfo(newUserToken); - }).then(response => { - if (!response) { - done('Could not get refreshed user token info: ' + response); - } - return promtests.refreshAuthToken(oldDeviceToken, deviceRefreshToken); - }).then(response => { - newDeviceToken = response.jwt; - return promtests.authTokenInfo(newDeviceToken); - }).then((response) => { - if (response) { - done(); - } else { - done('Could not get refreshed device token info: ' + response); - } - }); - } - }; -}; - -var descriptions = { - "getRefreshTokensForDeviceAndUser": "Create a refresh token for given device and user", - "refreshTokensForDeviceAndUser": "Use refresh token to get new JWT tokens for device and user" -}; - -module.exports = { - test: test, - descriptions: descriptions -}; diff --git a/tests/subtests/scale-devices-tests.js b/tests/subtests/scale-devices-tests.js deleted file mode 100644 index 1d0f8e6e..00000000 --- a/tests/subtests/scale-devices-tests.js +++ /dev/null @@ -1,219 +0,0 @@ -/** - * Copyright (c) 2020 Intel Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/*jshint esversion: 6 */ -/*jshint undef: true, unused: true */ -/* jshint node: true */ - -"use strict"; - -var test = function(userToken, accountId) { - var chai = require('chai'); - var assert = chai.assert; - var componentNames = ["temperature-sensor-st", "humidity-sensor-st", "metadata-sensor-st", "binarystate-senosr-st", "binarydata-sensor-st"]; - var componentTypes = ["temperature.v1.0", "humidity.v1.0", "metaData.v1.0", "binaryState.v1.0", "images.v1.0"]; - var componentMapping = {}; - var promtests = require('./promise-wrap'); - var componentIds = []; - var newDeviceId = "scaleDevice"; - var newDeviceNumber = 100; - var scaleSamplesNumber = 11000; - const BASE_TIMESTAMP = 1000000000000; - - - function random(max) { - return Math.floor(Math.random() * max); - } - - var dataValues = [ - { - component: 0, - value: 10, - ts: BASE_TIMESTAMP - }, - { - component: 1, - value: 12, - ts: BASE_TIMESTAMP - }, - { - component: 2, - value: "Hello World", - ts: BASE_TIMESTAMP - }, - { - component: 3, - value: 1, - ts: BASE_TIMESTAMP - }, - { - component: 4, - value: Buffer.from("Hello World!"), - ts: BASE_TIMESTAMP - } - ]; - //********************* Main Object *****************// - //---------------------------------------------------// - return { - "setup": function(done) { - var promises = Array.apply(0, Array(newDeviceNumber)).map((item, index) => { - return promtests.createDevice(newDeviceId + index, newDeviceId + index, userToken, accountId) - .then(() => promtests.activateDevice(userToken, accountId, newDeviceId + index)) - .then(() => promtests.addComponent(componentNames[index % 5], componentTypes[index % 5], userToken, accountId, newDeviceId + index)) - .then(id => {componentIds[index] = []; componentIds[index][0] = id; return;}) - .then(() => { - var randComp = random(5); - if (randComp === index % 5) { - randComp += 1; - randComp = randComp % 5; - } - componentMapping[newDeviceId + index] = randComp; //save the random component for later to determine data type - return promtests.addComponent(componentNames[randComp], componentTypes[randComp], userToken, accountId, newDeviceId + index); - }) - .then(id => {componentIds[index][1] = id; return;}) - .catch((err) => { - done(err); - }); - }); - - Promise.all(promises) - .then(() => done()) - .catch((err) => { - done(err); - }); - }, - "sendDataToSingleDevice": function(done) { - var did = newDeviceId + "0"; - var index = 0; - /* jshint -W119 */ - var promchain = Array.apply(0, Array(scaleSamplesNumber)).reduce(async (acc) => { - /* jshint +W119 */ - await acc; - var valueList = []; - valueList[0] = dataValues[0]; - valueList[0].component = 0; - valueList[0].ts = BASE_TIMESTAMP + (newDeviceNumber + 1) * 100 + index * 100; - var cidList = componentIds[0]; - index++; - return promtests.submitDataListAsUser(valueList, userToken, accountId, did, cidList); - }, Promise.resolve()); - promchain.then(() => done()) - .catch((err) => { - done(err); - }); - }, - "sendDataToAllDevices": function(done) { - var promises = Array.apply(0, Array(newDeviceNumber)).map((item, index) => { - var valueList = []; - valueList[0] = dataValues[index % 5]; - valueList[1] = dataValues[componentMapping[newDeviceId + index]]; - valueList[0].ts = BASE_TIMESTAMP + index * 100; - valueList[0].component = 0; - valueList[1].ts = BASE_TIMESTAMP + index * 100; - valueList[1].component = 1; - var cidList = componentIds[index]; - return promtests.submitDataListAsUser(valueList, userToken, accountId, newDeviceId + index, cidList); - }); - Promise.all(promises) - .then(() => done()) - .catch((err) => { - done(err); - }); - }, - "countAllData": function(done) { - var deviceIds = Array.apply(0, Array(newDeviceNumber)) - .map((item, index) => newDeviceId + index); - var cids = componentIds.reduce((acc, cur)=> acc.concat(cur)); - promtests.searchDataAdvanced(BASE_TIMESTAMP, BASE_TIMESTAMP + newDeviceNumber * 100, - userToken, accountId, deviceIds, cids, false, undefined, undefined, true) - .then((result) => { - if (result.data.length !== newDeviceNumber) { - return done("Wrong number of point series!"); - } - assert.equal(result.rowCount, newDeviceNumber * 2); - done(); - }) - .catch((err) => { - done(err); - }); - }, - "countPartialData": function(done) { - var deviceIds = Array.apply(0, Array(newDeviceNumber)) - .map((item, index) => newDeviceId + index); - var cids = componentIds.reduce((acc, cur)=> acc.concat(cur)); - var partialDeviceNumber = newDeviceNumber / 2; - promtests.searchDataAdvanced(BASE_TIMESTAMP, BASE_TIMESTAMP + (partialDeviceNumber - 1) * 100, - userToken, accountId, deviceIds, cids, false, undefined, undefined, true) - .then((result) => { - if (result.data.length !== newDeviceNumber) { - return done("Wrong number of point series! Got " + result.data.length + " expected " + newDeviceNumber); - } - assert.equal(result.rowCount, newDeviceNumber); - done(); - }) - .catch((err) => { - done(err); - }); - }, - "countSingleDeviceData": function(done) { - var deviceIds = newDeviceId + "0"; - promtests.searchDataAdvanced(BASE_TIMESTAMP + newDeviceNumber * 100, -1, userToken, - accountId, deviceIds, componentIds[0], false, undefined, undefined, true) - .then((result) => { - if (result.data.length !== 1) { - return done("Wrong number of point series! Got " + result.data.length + " expected " + "1"); - } - assert.equal(result.rowCount, scaleSamplesNumber); - done(); - }) - .catch((err) => { - done(err); - }); - }, - "waitForBackendSynchronization": function(delay, done) { - setTimeout(done, delay); - }, - "cleanup": function(done) { - var promises = Array.apply(0, Array(newDeviceNumber)).map((item, index) => { - return promtests.deleteDevice(userToken, accountId, newDeviceId + index) - .catch((err) => { - done(err); - }); - }); - - Promise.all(promises) - .then(() => done()) - .catch((err) => { - done(err); - }); - } - }; -}; - -var descriptions = { - "setup": "Shall setup needed devices and components", - "sendDataToAllDevices": "Send Data to all devices", - "sendDataToSingleDevice": "Send large amount of data to single device", - "countAllData": "Count data of all devices and components", - "countPartialData": "Count data of partial devices and components", - "countSingleDeviceData": "Count large amount of data sent to single device", - "waitForBackendSynchronization": "Waiting maximal tolerable time backend needs to flush so that points are available", - "cleanup": "Cleanup components, commands created for subtest" -}; - -module.exports = { - test: test, - descriptions: descriptions -}; diff --git a/tests/subtests/tsdb-proxy-tests.js b/tests/subtests/tsdb-proxy-tests.js deleted file mode 100644 index 0bab8bb8..00000000 --- a/tests/subtests/tsdb-proxy-tests.js +++ /dev/null @@ -1,154 +0,0 @@ -/** - * Copyright (c) 2020 Intel Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -"use strict"; - -var test = function(userToken) { - var chai = require('chai'); - var request = require('request-promise'); - var assert = chai.assert; - var config = require('../test-config.json'); - var componentName = "temperature-sensor-srt"; - var componentType = "temperature.v1.0"; - var promtests = require('./promise-wrap'); - var deviceId = "11-11-22-33-44-55"; - - var accountId, deviceToken, componentId; - - var componentData = [15, 20]; - var startTime = new Date(); - var tsdbUrl = config.tsdbproxy.protocol + '://' + config.tsdbproxy.host + - ':' + config.tsdbproxy.port; - var suggestUrl = tsdbUrl + '/' + config.tsdbproxy.suggest; - var queryUrl = tsdbUrl + '/' + config.tsdbproxy.query; - var tsdbOptions = { - strictSSL: config.grafana.strictSSL, - timeout: config.tsdbproxy.timeout, - resolveWithFullResponse: true, - json:true, - simple: true - }; - - return { - "prepareTestSetup": done => { - promtests.createAccount("tsdbproxyacc", userToken).then(response => { - accountId = response.id; - return promtests.authGetToken(process.env.USERNAME, process.env.PASSWORD); - }).then(grant => { - userToken = grant.token; - return promtests.createDevice("device", deviceId, userToken, accountId); - }).then(() => { - return promtests.activateDevice(userToken, accountId, deviceId); - }).then(response => { - deviceToken = response.deviceToken; - return promtests.addComponent(componentName, componentType, userToken, accountId, deviceId); - }).then(response => { - componentId = response; - return promtests.submitData(componentData[0], deviceToken, accountId, deviceId, componentId); - }).then(() => { - return promtests.submitData(componentData[1], deviceToken, accountId, deviceId, componentId); - }).then(() => { - setTimeout(done, 1000); - }).catch(err => { - done(err); - }); - }, - "testQuery": done => { - assert.notEqual(userToken, null, "userToken is undefined"); - assert.notEqual(accountId, null, "accountId is undefined"); - assert.notEqual(componentId, null, "componentId is undefined"); - - var tsdbQueryBody = { - start_absolute: startTime.getTime(), - metrics: [ - { - name: accountId + '.' + componentId - } - ] - }; - - tsdbOptions.url = queryUrl; - tsdbOptions.headers = { 'Authorization': 'Bearer ' + userToken, - 'charset': 'utf-8', 'Content-type': 'application/json' }; - tsdbOptions.method = 'post'; - tsdbOptions.body = tsdbQueryBody; - - request(tsdbOptions).then(response => { - var metrics = response.body.queries[0].results; - var dataBelongsToUser = function(metric) { - if (metric.name === accountId + '.' + componentId) { - return metric.values.every(timestampValuePair => { - return componentData.some(data => { - return timestampValuePair[1] < data + 1E-10 && - timestampValuePair[1] > data - 1E-10; - }); - }); - } else { - return false; - } - }; - if (!metrics.every(dataBelongsToUser)) { - done('Got unexpected data from proxy: ' + metrics); - } else { - done(); - } - }).catch(err => { - done(err); - }); - }, - "testSuggestion": done => { - assert.notEqual(userToken, null, "userToken is undefined"); - assert.notEqual(accountId, null, "accountId is undefined"); - assert.notEqual(componentId, null, "componentId is undefined"); - - tsdbOptions.url = suggestUrl + "?prefix=" + accountId; - tsdbOptions.headers = { 'Authorization': 'Bearer ' + userToken, 'charset': 'utf-8' }; - tsdbOptions.method = 'get'; - delete tsdbOptions.body; - - request(tsdbOptions).then(response => { - var suggestions = response.body.results; - suggestions.forEach(suggestion => { - if (suggestion !== accountId + '.' + componentId) { - done("Got unexpected suggestion: ", suggestion); - } - }); - done(); - }).catch(err => { - done(err); - }); - }, - "cleanup": function(done) { - promtests.deleteAccount(userToken, accountId).then(() => { - done(); - }).catch(err => { - done(err); - }); - } - }; -}; - -var descriptions = { - "prepareTestSetup": "Create account, device and component for the subtest", - "testQuery": "Shall search and find metric values belonging to user", - "testSuggestion": "Shall search and find metric name belonging to user", - "cleanup": "Cleanup account, device and component created for this subtest" -}; - -module.exports = { - test: test, - descriptions: descriptions -}; diff --git a/tests/test-backup-after.js b/tests/test-backup-after.js deleted file mode 100644 index f4bfc9bd..00000000 --- a/tests/test-backup-after.js +++ /dev/null @@ -1,219 +0,0 @@ -/** - * Copyright (c) 2020 Intel Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -"use strict"; - -var chai = require('chai'); -var assert = chai.assert; -var colors = require('colors'); // jshint ignore:line - -var config = require("./test-config.json"); -var kafka = require('kafka-node'); -var helpers = require("./lib/helpers"); -var promtests = require('./subtests/promise-wrap'); - -var userToken; -var deviceToken; -var accountId = process.env.ACCOUNTID; -var deviceId; -var deviceName = "backup-tests-device"; -var activationCode = process.env.ACTIVATIONCODE; -var userId; -var username = process.env.USERNAME; -var password = process.env.PASSWORD; - -var componentId; -var componentType = "temperature.v1.0"; -var componentName = "temp;"; - -var getNewUserTokens = function(done) { - - return promtests.authGetToken(username, password).then(grant => { - userToken = grant.token; - done(); - }).catch(err => { - done(err); - }); -}; -//------------------------------------------------------------------------------------------------------- -// Tests -//------------------------------------------------------------------------------------------------------- -process.stdout.write("_____________________________________________________________________\n".bold); -process.stdout.write(" \n"); -process.stdout.write(" OISP Backup Test after \n".green.bold); -process.stdout.write("_____________________________________________________________________\n".bold); - - - -describe("Waiting for OISP services to be ready ...\n".bold, function() { - - before(function(done) { - userToken = null; - deviceId = "00-12-23-34-45-56"; - done(); - }); - - it('Shall wait for oisp services to start', function(done) { - var kafkaConsumer; - var topic = config["connector"]["kafka"]["topic"]; - var partition = 0; - var kafkaAddress = config["connector"]["kafka"]["host"] + ":" + config["connector"]["kafka"]["port"]; - var kafkaClient = new kafka.KafkaClient({ kafkaHost: kafkaAddress }); - var kafkaOffset = new kafka.Offset(kafkaClient); - - var getKafkaOffset = function(topic_, partition_, cb) { - kafkaOffset.fetchLatestOffsets([topic_], function(error, offsets) { - if (!error) { - cb(offsets[topic_][partition_]); - } - else { - setTimeout(function() { - getKafkaOffset(topic_, partition_, cb); - }, 1000); - } - }); - }; - - getKafkaOffset(topic, partition, function(offset) { - if (offset >= 0) { - var topics = [{ topic: topic, offset: offset + 1, partition: partition }]; - var options = { autoCommit: true, fromOffset: true }; - - kafkaConsumer = new kafka.Consumer(kafkaClient, topics, options); - - var oispServicesToMonitor = ['rules-engine']; - process.stdout.write(" "); - kafkaConsumer.on('message', function(message) { - process.stdout.write(".".green); - if (kafkaConsumer) { - var i = 0; - for (i = 0; i < oispServicesToMonitor.length; i++) { - if (oispServicesToMonitor[i] != null && oispServicesToMonitor[i].trim() === message.value.trim()) { - oispServicesToMonitor[i] = null; - } - } - for (i = 0; i < oispServicesToMonitor.length; i++) { - if (oispServicesToMonitor[i] != null) { - break; - } - } - if (i === oispServicesToMonitor.length) { - kafkaConsumer.close(true); - kafkaConsumer = null; - process.stdout.write("\n"); - done(); - } - } - }); - } - else { - done(new Error("Cannot get Kafka offset ")); - } - }); - - }).timeout(1000 * 60 * 1000); -}); - -describe("get authorization and manage user ...\n".bold, function() { - - it('Shall authenticate', function(done) { - getNewUserTokens(done); - }).timeout(10000); - - it('Shall get token info', function (done) { - helpers.auth.tokenInfo(userToken, function (err, response) { - if (err) { - done(new Error("Cannot get token info: " + err)); - } else { - assert.equal(response.header.typ, 'JWT', 'response type error' ); - if (response.payload.sub == null){ - done(new Error("get null user id")); - } - else { - userId = response.payload.sub; - } - - done(); - } - }); - }); - - it('Shall get user information', function(done) { - helpers.users.getUserInfo(userToken, userId, function(err, response) { - if (err) { - done(new Error("Cannot get user information : " + err)); - } else { - assert.isString(response.id); - done(); - } - }); - }); - -}); - -describe("Check account and device ...\n".bold, function() { - it('Shall retrieve account info', function(done) { - helpers.accounts.getAccountInfo(accountId, userToken, function(err, response) { - if (err) { - done(new Error("Cannot get user info: " + err)); - } else { - assert.equal(accountId, response.id); - done(); - } - }); - }).timeout(10000); - - - it('Shall get devices', function(done) { - - helpers.devices.getDevices(userToken, accountId, function(err, response) { - if (err) { - done(new Error("Cannot create device: " + err)); - } else { - assert.equal(response.length, 1); - assert.equal(response[0].deviceId, deviceId, 'incorrect device id'); - assert.equal(response[0].name, deviceName, 'incorrect device name'); - assert.equal(response[0].components[0].name, componentName); - assert.equal(response[0].components[0].type, componentType); - componentId = response[0].components[0].cid; - done(); - } - }); - }); - - it('Shall activate device without token', function(done) { - assert.notEqual(deviceId, null, "Invalid device id"); - - helpers.devices.activateDeviceWithoutToken(activationCode, deviceId, function(err, response) { - if (err) { - done(new Error("Cannot activate device: " + err)); - } else { - deviceToken = response.deviceToken; - done(); - } - }); - }).timeout(5000); - - it('Shall send data point', function(done) { - - helpers.devices.submitData("23", deviceToken, accountId, deviceId, componentId, function(err) { - if (err) { - done(new Error("Cannot create device: " + err)); - } else { - done(); - } - }); - }).timeout(10000); -}); diff --git a/tests/test-backup-before.js b/tests/test-backup-before.js deleted file mode 100644 index 0671c5aa..00000000 --- a/tests/test-backup-before.js +++ /dev/null @@ -1,275 +0,0 @@ -/** - * Copyright (c) 2020 Intel Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -"use strict"; - -var chai = require('chai'); -var assert = chai.assert; -var colors = require('colors'); // jshint ignore:line - -var config = require("./test-config.json"); -var kafka = require('kafka-node'); -var helpers = require("./lib/helpers"); -var promtests = require('./subtests/promise-wrap'); - -var userToken; -var deviceToken; -var accountId = process.env.ACCOUNTID; -var deviceId; -var deviceName = "backup-tests-device"; -var activationCode = process.env.ACTIVATIONCODE; -var userId; -var username = process.env.USERNAME; -var password = process.env.PASSWORD; - -var componentId; -var componentType = "temperature.v1.0"; -var componentName = "temp;"; - -var getNewUserTokens = function(done) { - - return promtests.authGetToken(username, password).then(grant => { - userToken = grant.token; - done(); - }).catch(err => { - done(err); - }); -}; -//------------------------------------------------------------------------------------------------------- -// Tests -//------------------------------------------------------------------------------------------------------- -process.stdout.write("_____________________________________________________________________\n".bold); -process.stdout.write(" \n"); -process.stdout.write(" OISP Backup Test before \n".green.bold); -process.stdout.write("_____________________________________________________________________\n".bold); - - - -describe("Waiting for OISP services to be ready ...\n".bold, function() { - - before(function(done) { - userToken = null; - deviceId = "00-12-23-34-45-56"; - done(); - }); - - it('Shall wait for oisp services to start', function(done) { - var kafkaConsumer; - var topic = config["connector"]["kafka"]["topic"]; - var partition = 0; - var kafkaAddress = config["connector"]["kafka"]["host"] + ":" + config["connector"]["kafka"]["port"]; - var kafkaClient = new kafka.KafkaClient({ kafkaHost: kafkaAddress }); - var kafkaOffset = new kafka.Offset(kafkaClient); - - var getKafkaOffset = function(topic_, partition_, cb) { - kafkaOffset.fetchLatestOffsets([topic_], function(error, offsets) { - if (!error) { - cb(offsets[topic_][partition_]); - } - else { - setTimeout(function() { - getKafkaOffset(topic_, partition_, cb); - }, 1000); - } - }); - }; - - getKafkaOffset(topic, partition, function(offset) { - if (offset >= 0) { - var topics = [{ topic: topic, offset: offset + 1, partition: partition }]; - var options = { autoCommit: true, fromOffset: true }; - - kafkaConsumer = new kafka.Consumer(kafkaClient, topics, options); - - var oispServicesToMonitor = ['rules-engine']; - process.stdout.write(" "); - kafkaConsumer.on('message', function(message) { - process.stdout.write(".".green); - if (kafkaConsumer) { - var i = 0; - for (i = 0; i < oispServicesToMonitor.length; i++) { - if (oispServicesToMonitor[i] != null && oispServicesToMonitor[i].trim() === message.value.trim()) { - oispServicesToMonitor[i] = null; - } - } - for (i = 0; i < oispServicesToMonitor.length; i++) { - if (oispServicesToMonitor[i] != null) { - break; - } - } - if (i === oispServicesToMonitor.length) { - kafkaConsumer.close(true); - kafkaConsumer = null; - process.stdout.write("\n"); - done(); - } - } - }); - } - else { - done(new Error("Cannot get Kafka offset ")); - } - }); - - }).timeout(1000 * 60 * 1000); -}); - -describe("get authorization and manage user ...\n".bold, function() { - - it('Shall authenticate', function(done) { - getNewUserTokens(done); - }).timeout(10000); - - it('Shall get token info', function (done) { - helpers.auth.tokenInfo(userToken, function (err, response) { - if (err) { - done(new Error("Cannot get token info: " + err)); - } else { - assert.equal(response.header.typ, 'JWT', 'response type error' ); - if (response.payload.sub == null){ - done(new Error("get null user id")); - } - else { - userId = response.payload.sub; - } - - done(); - } - }); - }); - - it('Shall get user information', function(done) { - helpers.users.getUserInfo(userToken, userId, function(err, response) { - if (err) { - done(new Error("Cannot get user information : " + err)); - } else { - assert.isString(response.id); - done(); - } - }); - }); - - it('Shall update user information', function(done) { - var newuserInfo = { - attributes:{ - "phone":"123321", - "another_attribute":"another_attribute", - "new":"value" - } - }; - - helpers.users.updateUserInfo(userToken, userId, newuserInfo, function(err, response) { - if (err) { - done(new Error("Cannot update user information : " + err)); - } else { - assert.equal(response.status, 'OK', 'status error'); - done(); - } - }); - }); -}); - -describe("Get account and create device ...\n".bold, function() { - - var accountInfo; - - it('Shall retrieve account info', function(done) { - helpers.accounts.getAccountInfo(accountId, userToken, function(err, response) { - if (err) { - done(new Error("Cannot get user info: " + err)); - } else { - accountInfo = response; - done(); - } - }); - }).timeout(10000); - - - it('Shall update an account', function (done) { - - accountInfo.attributes = { - "phone":"987654321", - "another_attribute":"this_value", - "new":"cur_string_value" - }; - - helpers.accounts.updateAccount(accountId, userToken, accountInfo, function (err, response) { - if (err) { - done(new Error("Cannot update account: " + err)); - } else { - assert.deepEqual(response.attributes, accountInfo.attributes, 'new attributes not being updated'); - done(); - } - }); - }); - - - it('Shall create device', function(done) { - assert.notEqual(accountId, null, "Invalid account id"); - - helpers.devices.createDevice(deviceName, deviceId, userToken, accountId, function(err, response) { - if (err) { - done(new Error("Cannot create device: " + err)); - } else { - assert.equal(response.deviceId, deviceId, 'incorrect device id'); - assert.equal(response.name, deviceName, 'incorrect device name'); - done(); - } - }); - }); - - it('Shall activate device without token', function(done) { - assert.notEqual(deviceId, null, "Invalid device id"); - - helpers.devices.activateDeviceWithoutToken(activationCode, deviceId, function(err, response) { - if (err) { - done(new Error("Cannot activate device: " + err)); - } else { - deviceToken = response.deviceToken; - done(); - } - }); - }).timeout(5000); - - it('Shall add device a component', function(done) { - - helpers.devices.addDeviceComponent(componentName, componentType, userToken, accountId, deviceId, function(err, id) { - if (err) { - done(new Error("Cannot create component " + componentName + " : " +err)); - } else { - if ( id ) { - componentId = id; - done(); - } - else { - done(new Error("Wrong id for component " + componentName )); - } - } - }); - - - }).timeout(10000); - - it('Shall send data point', function(done) { - - helpers.devices.submitData("22", deviceToken, accountId, deviceId, componentId, function(err) { - if (err) { - done(new Error("Cannot create device: " + err)); - } else { - done(); - } - }); - }).timeout(10000); -}); diff --git a/tests/test-config-mqtt.json b/tests/test-config-mqtt.json deleted file mode 100644 index efc399dd..00000000 --- a/tests/test-config-mqtt.json +++ /dev/null @@ -1,57 +0,0 @@ -{ - "logger": { - "LEVEL": "info", - "PATH": "/tmp/", - "MAX_SIZE": 134217728 - }, - "default_connector": "mqtt", - "connector": { - "rest": { - "host": "dashboard", - "port": 4001, - "protocol": "http", - "strictSSL": false, - "timeout": 30000, - "proxy": { - "host": false, - "port": false - } - }, - "ws": { - "host": "websocket-server", - "port": 5000, - "minRetryTime": 2500, - "maxRetryTime": 600000, - "testTimeout": 40000, - "pingPongIntervalMs": 30000, - "enablePingPong": true, - "secure": false, - "proxy": { - "host": false, - "port": false - } - }, - "kafka": { - "host": "my-cluster-kafka-bootstrap.iff.svc.cluster.local", - "port": 9092, - "topic": "heartbeat" - }, - "mqtt": { - "host": "emqx", - "port": 8883, - "qos": 1, - "retain": false, - "secure": true, - "strictSSL": true, - "retries": 5, - "topic": { - "metric_topic": "server/metric/{accountid}/{deviceid}", - "health": "server/devices/{deviceid}/health", - "health_status": "device/{deviceid}/health", - "control_command": "device/{gwid}/control", - "ingestion_response": "device/{deviceid}/metric/response", - "actuation": "server/{accountid}/DCMD/{gatewayId}/{deviceid}" - } - } - } -} diff --git a/tests/test-config-template.json b/tests/test-config-template.json deleted file mode 100644 index 228c8608..00000000 --- a/tests/test-config-template.json +++ /dev/null @@ -1,83 +0,0 @@ -{ - "logger": { - "LEVEL": "info", - "PATH": "/tmp/", - "MAX_SIZE": 134217728 - }, - "default_connector": "rest+ws", - "connector": { - "rest": { - "host": "frontend", - "port": 4001, - "protocol": "http", - "strictSSL": false, - "timeout": 30000, - "proxy": { - "host": false, - "port": false - } - }, - "ws": { - "host": "websocket-server", - "port": 5000, - "minRetryTime": 2500, - "maxRetryTime": 600000, - "testTimeout": 40000, - "pingPongIntervalMs": 30000, - "enablePingPong": true, - "secure": false, - "proxy": { - "host": false, - "port": false - } - }, - "kafka": { - "host": "my-cluster-kafka-bootstrap.iff.svc.cluster.local", - "port": 9092, - "topic": "heartbeat" - } - }, - "grafana": { - "host": "frontend", - "port": 4002, - "protocol": "http", - "subPath": "/ui/grafana", - "strictSSL": false, - "timeout": 30000, - "proxy": { - "host": false, - "port": false - }, - "admin": "grafana", - "password": "${OISP_GRAFANA_PASSWORD}", - "datasourceSuggest": "/api/v1/metricnames", - "datasourceQuery": "/api/v1/datapoints/query" - }, - "streamer": { - "host": "streamer", - "port": 9000 - }, - "tsdbproxy": { - "host": "frontend", - "port": 4003, - "protocol": "http", - "strictSSL": false, - "suggest": "/api/v1/metricnames", - "query": "/api/v1/datapoints/query", - "timeout": 30000 - }, - "skip": - { - "non_essential": "${OISP_TESTS_SKIP_NON_ESSENTIAL}", - "rules": "${OISP_TESTS_SKIP_RULES}", - "data_sending": "${OISP_TESTS_SKIP_DATA_SENDING}", - "email": "${OISP_TESTS_SKIP_EMAIL}", - "grafana": "${OISP_TESTS_SKIP_GRAFANA}", - "tsdbproxy": "${OISP_TESTS_SKIP_TSDBPROXY}", - "mqtt": "${OISP_TESTS_SKIP_MQTT}", - "alerts": "${OISP_TESTS_SKIP_ALERTS}", - "scale": "${OISP_TESTS_SKIP_SCALE}", - "streamer": "${OISP_TESTS_SKIP_STREAMER}", - "services": "${OISP_TESTS_SKIP_SERVICES}" - } -} diff --git a/wait-until-ready.sh b/wait-until-ready.sh index ad0a85ed..83292255 100644 --- a/wait-until-ready.sh +++ b/wait-until-ready.sh @@ -74,7 +74,6 @@ while kubectl -n $NAMESPACE get pods | grep -q 'Pending\|Terminating'; \ fi done; -check_deployment backend ${NAMESPACE} backend 60 check_deployment frontend ${NAMESPACE} frontend 120 check_deployment kairosdb ${NAMESPACE} kairosdb 60 check_sts mqtt-gateway ${NAMESPACE} 240