<commit_before>/**
 *****************************************************************************
 Copyright (c) 2019 IBM Corporation and other Contributors.
 All rights reserved. This program and the accompanying materials
 are made available under the terms of the Eclipse Public License v1.0
 which accompanies this distribution, and is available at
 http://www.eclipse.org/legal/epl-v10.html
 *****************************************************************************
 *
 */
const uuidv4 = require('uuid/v4');

import { expect, use } from 'chai';
const chaiAsPromised = require('chai-as-promised');
use(chaiAsPromised);

var Cloudant = require('@cloudant/cloudant');

import { ApplicationConfig, ApplicationClient } from '../src/application';
import * as errors from '../src/api/ApiErrors';

// Turn off console output
console.info = () => {};



const generateCloudantServiceConfigDbName = (orgId, serviceId) => {
    return `iotp_${orgId}_${serviceId}_configuration`;
}

const generateCloudantDestinationConfigDbName = (orgId, destinationName) => {
  return `iotp_${orgId}_${destinationName}_configuration`;
}

const generateCloudantDestinationBucketDbNamePattern = (orgId, destinationName, bucketInterval) => {
  let bucketPattern;
  switch(bucketInterval.toUpperCase()) {
    case 'DAY': bucketPattern = '\\d{4}-\\d{2}-\\d{1,2}'; break;
    case 'WEEK': bucketPattern = '\\d{4}-w\\d{1,2}'; break;
    case 'MONTH': bucketPattern = '\\d{4}-\\d{2}'; break;
    default: throw new Error(`Unknown bucketInterval: ${bucketInterval}`);
  }
  return new RegExp(`iotp_${orgId}_${destinationName}_${bucketPattern}`);
}


/*
 * Wrap cloudant:2.1.0 (OSS pre-approved) to callbacks to promises
 */


const cloudantDestroyDb = (cloudant, dbName) => {
  return new Promise( 
    (resolve, reject) => {
      cloudant.db.destroy(
        dbName, 
        function(err, data) {
          if(err){
            console.warn(`Failed to delete cloudant DB ${dbName}: ${err}`);
            reject(err);
          } else {
            resolve(data);
          }
        }
      );
    }
  );
}


const cloudantListDbs = (cloudant) => {
  return new Promise(
    (resolve, reject) => cloudant.db.list(function(err, data) {
      if(err) {
        console.warn(`Failed to list cloudant DBs`);
        reject(err);
      } else {
        resolve(data);
      }
    })
  )
}

describe('WIoTP DSC Client Capabilities', function() {

  let orgId = null;
  let dscClient = null;

  before("Initialize the application", function(){
    const appConfig = ApplicationConfig.parseEnvVars();
    orgId = appConfig.getOrgId();
    const appClient = new ApplicationClient(appConfig);
    dscClient = appClient.dsc;
  });



  // TODO: Example scenarios - these should both:
  //  1. provide coverage of client function
  //  2. serve as useful, self-documenting reference material
  // e.g.
  describe('Create, retrieve, connect and delete a Cloudant service binding', function() {

      this.timeout(10000);

      const description = 'WIoTP DSC Client Capabilities / Create, retrieve, connect and delete a Cloudant service binding';
    
      let cloudantUsername;
      let cloudantPassword;
      let cloudant;

      let createdService;
      let createdConnector;
      let createdDestination;
      let createdForwardingRule;


      before('Init Cloudant Client', function() {
        cloudantUsername = process.env.CLOUDANT_USERNAME || null;
        cloudantPassword = process.env.CLOUDANT_PASSWORD || null;
        if( cloudantUsername === null) expect.fail('CLOUDANT_USERNAME env variable is required for this test');
        if( cloudantPassword === null) expect.fail('CLOUDANT_PASSWORD env variable is required for this test');
        cloudant = Cloudant({account: cloudantUsername, password: <PASSWORD>Password})
      })

      step('Create service', () => {
        const name = uuidv4();
        return dscClient.createCloudantService({name, description, username: cloudantUsername, password: <PASSWORD>antPassword})
          .then(_createdService => {
            console.log(_createdService)
            createdService = _createdService;
            expect(createdService.type).to.equal('cloudant');
            expect(createdService.name).to.equal(name);
            expect(createdService.description).to.equal(description);
          });
      })

      step('Retrieve services', () => {
        return dscClient.getServices()
          .then(services => {
            expect(services).to.have.property('results');
            const filtered = services.results.filter(service => service.id === createdService.id);
            expect(filtered).to.have.length(1);
            const service = filtered[0];
            expect(service).to.deep.equal(createdService);
          });
      });

      
      step('Retrieve service', function() {
        dscClient.getService(createdService.id)
          .then(service => {
            expect(service).to.deep.equal(createdService);
          })
      });
      

      step('Create connector for service', function() {
        const name = uuidv4();
        const timezone = "Africa/Casablanca";
        return dscClient.createConnector({name, description, serviceId: createdService.id, timezone})
          .then(connector => {
            createdConnector = connector;
            expect(connector).to.have.property('id');
            expect(connector).to.have.property('name', name);
            expect(connector).to.have.property('serviceId', createdService.id);
            expect(connector).to.have.property('type', 'cloudant');
            expect(connector).to.have.property('timezone', timezone);
            expect(connector).to.have.property('enabled', true);
            expect(connector).to.have.property('created');
            expect(connector).to.have.property('createdBy');
            expect(connector).to.have.property('updated');
            expect(connector).to.have.property('updatedBy');
            expect(connector).to.have.property('refs');
          })
      });

      // TODO: retrieve connector
      // TODO: retrieve connectors

      
      step('Create connector destination', function() {
        const name = uuidv4();
        console.log(name);
        const bucketInterval = 'MONTH';
        return dscClient.createCloudantDestination(createdConnector.id, {name, bucketInterval})
          .then(destination => {
            createdDestination = destination;
            expect(destination).to.have.property('name', name);
            expect(destination).to.have.property('type', 'cloudant');
            expect(destination).to.have.property('configuration');
            expect(destination.configuration).to.have.property('bucketInterval', bucketInterval);
          })
      });

      // TODO: retrieve connector destination
      // TODO: retrieve connector destinations

      step('Create connector forwarding rule', function() {
        const name = uuidv4();
        const deviceType='*';
        const eventId='*';
        return dscClient.createEventForwardingRule(createdConnector.id, {name, destinationName: createdDestination.name, deviceType, eventId})
          .then(forwardingRule => {
            createdForwardingRule = forwardingRule;
            expect(forwardingRule).to.have.property('name', name);<commit_msg>Remove some console.logs left in by mistake<commit_after>/**
 *****************************************************************************
 Copyright (c) 2019 IBM Corporation and other Contributors.
 All rights reserved. This program and the accompanying materials
 are made available under the terms of the Eclipse Public License v1.0
 which accompanies this distribution, and is available at
 http://www.eclipse.org/legal/epl-v10.html
 *****************************************************************************
 *
 */
const uuidv4 = require('uuid/v4');

import { expect, use } from 'chai';
const chaiAsPromised = require('chai-as-promised');
use(chaiAsPromised);

var Cloudant = require('@cloudant/cloudant');

import { ApplicationConfig, ApplicationClient } from '../src/application';
import * as errors from '../src/api/ApiErrors';

// Turn off console output
console.info = () => {};



const generateCloudantServiceConfigDbName = (orgId, serviceId) => {
    return `iotp_${orgId}_${serviceId}_configuration`;
}

const generateCloudantDestinationConfigDbName = (orgId, destinationName) => {
  return `iotp_${orgId}_${destinationName}_configuration`;
}

const generateCloudantDestinationBucketDbNamePattern = (orgId, destinationName, bucketInterval) => {
  let bucketPattern;
  switch(bucketInterval.toUpperCase()) {
    case 'DAY': bucketPattern = '\\d{4}-\\d{2}-\\d{1,2}'; break;
    case 'WEEK': bucketPattern = '\\d{4}-w\\d{1,2}'; break;
    case 'MONTH': bucketPattern = '\\d{4}-\\d{2}'; break;
    default: throw new Error(`Unknown bucketInterval: ${bucketInterval}`);
  }
  return new RegExp(`iotp_${orgId}_${destinationName}_${bucketPattern}`);
}


/*
 * Wrap cloudant:2.1.0 (OSS pre-approved) to callbacks to promises
 */


const cloudantDestroyDb = (cloudant, dbName) => {
  return new Promise( 
    (resolve, reject) => {
      cloudant.db.destroy(
        dbName, 
        function(err, data) {
          if(err){
            console.warn(`Failed to delete cloudant DB ${dbName}: ${err}`);
            reject(err);
          } else {
            resolve(data);
          }
        }
      );
    }
  );
}


const cloudantListDbs = (cloudant) => {
  return new Promise(
    (resolve, reject) => cloudant.db.list(function(err, data) {
      if(err) {
        console.warn(`Failed to list cloudant DBs`);
        reject(err);
      } else {
        resolve(data);
      }
    })
  )
}

describe('WIoTP DSC Client Capabilities', function() {

  let orgId = null;
  let dscClient = null;

  before("Initialize the application", function(){
    const appConfig = ApplicationConfig.parseEnvVars();
    orgId = appConfig.getOrgId();
    const appClient = new ApplicationClient(appConfig);
    dscClient = appClient.dsc;
  });



  // TODO: Example scenarios - these should both:
  //  1. provide coverage of client function
  //  2. serve as useful, self-documenting reference material
  // e.g.
  describe('Create, retrieve, connect and delete a Cloudant service binding', function() {

      this.timeout(10000);

      const description = 'WIoTP DSC Client Capabilities / Create, retrieve, connect and delete a Cloudant service binding';
    
      let cloudantUsername;
      let cloudantPassword;
      let cloudant;

      let createdService;
      let createdConnector;
      let createdDestination;
      let createdForwardingRule;


      before('Init Cloudant Client', function() {
        cloudantUsername = process.env.CLOUDANT_USERNAME || null;
        cloudantPassword = process.env.CLOUDANT_PASSWORD || null;
        if( cloudantUsername === null) expect.fail('CLOUDANT_USERNAME env variable is required for this test');
        if( cloudantPassword === null) expect.fail('CLOUDANT_PASSWORD env variable is required for this test');
        cloudant = Cloudant({account: cloudantUsername, password: <PASSWORD>})
      })

      step('Create service', () => {
        const name = uuidv4();
        return dscClient.createCloudantService({name, description, username: cloudantUsername, password: <PASSWORD>})
          .then(_createdService => {
            createdService = _createdService;
            expect(createdService.type).to.equal('cloudant');
            expect(createdService.name).to.equal(name);
            expect(createdService.description).to.equal(description);
          });
      })

      step('Retrieve services', () => {
        return dscClient.getServices()
          .then(services => {
            expect(services).to.have.property('results');
            const filtered = services.results.filter(service => service.id === createdService.id);
            expect(filtered).to.have.length(1);
            const service = filtered[0];
            expect(service).to.deep.equal(createdService);
          });
      });

      
      step('Retrieve service', function() {
        dscClient.getService(createdService.id)
          .then(service => {
            expect(service).to.deep.equal(createdService);
          })
      });
      

      step('Create connector for service', function() {
        const name = uuidv4();
        const timezone = "Africa/Casablanca";
        return dscClient.createConnector({name, description, serviceId: createdService.id, timezone})
          .then(connector => {
            createdConnector = connector;
            expect(connector).to.have.property('id');
            expect(connector).to.have.property('name', name);
            expect(connector).to.have.property('serviceId', createdService.id);
            expect(connector).to.have.property('type', 'cloudant');
            expect(connector).to.have.property('timezone', timezone);
            expect(connector).to.have.property('enabled', true);
            expect(connector).to.have.property('created');
            expect(connector).to.have.property('createdBy');
            expect(connector).to.have.property('updated');
            expect(connector).to.have.property('updatedBy');
            expect(connector).to.have.property('refs');
          })
      });

      // TODO: retrieve connector
      // TODO: retrieve connectors

      
      step('Create connector destination', function() {
        const name = uuidv4();
        const bucketInterval = 'MONTH';
        return dscClient.createCloudantDestination(createdConnector.id, {name, bucketInterval})
          .then(destination => {
            createdDestination = destination;
            expect(destination).to.have.property('name', name);
            expect(destination).to.have.property('type', 'cloudant');
            expect(destination).to.have.property('configuration');
            expect(destination.configuration).to.have.property('bucketInterval', bucketInterval);
          })
      });

      // TODO: retrieve connector destination
      // TODO: retrieve connector destinations

      step('Create connector forwarding rule', function() {
        const name = uuidv4();
        const deviceType='*';
        const eventId='*';
        return dscClient.createEventForwardingRule(createdConnector.id, {name, destinationName: createdDestination.name, deviceType, eventId})
          .then(forwardingRule => {
            createdForwardingRule = forwardingRule;
            expect(forwardingRule).to.have.property('name', name);
{'fraction_non_alphanumeric': 0.14773117319969795, 'fraction_numerical': 0.004805382027871216, 'mean_word_length': 2.9673202614379086, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 41, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3912703', 'n_tokens_mistral': 3925, 'n_tokens_neox': 3850, 'n_words': 857}