Monday, 27 November 2017

browser stack

1. proxy setup
  • webDriverProxy: 'http://606885:summer99@qfwsg-prod.qantas.com.au:8080'

2. local testing
  • test internal server
  • use 'browserstack-local'
  •  exports.bs_local.start({ 'key': exports.config.capabilities['browserstack.key'], 'proxyHost': 'qfwsg-prod.qantas.com.au', 'proxyPort': '8080', 'proxyUser': '606885', 'proxyPass': 'summer99' }, function (error)

3. protractor-multiple-cucumber-html-reporter-plugin + multiple-cucumber-html-reporter
  • connect Protractor, CucumberJS and protractor-cucumber-framework
  • create multiple reports for parallel testing  

4. protractor-cucumber-framework

5. run cucumber/protractor feature files in parallel

6. protractor tips and tricks
  • browser.pause()

7. using local test exe
  • BrowserStackLocal.exe --key 8ceKoJrDNAowyMaFV5py --proxy-host qfwsg-prod.qantas.com.au --proxy-port 8080 --proxy-user 606885 --proxy-pass winter99


reference

Saturday, 4 November 2017

powershell & chocolatey

1. set web proxy

$reg = "HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings"
Set-ItemProperty -Path $reg -Name ProxyServer -Value "proxy.example.org:8080"
Set-ItemProperty -Path $reg -Name ProxyEnable -Value 1


2. install chocolatey
iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))


3. install and uninstall app
  • cinst jdk8 -y
  • clist -l
  • cuninst packagename

4. execute native command
  • iex

5. execute executable
  • &

6. log console output to file

  • Start-Transcript -path $LogFile -append
  • Stop-Transcript

7. task security

  • run only when user is logged on
  • run whether user is logged on or not (does not work for UI interactive program like autoit)

8. rdp session



ref
1. set window web proxy with powershell
2. powerscript to install dev machine
3. powershell run executables
4. redirect output to file
5. task security when using schtasks
6. rdp session timeout configuration
7. inactive logon windows 2012

Monday, 30 October 2017

protractor with typescript

1. files
  • package.json (npm specific, same as pom.xml in maven)
  • tsconfig.json (typescript specific, typescript project file)
  • vscode cucumber plugin and cucumber-mapper plugin

2. setup
  • npm install -g protractor (global install, can use in command line without specify path)
  • npm install protractor (local install, used by require(), can also use in command line if specify path)
  • npm list <package_name> (list local packages)
  • npm list -g <package_name>  (list globally packages)
  • npm list -g --depth=0 (list globally user installed top level package)
  • npm install <package_name> --save (used for production)
  • npm install <package_name> --save-dev (used for development)
  • both write to package.json -> dependencies
  • npm install (install dependencies in ./package.json)
  • npm run update (install update)

3.tsconfig.json
  • it lists the files belonging to the project as well as compiler options
  • outFile (.ts files are converted to .js and output here, help sourceMap to find)
  • @types, typeRoots and types
  • by default all visible “@types” packages are included in your compilation
  • if typeRoots is specified, only packages under typeRoots will be included
  • if types is specified, only packages listed will be included

4. config.js
  • browser.ignoreSynchronization = true      //this is used for non-angular app, now become selemium js and should use explicit wait
  • browser.ignoreSynchronization = false     //this is used for angular app, and no wait is needed for angular element
  • browser.ignoreSynchronization is depreciated, now should use browser.waitForAngularEnabled
  • SELENIUM_PROMISE_MANAGER: false     //disable control flow
  • when control flow is disabled, can use async/await or promise chain (i.e. .then()) to synchronise command
  • when control flow is enabled, use async/await has conflict with control flow, so need to use promise chain

5. promise & control flow
  • all webdriver js (i.e. protractor) functions are async and return promises
  • webdriver js maintain a queue of pending promises called control flow 

5. debug typescript in vscode
  • "sourceMap": true in tsconfig.json so that you can debug .ts
  • configure 'launch.json' file correctly, it can contain multiple configurations (choose one when debugging)

5. shortcut
  • ctrl+shift+f (search all)
  • f5 (debug)
  • ctrl+f5 (run)
  • ctrl+p (open recent files)

6. await/async
  • async function return a promise
  • await can only be used in async function
  • await make javascript wait until promise resolve

7. webdriver js
  • when promise manager is disabled (SELENIUM_PROMISE_MANAGER=0), each command will execute as soon as it's scheduled
  • when promise manager is enabled, each command will block until the previous command complete
  • turn off control flow (SELENIUM_PROMISE_MANAGER: false) when using async/await
  • setDefaultTimeout(60 * 1000); to change default timeout

8.  npm run or npm test or npm start
  • your current package directory's bin directory is placed at the front of your path

9. npm ls selenium-webdriver

10. node js
  • single threaded
  • concurrency model based on event loop and registered callback

11. style guide
  • make test independent at least at file level

12. debug protractor in vscode
  • .vscode/launch.json

"name": "Launch",
"type": "node",
"request": "launch",
"program": "${workspaceRoot}/node_modules/protractor/bin/protractor",
"stopOnEntry": false,
"args": ["${workspaceRoot}/protractor.conf.js"],


reference

Sunday, 22 October 2017

aws

1. aws cli credential (also see item 9)
  • '~/.aws/config' file, or
    '~/.aws/credentials' file, or
    'AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY' env variable, or
    ec2 instance profile credentials
  • 'credentials' stores access keys
  • 'config' stores other configuration like region and output format
  • no conflict between 'credentials' and 'config', aws cli or java sdk will look at both file
  • when using aws cli, set 'AWS_PROFILE' env variable or use --profile flag in cli command if profile is not default
  • when using java sdk, use ProfileCredentialsProvider if profile is not default

2. iam user/group/role/policy/profile
  • user is used to sign in  (aws iam list-users)
  • group is collection of users
  • role is collection of policies (user can have multiple roles)
  • policy=permission
  • profile is a settings file

3. arn 
  • amazon resource name
  • arn:partition:service:region:account:resource        //format
  • arn:aws:iam::998355367879:user/test-user            //example: user

4. kinesis
  • streaming data service
  • consumer: firehose, data analytics etc
  • pip3 install kines
  • kines walk streamotion-gam-datalake-nonprod  000000000120 -l -f    //000000000120 is one of the shards id. shard == partition 

5. commands
  • aws configure list-profiles         //show all profiles
  • aws configure list                      //show current profile
  • aws sts get-caller-identity         //current user, role

6. profile
  • [default] is used when running cmd without --profile param
  • export AWS_PROFILE=user1                  //use the named profile

7. cli settings precedence (which override which)
  • command line option                    //--profile
  • environment variable                    //export 
  • credentials file
  • config file

8. ec2 key pair
  • when ec2 instance boost, public key is stored in instance
  • when connecting to ec2 instance, you must specify private key

9. set credentials when use java sdk or aws cli
  • option 1: use '~/.aws/credentials' file to set up credential (not 'config' file)
[default]
role_arn = arn:aws:iam::111111111111:role/group-xxxxx-xxxxx
source_profile = okta
region = ap-southeast-2

[default]
aws_access_key_id = YOUR_ACCESS_KEY
aws_secret_access_key = YOUR_SECRET_KEY

  • option 2: use aws environment variable to set up credentials
export AWS_ACCESS_KEY_ID=your_access_key_id
export AWS_SECRET_ACCESS_KEY=your_secret_access_key
export AWS_REGION=your_aws_region
  • aws env variable take precedence over ~/.aws/credentials, but in general, it's best practice to store credentials in the ~/.aws/credentials file, and load the credentials in your code using the AWSCredentialsProvider class
AWSCredentialsProvider credentialsProvider = new ProfileCredentialsProvider();


10. aws lambda vs ec2
  • ec2: need to provision container, orchestration, scaling
  • lambda: taken care of by aws

  • ec2: need to take care of security layer access
  • lambda: taken care of by aws

  • ec2: combined with ALB, has no timeout limit
  • lambda: combined with api gateway, has timeout limit of 15min for lambda and 30 sec for gateway

  • ec2: need to config auto scaling group
  • lambda: taken care of by aws

  • ec2: always available
  • lambda: on demand

  • ec2: cold start not needed unless for a new container
  • lambda: cold start needed

11. api gateway
  • default max integration timeout limit 30 sec

12. skill used at work
  • management console, cli, sdk
  • s3, secret manager, kinesis, sqs, nosql
  • ec2 - elastic compute cloud (vm)
  • ecs - elastic container service (docker)

reference

Sunday, 30 July 2017

shortcuts

1. shift + end or shift + cmd + right arrow (select till the end of line) 

2. ctrl+shift+n (chrome change to incognito mode)

3. install EditThisCookie plugin in chrome to remove cookies

4. chrome dev tools
  • search file file: ctrl + p
  • search code: ctrl + shif + f
5. eclipse
  • ctrl+shift+r (find resources)
  • ctrl+l (goto line)
6. schtasks
  • SchTasks /Create /SC DAILY /TN MyTask /TR "\"D:\CM Data Creation - Final\GeneratePNR3_SITA.exe\"" /ST 23:35
  • SchTasks /Create /SC DAILY /TN MyTask /TR D:\GeneratePNR\GeneratePNR3.exe /ST 03:30
  • schtasks.exe /query /tn MyTask /v /fo list
7. rdp
  • query session                                     //run as admin user
  • tscon 2 /dest:console
8. vs code
  • alt+left                          - go back
  • ctrl+k plus ctrl+f          - format 
  • ctrl+p                            - find file
  • ctrl+shift+\                   - find closing bracket
  • shift+option+f              - auto format

9. lICEcap
  • animated screen capture

10. chrome plugin
  • browserstack
  • editthiscookie
  • fullpagescreencapture
  • json formatter
  • launch and DTM switch/adobe experience cloud debugger
  • postman interceptor
  • WAVE evaluation tool
  • JWT debugger
  • resource override
  • live http header

11. chrome
  • remove all cookies: command + shift + delete 

12. win10
  • pin folder to quick access

reference

Wednesday, 5 July 2017

angularjs

1. ng-app
  • define the root element of the angularjs application in html

2.  angular.module
  • define the angularjs application in javascript

3. $scope
  • the model in MVC pattern (html being the view, controller being the control) 

4. data binding
  • ng-model="firstname"
  • {{firstname}}
  •  ng-model="firstname" (two way binding)

5. filter
  • a normal filter '|' transform data
  • a 'filter' filter select a subset of array

6. service
  • a singleton object that provide utility
  • example: $scope, $filter


reference

Sunday, 18 June 2017

javascript

1. data type

    string, number, boolean, null, undefined              //primitive, everything else object

    object = {type:"fiat", color:"white"};                   //object

    function Person(first, last, age, eyecolor) {         //constructor function, 1st class object
        this.firstName = first;
        this.lastName = last;
    }
    var myFather = new Person("John", "Doe");

    NaN: not a legal number
    undefined: does not have value
    null: is empty, not pointing to memory address

    compare two javascript objects always return false

2. == and ===
  • never use ==
  • === compare 'type' and 'value' for primitive type
  • === compare 'reference' for complex type
  • == do type conversion before comparison

3. closure
  • closure is function with preserved scope data
  • closure is an (usually anonymous) inner function within a outer function
  • inner function access latest value of the outer function's variable
  • essence: function can always see the variable in scope when it's defined, if the variable is not global, it will not pollute namespace
      var add = (function () {
          var counter = 0;
          return function () {return counter += 1;}  
      })();

      /* add() is a function, where it searches for the 'counter' value via lexical scope chain till find it */

      add();   // 1
      add();   // 2
      add();   // 3

4. hoist
  • 'hoisted' means you can use it before declaring it
  • 'var' and function declaration are hoisted
  • 'let' and 'const' is not hoisted
  • always declare your variables at the top!
   
      function foo() {
          function bar() {
              return 3;
          }
          return bar();
          function bar() {
              return 8;
          }
      }
      alert(foo());      //8

      function foo(){
          var bar = function() {
              return 3;
          };
           return bar();
           var bar = function() {
                return 8;
           };
      }
      alert(foo());    //3

5. const
  • const is not const value but const reference
  • cannot reassign const value, array, object
  • can change element of const array, can change property of const object

6. function
  • javascript function is OBJECT!
  • first class function/object: language treat function as variable
  • high-order function: function that works on other function, i.e. can accept function as parameter, can return function as result

7. property
  • a free form object can add property any time
  • an object created from constructor can not add additional property
      function Person(first, last, age, eyecolor) {
          this.firstName = first;
          this.lastName = last;
          this.age = age;
          this.eyeColor = eyecolor;
      }
      Person.prototype.nationality = "English";


8. prototype chain
  • all javascript objects (including function) inherit property and method from prototype
  • 'prototype' allow you to add new property and method to constructor function
  • after prototype is changed, all newly created object will have the changed property value, all previously created object will have previous value
  • '__proto__' is the property of an object, pointing to its prototype

9. wait for ajax call to complete
  • it depends on how ajax call is implemented
  • if implemented in jquery, use jquery function

10. promise
  • implementation
      var promise = new Promise (function(resolve, reject) {
          // "producing code" (may take some time)

          if (/* everything turned out fine */) {
              resolve("stuff worked!");                      //return 'stuff worked!'
          }
          else {
              reject(Error("It broke"));                      //return Error('it broke')
          }
      }); 
  • usage
      promise.then (
          onFulfilled (result) {
              console.log(result);                             // "Stuff worked!"
          }, 
          onRejected (err) {
              console.log(err);                                 // Error: "It broke"
      });

      promise.catch (
          onRejected (err) {
              console.log(err);                                // Error: "It broke"
      });
  • function needs to return a promise to be able to use .then()

11. arrow function (arguments on the left, return type on the right)
   
      (param1, param2, …, paramN) => { statements }
      (param1, param2, …, paramN) => expression          // equivalent to: => { return expression; }
      singleParam => { statements }
      () => { statements }
      params => ({foo: bar})

      const multiplyES6 = (x, y) => { return x * y };
      (id, name) => ({ id: id, name: name });

      var MakePoint: () => {x: number; y: number;};  //function declaration, not definition
      var MakePoint = () => 1;   //function definition

12. scope
  • global scope
  • function scope and block scope
  • 'var' has functional scope
  • 'let' and 'const' has block scope
  • declare variable at beginning of script
      for (var i=0; i<10; i++) {
          // block scope for the for statement
      }
      console.log(i) // => 10

      for (let i=0; i<10; i++) {
          // block scope for the for statement
      }
      console.log(i) // ReferenceError: i is not defined
  • closure: outer function variable visible in inner function

13. context vs scope
  • context is the value of 'this' when function is called
  • scope is how javascript resolve a variable at run time

14. this
  • in regular function 'this' refer to current context (the object that calls the function)
  • in arrow function 'this' will always be the context when function is initially defined
  • closure can not access outer function's 'this'
      var person = {
          name: "John",
          getName : function() {
              return this.name;
          }
      };
      person.getName();  //John, 'this' refer to person

      var person = {
          name: "John",
          getName : () => {
              return this.name;
          }
      };
      person.getName();  //window.name, 'this' refer to window

      function Person(name) {
          this.name = name;
          this.getName = () => {
              return this.name;
          }
      }
      person = new Person('Mike');
      person.getName(); //Mike


15. curried function
  • transform a function from f(a, b, c) to f(a) (b) (c)
  • equivalent curried function: let add = x => y => x + y;

16. callback

      function getWidthOfImage(src) {
          var imgWidth;

          var img = document.createElement('img');
          img.onload = function() {
              imgWidth = this.width;             //async call
          };
          return imgWidth;                          //return 'undefined'
      }

      var width = getWidthOfImage('lolcat.png');
      alert(width);

      function getWidthOfImage(src, cb) {   
          var img = document.createElement('img');
          img.onload = function() {
              cb(this.width);
          };
      }

      getWidthOfImage('lolcat.png', function (width) {
          alert(width);                                  //using callback
      });

17. var vs let, const
  • var is scoped to the nearest function scope
  • let, const is scoped to the nearest block scope
  • use 'let' if you'll reassign value
  • use 'const' unless you'll reassign value
  • never use 'var'

18. common function
  • map() create a new array when calling a function on current array
  • splice() insert item into array at specified index
  • split() split a string into an array of substrings
  • slice(begin, end) return part of the string

19. ...
  • rest operatunor: get the argument list passed to function
      function countArguments(...args) {  
          return args.length;
      }

20. async and await
  • async function returns a promise
  • you can use await with any function that returns a promise (not necessarily async) 
  • you should use async function ONLY when you use await inside the function
  • makes it easier to use common programming constructs like return and try/catch
  • await won't work in the top level code

21. catch error for promise
  • use asyn/await
  • ending promise chain with catch()
save()
  .then(
    handleSuccess,
    handleNetworkError
  )
  .catch(handleProgrammerError)
;


22. generator and yield
  • generator return an iterator
  • each call to the iterator's next() function return the next step
  • each step's value is the value specified by yield

23. IIFE
  • does not pollute global namespace
(function() {
  /* */
  return {}          //return object literal
})()


24. shallow copy vs deep copy
  • primitive type: pass value
  • structural type: pass reference
  • shallow copy does not work with nested objects

25. optional access operator
  • ?      // optional chaining, if object is undefined or null, it will short circuit to undefined instead of throwing error

reference
1. javascript closure
2. javascript promise
3. how javascript promise works
4. understand javascript this
5. understanding javascript closure
6. ES6 arrow functions
7. typescript deep dive
8. javascript scope and context
9. when to use arrow function
10. call back, promise and async await
11. the modern javascript tutorial
12. javascript scope and closures
13. function scope and block scope
14. catch error in javascript promise
14. arrow function
15. javascript inheritance
16, top javascript to learn 2017
17. promise resolve and reject
18. From JavaScript Promises to Async/Await: why bother?
19. javascript generators: understanding them
20. the basics of javaScript generators
21. the modern javascript tutorial
22. need to return a promise to be used by then()
23. javascript inheritance pattern
24. 6-advanced-javascript-techniques-you-should-know
25. 23 advanced javascript interview questions
26. javascript.info async-await

Monday, 5 June 2017

algorithm

1. tree traversal
  • depth-first-search, use stack
  1. pre-order: root, left, right
  2. in-order: left, root, right
  3. post-order: left, right, root
  • breadth-first-search, use queue
  1. level-order: 1st level, 2nd level

2. pre-order
  • check if root is empty or null
  • display(root->data)
  • preorder(root->left)
  • preorder(root->right)

3. inorder
  • check if root is empty or null
  • inorder(root->left)
  • display(root->data)
  • inorder(root->right)

4. post-order
  • check if root is empty or null
  • postorder(root->left)
  • postorder(root->right)
  • display(root->data)

5. coding interview
  • 'null' check
  • use 'sorting'
  • use 'map'
  • use 'two index pointer'

6. two sum

    problem:
        find indices of two numbers such that they add to specific target value
        e.g. given nums = [2, 7, 11, 15], target = 9

    solution:
         1. use hashmap, while iterate array, store (9's complement of a[i], i)  to map, search map
         2. 双指针,一头一尾,sum小移头,sum大移尾

7. binary search
  • edge case 1: array==null || array.length ==0
  • edge case 2: target < min(array) || target > max(array)
  • edge case 3: if it is not a perfect match, found index diff by either +1 or -1
    int binarySearch (int[] nums, int target){
        if (nums == null || nums.length == 0)
            return -1;

        int left = 0, right = nums.length - 1;

        while(left < right){
            // Prevent (left + right) overflow
            int mid = left + (right - left) / 2;
            if (nums[mid] == target) { return mid; }
            else if (nums[mid] < target) { left = mid + 1; }
            else { right = mid - 1; }
        }

        // End Condition: left > right
        return -1;
}

8. binary search tree

    public static boolean contains(Node root, int value) {
        if (root == null) {
            return false;
        } else if (root.value == value) {
                return true;
   
        } else if (value < root.value) {
            return contains(root.left, value);
        } else {
            return contains(root.right, value);
        }
    }

9. longest substring without repeating char
  • use hashmap to store existing char and index 
  • use sliding window to track current substring
  • if duplicate char is found, update sliding window to the right of duplicate

10. merge two sorted array

    input:
    nums1 = [1,2,3,0,0,0], m = 3
    nums2 = [2,5,6],       n = 3

    output: [1,2,2,3,5,6]

    public void merge(int a[], int m, int b[], int n) {
        int i = m - 1;
        int j = n - 1;
        int k = m + n - 1;

while (i >= 0 && j >= 0) {
            if (a[i] > b[j])
                a[k--] = a[i--];
            else
                a[k--] = b[j--];
            }
        while (j >= 0)
                a[k--] = b[j--];
    }

11. leetcode: https://www.youtube.com/watch?v=qg0CY00qJqI&list=PLi9RQVmJD2fYXgBAUfaN5MXgYPUTbzqeb&index=6


reference
1. cracking the coding interview.pdf
2. tree traversal, preorder, inorder, postorder
5. Steven Skiena's The Algorithm Design Manual.

Friday, 2 June 2017

rest-assured

1. getting started
  • place rest-assured before the JUnit dependency declaration in pom.xml
  • use statically import methods, i.e. 'import static io.restassured.RestAssured.*;'

2. example

given().   // parameter
    contentType()
    param().
    formParam().
    queryParam().

when().   // action
    get().
    put()
    post().

then().     // field
    body()
    statusCode()

assertion  // locator + matcher

locator
--------
lotto.lottoId
lotto.winners.winnerId

find { it.@type == 'groceries' }  //Groovy

hamcrest matchers
-----------------------
is
equalTo
hasItems
hasXPath
matchesXsd
matchesJsonSchemaInClasspath
matchesXsd

    {
        "lotto":{
            "lottoId":5,
            "winning-numbers":[2,45,34,23,7,5,3],
            "winners":[
               {
                    "winnerId":23,
                    "numbers":[2,45,34,23,3,5]
                },
               {
                    "winnerId":54,
                    "numbers":[52,3,12,11,18,22]
                }
             ]
        }
    }


3. pass parameters

    given().                                           //'get' will automatically convert param to query
        param("param1", "value1").
    when().
        get("/something");

    given().                                           //'post' and 'put' user will hava choice
        formParam("formParamName", "value1").
        queryParam("queryParamName", "value2").
    when().
        post("/something");


4. others
  • log().all()
  • request.relaxedHTTPSValidation()

5. multipart/form data 
  • multipart -> multiPart (file)
  • form data -> formParam (json, name value pair)

6. link in rest-assured/SSLITest.java for example on using of certificate

7. link for client certificate example on using .jks as truststore and .p12 as keystore

8. two ways to parse json response and 1 way to reconstruct into json

    Map responseBody = RestAssuredClientFactory.responseToObject(response, Map)
    assert responseBody.BSBResponse.BSBName

    @Step("Map response to generic Object")
    public static <T> T responseToObject(Response response, Class<T> responseType) {
        return response.getBody().as(responseType);
    }

   or 
   
   response.jsonPath().get("results[0].data.type")

   then 
   new JsonBuilder(payload).toPrettyString()


9. do not use default charset in content header

RestAssured.config =
    RestAssured.config().encoderConfig(
            RestAssured.config().encoderConfig
                    .appendDefaultContentCharsetToContentTypeIfUndefined(false))


10. create json payload

ObjectMapper objectMapper = new ObjectMapper()
        def payload = [
                assetId: assetId,
                udid: playerEnum.udid
        ]
objectMapper.writeValueAsString(payload)


11. package io.restassured.path.json
      public class JsonPath {}
      can be used to parse json STRING in general


12. use jackson to change json file value

import com.fasterxml.jackson.databind.ObjectMapper
String path = FileSystem.getResourcePath(fileName)
Map map = objectMapper.convertValue(loadFile(path), Map)   //convert from jsonNode to map
map.channel.name = channelName                                             //change value
objectMapper.writeValueAsString(map)                                     //convert back to json

static JsonNode loadFile(String file) {
    InputStream fileStream = new FileInputStream(file)
    objectMapper.readValue(fileStream, JsonNode)
}


13. groovy define json payload 

def payload = [records: []]
payload.records << [
        key  : [
                channelName: playList.channelName,
                origin     : playList.origin
        ],
        value: [
                channel: [
                        name   : playList.channelName,
                        enabled: false
                ],
                date   : playList.playlistDate
]

protractor

1. install nodejs

2. install protractor and start selenium server
  •     npm install -g protractor
  •     webdriver-manager update
chromedriver version which protractor uses for tests executing depends on version in node_modules/protractor
npm update protractor - update protractor to latest version
webdriver-manager update - update chrome driver to latest version
  •     webdriver-manager start

3. run protractor
  •     protractor conf.js

4. angular locator
  •     browser.getTitle()
  •     by.model
  •     by.id
  •     by.binding
  •     by.repeater

5. webdriverjs is asynchronous
  • by default it return promise
  • .then() is called when promise is 'fulfilled', .catch() is called when promise is 'rejected
  • 'control flow' ensure async tasks executed and completed in the correct order 

6. framework
  • by default, protractor use jasmine
  • cucumber is no longer included
  • it also support mocha and cucumber, cucumber is prefered

7. exports.config = {
        seleniumAddress: "http://127.0.0.1:4444/wd/hub",
        baseUrl: "localhost:8080"
}
  • used for globals variables and configuation of test

8. webdriver control flow
  • most webdriver actions are asynchronous
  • to synchroize, use either 'control flow', 'promise chain' or 'async/await'
  • control flow makes sure commands are executed in the order they were received
  • protractor will wait until control flow is empty before deeming a test finished

9. protractor click method on anchor is not working
  • browser.executeScript("arguments[0].scrollIntoView();", e.getWebElement());
  • browser.executeScript("arguments[0].click();", e.getWebElement());

10. protractor-cucumber-framework

11. 'defineSupportCode' is depreciated in cucumber
  • use 'import {Given,Then,When} from "cucumber";'
  • use 'import {setWorldConstructor} from 'cucumber''

12. debug in vscode
  • add configuration
  • specify 'program' and 'args'
            "args":["${workspaceFolder}/protractor.conf.js"],
            "program": "${workspaceFolder}/node_modules/protractor/bin/protractor"
  • node_modules/protractor/bin/webdriver-manager update
  • webdriver-manager start before debug
  • kill -9 $(lsof -ti tcp:4444)

13. cucumber (gherkin) full support plugin
  • setting.json in .vscode folder to specify feature/step mapping


reference:
1. install nodejs in windows
2. protractor tutorial
3. enqueue non-promise statement into control flow
4. protractor-cucumber-framework
5. protractor-vs-webdriverio-vs-nightwatch
6. in depth protractor tutorial
7. protractor not working on anchor
8. webdriver control flow
9. return promise in protractor-cucumber-framework step function
10. defineSupportCode is not supported in cucumber
11. how to use setWorldConstructor
12. debug protractor in vscode
13. “could not find update-config.json” error message

Tuesday, 16 May 2017

Junit and TestNG

1. junit

2. junit folder structure (automatically created when create maven project in eclipse)
      module/
            src/
                  main/
                        java/
                  test/
                        java/

3. common issue 1
  • package org.junit does not exist' even though dependency added in pom.xml
  • root cause: in eclipse you default select create 'new junit 4 test', then in pom.xml you choose junit version '4.11' instead of '3.8.1'
4. common issue 2
  • if @Test use: public class xxxTest extends TestCase {}, it is junit 3
  • then you see error 'No tests found in package'
  • root cause: in junit 4, should use public class xxxTest {}
5. common issue 3
  • unknown lifecycle phase "Maven". you must specify a valid lifecycle phase or a goal
  • root cause: in eclipse the goal for maven run configuration should be e.g. 'test' instead of 'maven test'

reference
1. junit faq
2. unit testing with Junit - tutorial
3. youtube junit setup

Monday, 27 February 2017

serenity & jbehave

1. serenity.properties

    serenity.timeout=20000
    webdriver.wait.for.timeout=20000           //explicit timeout
    serenity.take.screenshots=FOR_FAILURES


2. implicit wait
    webdriver.timeouts.implicitlywait property


3. explicit wait

    webdriver.wait.for.timeout

    waitFor(ExpectedConditions.presenceOfElementLocated(By.cssSelector(".mjHome")));
    withTimeoutOf(10,TimeUnit.SECONDS).waitFor(ExpectedConditions.presenceOfElementLocated(By.cssSelector(".mjHome")));


4. the correct plugin to use for jbehave is 'jbehave support', uninstall the others if unable to display step definition properly

Thursday, 23 February 2017

pl/sql


1. anonymous block
      [declare]
           ...
      begin
           ...
           [exception]
               ...
      end;
      /                              // / is a signal to instruct sql client to execute pl/sql block

      --/                           // --/..../ is a signal to instruct dbvisualizer to execute pl/sql block
      begin
         null;
      end;
      /


2. declare variable
      declare
         v_last_name            varchar2(20);
         v_first_name           table_1.column_1%type;
         n_employee_id       number;
         d_hire_date             date;
         b_flag                      boolean;

         type tableType is table of existing_table%rowtype;      //define table based on existing
         t_my_table                 tableType ;

         r_my_row               existing_table%rowtype;
      begin
         v_first_name := 'Mary';
         v_last_name := 'Jane';
         d_hire_date := to_date('19700101','yyyymmdd');
         b_flag := false;
      end;


3. function
      create [or replace] function function_name (
         parameter_1 [in] [out] data_type,
         parameter_2 [in] [out] data_type,
         parameter_n [in] [out] data_type
      )
      return return_data_type IS
      ...                                                                       //declare
      begin
         ...                                                                    //execute
         return return_data_type;
         exception
         ...                                                                    //exception
      end;


4. call a function
      declare
        n_x number;
      begin
         n_x := try_parse('574');
         dbms_output.put_line(n_x);
      end;

or

      select try_parse('1234') from dual;


5. procedure
  • no return value compared with function
      create or replace procedure [schema.]name[( parameter[, parameter...] ) ]
      is
      ...
      begin
        ...
        exception
        ...
      end [name];


6. call procedure
      exec procedure_name(param1,param2…paramn);


reference
1. pl/sql tutorial
2. pl/sql working with record
3. sql topics