lundi 30 novembre 2015

No option to add User and Roles to iTunesConnect

I have an enrolled an apple account and i have membership of developer portal.

Recently my client wanted me to use testflight and as long as i researched regarding testflight. It says i have to add "User & Roles" in first step.

But i cant see any option for "User & Roles" under iTunesConnect. Also i have Admin rights but still cant see that option.

The person who is team agent can see this option but when adding users there is no option to select "Technical"

Please help whether any different enrolment needed to use Apple Testflight for testing purpose?

Code Coverage Test

Task: Using the bankAccount() method, draw its flow graph and list all the possible paths in the flow of the method. List all possible paths

You should list paths that include up to 2 menu choices followed by a quit eg. ‘make a deposit’, followed by ‘print a balance’ then ‘quit’ could be one valid path.

I have completed this task using flowchart. As i am new to this, I would appreciate if someone could look at my solution and let me know if it's good. I've put many hours into this so hopefully i've done the right thing.

The flowchart (my solution): enter image description here

The code that contains the bankAccount() method:

import  java.text.DateFormat;
import  java.text.SimpleDateFormat;
import  java.util.*;

public  class   Bank {

    public  int bankAccount(int customerNumber, int startingBalance) {
        Scanner stdin = new Scanner(System.in);
        System.out.println("Welcome to  the Bank.");
        Customer myCustomer = Customer.getWithCustomerNumber(customerNumber);   // get the customer
        String name = myCustomer.name; // get the customer name
        int balance = startingBalance; // get the starting balance
        DateFormat dateFormat   =   new SimpleDateFormat("yyyy/MM/dd    HH:mm:ss");     // Get the date and time
        Date date = new Date();
        int choice  =   0; //1=make deposit, 2=make withdrawal, 3=print balance, 4=quit

        while (choice != 4) { // process until the user quits
            System.out.println("Here are your menu options:");
            System.out.println("1. Make a deposit.");
            System.out.println("2. Make a withdrawal.");
            System.out.println("3. Print your balance.");
            System.out.println("4. Quit.");
            System.out.println("Please enter the number of your choice.");
            choice = stdin.nextInt();
            switch (choice) {
                case 1: {   //handles deposit
                    System.out.println("Enter   the amount  of  your    deposit.");
                    int deposit =   stdin.nextInt();
                    balance =   balance +   deposit;
                    System.out.println(dateFormat.format(date)+"Customer " + name + " new balance is $" + balance + ".");
                    break;
                }
                case 2: { // handles withdrawal
                    System.out.println("Enter   the amount  of  your    withdrawal.");
                    int withdrawal  =   stdin.nextInt();
                    if  (balance - withdrawal >= 0) {
                        balance = balance - withdrawal;
                        System.out.println(dateFormat.format(date) + "Customer " + name + " new balance is $" + balance + ".");
                    }   
                    else    
                        System.out.println(dateFormat.format(date)  +   " Customer  " + name +  " Insufficient  funds for withdrawal. Balance is $" +balance+".");
                    break;
                }
                case 3: { //prints current balance
                    System.out.println(dateFormat.format(date)+"Customer "+name+" balance is $" +balance+".");
                    break;
                }
                case 4: {
                    break; // do nothing... quits
                }
                default: {
                    System.out.println("Sorry   that    is  not a   valid   choice.");
                }
            }
        }
        System.out.println("Thank you for using the bank!");
        return  balance;
        }
}

Length Validation Testing Rails Test:Unit

I am just getting into Rails testing, and I am using the built in testing "language" as opposed to Rspec. For the life of me I can't figure out why this is still failing.

test "product title is at least 10 chars long" do
    product = Product.new(description: 'yyy',
                          image_url: 'zzz.jpg',
                          price: 1)
    product.title = 'testitout'
    assert product.invalid?
    assert_equal ['title must be at least 10 chars long'], product.errors[:title]

    product.title = 'testitoutt'
    assert product.valid?
end

And here is the Product.rb

class Product < ActiveRecord::Base
  validates :title, :description, :image_url, presence: true
  validates :price, numericality: {greater_than_or_equal_to: 0.01}
  validates :title, uniqueness: true
  validates :image_url, allow_blank: true, format: {
    with: %r{\.(gif|jpg|png)\Z}i,
    message: 'must be a URL for GIF, JPG, or PNG'
  }
  validates :title, length: { minimum: 10 }
end

How Selenium webdriver locate element with a http response full of javascript

I use selenium webdriver to speed up my testing. In my work our website will redirect to paypal for user to finish payment. However, I cannot make selenium webdriver to locate the email and password input field on paypal.

The sample paypal URL : http://ift.tt/1SsWKXA

A demo of my code may like this:

    WebDriver m_driver = new FirefoxDriver();
    String redirected_url = "http://ift.tt/1PpC7xE";

    m_driver.get(redirected_url);
    Thread.sleep(15*1000);
    WebElement we = m_driver.findElement(By.xpath(".//*[@id='email']"));
    we.sendKeys("login_email");
    we = m_driver.findElement(By.xpath(".//*[@id='password']"));
    we.sendKeys("login_password");
    we = m_driver.findElement(By.xpath(".//*[@id='btnLogin']"));
    we.click();

My problem:

With that code and on the paypal website, I always got an error message of 'no such element' found exception.

I can locate the element with firepath in firefox but I cannot make selenium webdriver work.

I know this error may be caused by the javascript in the whole page of the paypal login page. I just don't know how to handle this situation. Can you please help me with an answer?

best way to check logs after Makefile command

One of my projects' Makefile runs a bunch of tests on a headless browser for the functional test step. Most of the test is for the front-end code, but i also check for any error/warning on the backend.

Currently, we are cleaning the web server log, running all the (very slow) tests, and then grepping the server log for any error or warning.

i was wondering if there was any way to have a listener parsing the log (e.g. tail -f | grep) starting on the background, and kill the make target if it detects any error/warning during the test run.

what i got so far was

  1. start long lived grep in the background and store PID.
  2. run tests.
  3. check output of long lived grep
  4. kill PID.
  5. in case of any error, fail.

This only bought me the advantage that now i do not lose the server logs on my dev box every time, as i do not have to clean it every time. But i still have to wait a long time (minutes) for a failure that may have occurred in the very first one.

is there any solution for it?

Laravel 5.1 PHPUnit - press() gives me 'Unreachable field ""'

When trying to call the press() method, I always get

InvalidArgumentException: Unreachable field ""

at that line.

According to the docs:

"Press" a button with the given text or name.

My method: press('Create') and my button is <button class="btn btn-lg btn-primary" type="submit" name="submit">Create</button>. I have also tried to use the name with the same result.

I have also tried submitForm('Create') which works, but then seeInDatabase('employees', ['email' => 'john@email.com']) always fails.

Unable to find row in database table [employees] that matched attributes [{"email":"john@email.com"}].

Here is my full method

public function testExample()
{

  $this->actingAs(\App\Employee::where('username', 'grant')->first())
    ->visit('/employees/create')
    ->type('john', 'username')
    ->type('1234', 'password')
    ->type('john@email.com', 'email')
    ->submitForm('Create')
    ->seeInDatabase('employees', ['email' => 'john@email.com'])
    ->see('Employee Directory');
}

Protractor Test Cases by sending key to md-auto-complete in Angular material

I want to send a key to the md-autocomplete but I am not able to send key into text field , Find code below

HTML:

 <md-autocomplete md-selected-item="selectedItem" md-search-text="searchText" md-items="item in getMatches(searchText)" md-item-text="item.display">
      <span id="xyz" md-highlight-text="searchText">{{item.display}}</span>
    </md-autocomplete>

Protractor code :

  it('checking my test case', function() {
    browser.get('http://localhost:8080/#/home');

    var inputSearchTextBox = element(by.id("xyz"));
    inputSearchTextBox.sendKeys('Boston , us , 02120');
  });

I am getting below error :

Test checking my test case
   Message:
     NoSuchElementError: No element found using locator: By.id("xyz")
   Stacktrace:
     NoSuchElementError: No element found using locator: By.id("xyz")

Angular Material Link :

ms-AutoComplete Link

Is there any way I can send key to md-autocomplete tag text field

Controller test for update, show and destroy does't work for referenced class

I have the "users" and the "empresas", i used the scaffold command to generate the initial CRUD for "empresas" and after that i put the users id into the empresas and all the model need to, so what i want is to just the users that are the owner of the empresa can have acess to the "show", "update" and "destroy", i have a correct_user function and before action to apply that on the actions, everything works fine, unless the tests, i just apply the login into the original scaffold tests.

Empresas Controller

class EmpresasController < ApplicationController
  before_action :set_empresa, only: [:show, :edit, :update, :destroy]
  before_action :logged_in_user, only: [:update, :show, :index, :create, :destroy]
  before_action :correct_user,   only: [:show, :update, :destroy]

  # GET /empresas
  # GET /empresas.json
  def index
    @empresas = current_user.empresas.all
  end

  # GET /empresas/1
  # GET /empresas/1.json
  def show
  end

  # GET /empresas/new
  def new
    @empresa = Empresa.new
  end

  # GET /empresas/1/edit
  def edit
  end

  # POST /empresas
  # POST /empresas.json
  def create
    @empresa = current_user.empresas.build(empresa_params)
    respond_to do |format|
      if @empresa.save
        format.html { redirect_to @empresa, notice: 'Empresa criada com sucesso.' }
        format.json { render :show, status: :created, location: @empresa }
      else
        format.html { render :new }
        format.json { render json: @empresa.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /empresas/1
  # PATCH/PUT /empresas/1.json
  def update
    respond_to do |format|
      if @empresa.update(empresa_params)
        format.html { redirect_to @empresa, notice: 'Empresa alterada com sucesso.' }
        format.json { render :show, status: :ok, location: @empresa }
      else
        format.html { render :edit }
        format.json { render json: @empresa.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /empresas/1
  # DELETE /empresas/1.json
  def destroy
    @empresa.destroy
    respond_to do |format|
      format.html { redirect_to empresas_url, notice: 'Empresa removida com sucesso.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_empresa
      @empresa = current_user.empresas.find_by(id: params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def empresa_params
      params.require(:empresa).permit(:nome_fantasia, :email, :razao_soc, :cnpj)
    end

    def correct_user
      @empresa = current_user.empresas.find_by(id: params[:id])
      redirect_to empresas_url if @empresa.nil?
    end

end

Empresas_controller test

require 'test_helper'

class EmpresasControllerTest < ActionController::TestCase
  setup do
    @user = users(:carlos)
    @empresa = empresas(:one)
    @empresa.user_id = @user.id
  end

  test "should get index" do
    log_in_as(users(:carlos))
    get :index
    assert_response :success
    assert_not_nil assigns(:empresas)
  end

  test "should get new" do
    get :new
    assert_response :success
  end

  test "should create empresa" do
    log_in_as(users(:carlos))
    assert_difference('Empresa.count') do
      post :create, empresa: {email: @empresa.email, nome_fantasia: @empresa.nome_fantasia, cnpj: @empresa.cnpj, razao_soc: @empresa.razao_soc }
    end

    assert_redirected_to empresa_path(assigns(:empresa))
  end

  test "should show empresa" do
    log_in_as(users(:carlos))
    get :show, id: @empresa
    assert_response :success
  end

  test "should get edit" do
    log_in_as(users(:carlos))
    get :edit, id: @empresa
    assert_response :success
  end

  test "should update empresa" do
    log_in_as(users(:carlos))
    patch :update, id: @empresa, empresa: {email: @empresa.email, nome_fantasia: @empresa.nome_fantasia, cnpj: @empresa.cnpj, razao_soc: @empresa.razao_soc }
    assert_redirected_to empresa_path(assigns(:empresa))
  end

  test "should destroy empresa" do
    log_in_as(users(:carlos))
    assert_difference('Empresa.count', -1) do
      delete :destroy, id: @empresa
    end

    assert_redirected_to empresas_path
  end


end

The erros msgs

FAIL["test_should_destroy_empresa", EmpresasControllerTest, 2015-11-13 11:07:25 +0000]
 test_should_destroy_empresa#EmpresasControllerTest (1447412845.23s)
        "Empresa.count" didn't change by -1.
        Expected: 2
          Actual: 3
        test/controllers/empresas_controller_test.rb:51:in `block in <class:EmpresasControllerTest>'

ERROR["test_should_get_edit", EmpresasControllerTest, 2015-11-13 11:07:25 +0000]
 test_should_get_edit#EmpresasControllerTest (1447412845.33s)
ActionView::Template::Error:         ActionView::Template::Error: First argument in form cannot contain nil or be empty
            app/views/empresas/_form.html.erb:1:in `_app_views_empresas__form_html_erb___3156194878750235915_67173720'
            app/views/empresas/edit.html.erb:4:in `_app_views_empresas_edit_html_erb___622806155688133729_66667680'
            test/controllers/empresas_controller_test.rb:39:in `block in <class:EmpresasControllerTest>'
        app/views/empresas/_form.html.erb:1:in `_app_views_empresas__form_html_erb___3156194878750235915_67173720'
        app/views/empresas/edit.html.erb:4:in `_app_views_empresas_edit_html_erb___622806155688133729_66667680'
        test/controllers/empresas_controller_test.rb:39:in `block in <class:EmpresasControllerTest>'

 FAIL["test_should_show_empresa", EmpresasControllerTest, 2015-11-13 11:07:25 +0000]
 test_should_show_empresa#EmpresasControllerTest (1447412845.35s)
        Expected response to be a <success>, but was <302>
        test/controllers/empresas_controller_test.rb:34:in `block in <class:EmpresasControllerTest>'

ERROR["test_should_update_empresa", EmpresasControllerTest, 2015-11-13 11:07:25 +0000]
 test_should_update_empresa#EmpresasControllerTest (1447412845.36s)
ActionController::UrlGenerationError:         ActionController::UrlGenerationError: No route matches {:action=>"show", :controller=>"empresas", :id=>nil} missing required keys: [:id]
            test/controllers/empresas_controller_test.rb:46:in `block in <class:EmpresasControllerTest>'
        test/controllers/empresas_controller_test.rb:46:in `block in <class:EmpresasControllerTest>'

  61/61: [==================================================================================================================] 100% Time: 00:00:02, Time: 00:00:02

Finished in 2.21698s
61 tests, 166 assertions, 2 failures, 2 errors, 0 skips

Everything are working, but i realy want to learn tests

Microsoft Excel cannot open or save any more documents on Unit Test

There are a lot of posts about this, but with asp.net, I have checked them, but I couldn't find anything that worked for me.

There is a test in our application that access an excel file, like this:

Excel.Application _excelApp = new Excel.Application { Visible = false };

// get a new workbook
_workbook = _excelApp.Workbooks.Add(Missing.Value);

And it fails with the following error at the line where tries to add a new Workbook:

Test method MyNamespace.MyTestMethod threw exception: System.Runtime.InteropServices.COMException: Microsoft Excel cannot open or save any more documents because there is not enough available memory or disk space.

• To make more memory available, close workbooks or programs you no longer need.

• To free disk space, delete files you no longer need from the disk you are saving to.

This error makes no sense since the disk has plenty of space. Our build "server" is running Windows 7, TFS launches the builds through the Network Service User. Every other test works perfectly, we are just having issues with the ones trying to use excel.

I think this is an issue of access rights, but what access could the NetworkService user be missing to make this work?

Defect clustering example? [on hold]

I'm interested in testing and bugs history. I wanted to know if there were any historical example of "defect clustering", n°4 principle of testing (ISTQB).

Definition here: http://ift.tt/1QPRjnW

Thanks in advance!

Python 2.7 - Mutation Testing Tool suggestions

I have a system, whose modules are written in Python 2.7 and I'm given the task of proceeding with a mutation testing of some of the modules. I've done my research on the topic and now I'm getting on the tools. As long as I read, MutPy is considered to be the best (so far) developed tool for this kind of testing. The problem is, though, it is suitable for testing in Python 3.* versions.

Could somebody please help me with ideas for other tools for Python 2.7?

I was also thinking of converting the modules I need from 2.7 to 3.*, but I'm unsure if the system will somehow misbehave.

Any help will be appreciated, thank you.

Point of sale EMV performance testing

I am working on a POC to test a Point of sale application that used EMV concept - Chip & PIN credit cards.

Has any performance tested this in the past? If so, how is it possible to simulate the card swipe during performance testing. In EMV, each card swipe will create a unique data and it can't be re-used for multiple transactions.

Thanks Anna

Mockito.doNothing() is still running

I'm trying to test small pieces of code. I do not want test one of the method and used Mockito.doNothing(), but this method was still run. How can I do that?

 protected EncoderClientCommandEventHandler clientCommandEventHandlerProcessStop = new EncoderClientCommand.EncoderClientCommandEventHandler() {
    @Override
    public void onCommandPerformed(
        EncoderClientCommand clientCommand) {
      setWatcherActivated(false);
      buttonsBackToNormal();
    }
  };

  protected void processStop() {
    EncoderServerCommand serverCommand = new EncoderServerCommand();
    serverCommand.setAction(EncoderAction.STOP);

    checkAndSetExtension();
    serverCommand.setKey(getArchiveJobKey());
    getCommandFacade().performCommand(
        serverCommand,
        EncoderClientCommand.getType(),
        clientCommandEventHandlerProcessStop);
  }

  @Test
  public void testClientCommandEventHandlerProcessStop() {
    EncoderClientCommand encoderClientCommand = mock(EncoderClientCommand.class);

    Mockito.doNothing().when(encoderCompositeSpy).buttonsBackToNormal();

    when(encoderCompositeSpy.isWatcherActivated()).thenReturn(false);
    encoderCompositeSpy.clientCommandEventHandlerProcessStop.onCommandPerformed(encoderClientCommand);

Rails Minitest for rescue_from InvalidAuthenticityToken in ApplicationController

Hey I am currently using the minitest framework that is built into rails. Trying to test some methods in my ApplicationController around protect_from_forgery and recovering from InvalidAuthenticityToken exceptions. For reference my ApplicationController looks like:

  class ApplicationController < ActionController::Base

      # Prevent CSRF attacks by raising an exception.
      # For APIs, you may want to use :null_session instead.
      protect_from_forgery with: :exception

      rescue_from ActionController::InvalidAuthenticityToken, with: :handle_invalid_token

     def access_denied(exception)
       redirect_to root_path, :alert => exception.message
     end

      protected

        def handle_invalid_token
          flash[:alert] = I18n.translate('devise.failure.invalid_token')
          redirect_to new_user_session_path
        end
   end

I am looking for away to test both the rescue_from ActionController::InvalidAuthenticityToken and the protect_from_forgery with: :exception methods. Is it possible to mock some of these things up with minitest, forgive me for my experience is limited to just basic model/controller/view testing.

Not much here but figured i would include the class for my ApplicationControllerTest

require 'test_helper'

class ApplicationControllerTest < ActionController::TestCase

  test 'invalid access token' do

  end

end

./manage.py test results in django.db.utils.OperationalError: no such column: MyNewColumn

Long story short: I made tests.py to cover my django code, I modified code and models a lot (18 migrations) and everything was OK.

But after last change and migration (Added some Boolean fileds) my tests start crashing on 8. migration with django.db.utils.OperationalError: no such column: The_new_column

In Apache on web site I can use the new column, add models with it and everything looks nice, but tests fails

Can somebody please tell me, what went wrong and how to correct it?


The long story:

Models.py:

def Ticket_generateUniqueID(related=''):
    retval=''
    sanitized=''
......
    # --- now find unique value
    while True:
            passNo += 1
            retval = generateID()
            try:
                    t = Ticket.objects.get(ticket_number=retval)
                    pass
            except ObjectDoesNotExist:
                    return retval
....
class Ticket(models.Model):
....
    ticket_number = models.CharField(max_length=100,default=Ticket_generateUniqueID,help_text=u"ID of ticket")
    ActionRequired = models.BooleanField(default=False,help_text=u"Action Required")
    def save(self):  # {{{
        if not self.id and not self.ticket_number: self.ticket_number=Ticket_generateUniqueID('OTH')
        retval=super(Ticket,self).save()
        return retval

and my testing session (should start with no test_* database)

$ ./manage.py test -v3
settings ...
Creating test database for alias 'default' (':memory:')...
Operations to perform:
  Synchronize unmigrated apps: django_extensions
  Apply all migrations: admin, tickets, contenttypes, auth, sessions
Synchronizing apps without migrations:
Running pre-migrate handlers for application admin
Running pre-migrate handlers for application auth
Running pre-migrate handlers for application contenttypes
Running pre-migrate handlers for application sessions
Running pre-migrate handlers for application django_extensions
Running pre-migrate handlers for application tickets
  Creating tables...
  Installing custom SQL...
  Installing indexes...
Loading 'initial_data' fixtures...
Checking '/home/gilhad/GIT/kompitech_test/src/kompitech_test' for fixtures...
No fixture 'initial_data' in '/home/gilhad/GIT/kompitech_test/src/kompitech_test'.
Installed 0 object(s) from 0 fixture(s)
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying sessions.0001_initial... OK
  Applying tickets.0001_initial... OK
  Applying tickets.0002_importedemail_is_new... OK
  Applying tickets.0003_auto_20151102_1642... OK
  Applying tickets.0004_auto_20151116_1633... OK
  Applying tickets.0005_auto_20151118_0756... OK
  Applying tickets.0006_emailpart_originalfilename... OK
  Applying tickets.0007_ticket_fv_ticket_id... OK
  Applying tickets.0008_auto_20151123_1430...Traceback (most recent call last):
  File "./manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/usr/lib/python2.7/dist-packages/django/core/management/__init__.py", line 385, in execute_from_command_line
    utility.execute()
  File "/usr/lib/python2.7/dist-packages/django/core/management/__init__.py", line 377, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/usr/lib/python2.7/dist-packages/django/core/management/commands/test.py", line 50, in run_from_argv
    super(Command, self).run_from_argv(argv)
  File "/usr/lib/python2.7/dist-packages/django/core/management/base.py", line 288, in run_from_argv
    self.execute(*args, **options.__dict__)
  File "/usr/lib/python2.7/dist-packages/django/core/management/commands/test.py", line 71, in execute
    super(Command, self).execute(*args, **options)
  File "/usr/lib/python2.7/dist-packages/django/core/management/base.py", line 338, in execute
    output = self.handle(*args, **options)
  File "/usr/lib/python2.7/dist-packages/django/core/management/commands/test.py", line 88, in handle
    failures = test_runner.run_tests(test_labels)
  File "/usr/lib/python2.7/dist-packages/django/test/runner.py", line 147, in run_tests
    old_config = self.setup_databases()
  File "/usr/lib/python2.7/dist-packages/django/test/runner.py", line 109, in setup_databases
    return setup_databases(self.verbosity, self.interactive, **kwargs)
  File "/usr/lib/python2.7/dist-packages/django/test/runner.py", line 299, in setup_databases
    serialize=connection.settings_dict.get("TEST", {}).get("SERIALIZE", True),
  File "/usr/lib/python2.7/dist-packages/django/db/backends/creation.py", line 377, in create_test_db
    test_flush=True,
  File "/usr/lib/python2.7/dist-packages/django/core/management/__init__.py", line 115, in call_command
    return klass.execute(*args, **defaults)
  File "/usr/lib/python2.7/dist-packages/django/core/management/base.py", line 338, in execute
    output = self.handle(*args, **options)
  File "/usr/lib/python2.7/dist-packages/django/core/management/commands/migrate.py", line 161, in handle
    executor.migrate(targets, plan, fake=options.get("fake", False))
  File "/usr/lib/python2.7/dist-packages/django/db/migrations/executor.py", line 68, in migrate
    self.apply_migration(migration, fake=fake)
  File "/usr/lib/python2.7/dist-packages/django/db/migrations/executor.py", line 102, in apply_migration
    migration.apply(project_state, schema_editor)
  File "/usr/lib/python2.7/dist-packages/django/db/migrations/migration.py", line 108, in apply
    operation.database_forwards(self.app_label, schema_editor, project_state, new_state)
  File "/usr/lib/python2.7/dist-packages/django/db/migrations/operations/fields.py", line 139, in database_forwards
    schema_editor.alter_field(from_model, from_field, to_field)
  File "/usr/lib/python2.7/dist-packages/django/db/backends/schema.py", line 457, in alter_field
    self._alter_field(model, old_field, new_field, old_type, new_type, old_db_params, new_db_params, strict)
  File "/usr/lib/python2.7/dist-packages/django/db/backends/sqlite3/schema.py", line 202, in _alter_field
    self._remake_table(model, alter_fields=[(old_field, new_field)])
  File "/usr/lib/python2.7/dist-packages/django/db/backends/sqlite3/schema.py", line 139, in _remake_table
    self.create_model(temp_model)
  File "/usr/lib/python2.7/dist-packages/django/db/backends/schema.py", line 213, in create_model
    definition, extra_params = self.column_sql(model, field)
  File "/usr/lib/python2.7/dist-packages/django/db/backends/schema.py", line 125, in column_sql
    default_value = self.effective_default(field)
  File "/usr/lib/python2.7/dist-packages/django/db/backends/schema.py", line 175, in effective_default
    default = field.get_default()
  File "/usr/lib/python2.7/dist-packages/django/db/models/fields/__init__.py", line 719, in get_default
    return self.default()
  File "/home/gilhad/GIT/kompitech_test/src/kompitech_test/tickets/models.py", line 56, in Ticket_generateUniqueID
    t = Ticket.objects.get(ticket_number=retval)
  File "/usr/lib/python2.7/dist-packages/django/db/models/manager.py", line 92, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/usr/lib/python2.7/dist-packages/django/db/models/query.py", line 351, in get
    num = len(clone)
  File "/usr/lib/python2.7/dist-packages/django/db/models/query.py", line 122, in __len__
    self._fetch_all()
  File "/usr/lib/python2.7/dist-packages/django/db/models/query.py", line 966, in _fetch_all
    self._result_cache = list(self.iterator())
  File "/usr/lib/python2.7/dist-packages/django/db/models/query.py", line 265, in iterator
    for row in compiler.results_iter():
  File "/usr/lib/python2.7/dist-packages/django/db/models/sql/compiler.py", line 700, in results_iter
    for rows in self.execute_sql(MULTI):
  File "/usr/lib/python2.7/dist-packages/django/db/models/sql/compiler.py", line 786, in execute_sql
    cursor.execute(sql, params)
  File "/usr/lib/python2.7/dist-packages/django/db/backends/utils.py", line 65, in execute
    return self.cursor.execute(sql, params)
  File "/usr/lib/python2.7/dist-packages/django/db/utils.py", line 94, in __exit__
    six.reraise(dj_exc_type, dj_exc_value, traceback)
  File "/usr/lib/python2.7/dist-packages/django/db/backends/utils.py", line 65, in execute
    return self.cursor.execute(sql, params)
  File "/usr/lib/python2.7/dist-packages/django/db/backends/sqlite3/base.py", line 485, in execute
    return Database.Cursor.execute(self, query, params)
django.db.utils.OperationalError: no such column: tickets_ticket.ActionRequired

see, that it is not nearly the last migration and tests went as expexted before everytime

$ ls -1 tickets/migrations/*py
tickets/migrations/0001_initial.py
tickets/migrations/0002_importedemail_is_new.py
tickets/migrations/0003_auto_20151102_1642.py
tickets/migrations/0004_auto_20151116_1633.py
tickets/migrations/0005_auto_20151118_0756.py
tickets/migrations/0006_emailpart_originalfilename.py
tickets/migrations/0007_ticket_fv_ticket_id.py
tickets/migrations/0008_auto_20151123_1430.py
tickets/migrations/0009_auto_20151123_1718.py
tickets/migrations/0010_auto_20151123_1928.py
tickets/migrations/0011_auto_20151124_0938.py
tickets/migrations/0012_auto_20151125_1351.py
tickets/migrations/0013_auto_20151125_1406.py
tickets/migrations/0014_configemailcompany.py
tickets/migrations/0015_auto_20151126_1435.py
tickets/migrations/0016_configemailcompany_we.py
tickets/migrations/0017_auto_20151126_1730.py
tickets/migrations/0018_auto_20151127_1103.py
tickets/migrations/0019_auto_20151130_0934.py
tickets/migrations/__init__.py

Does it cost for licencing of Mantis bug tracker?

I have recently deployed Mantis Bug tracker on a standalone webserver for trial. The experience has been great and now I want to deploy it on a broader aspect meaning, it will be used bys several users located in several countries. My question is, does it cost for the licencing of Mantis bug tracker? If, yes then how to go about it?

Appium GUI (Windows) Doesn't Launch

Hello and greetings everyone,

When I 'run' Appium, Appium appears in Task Manager Background and then it disappears. Appium GUI cannot be opened on computer anymore. I was working on automated mobile test last week with Appium and Python/Java. Everything was working well. But today I cannot use Appium, so I cannot run my tests.

What should I do? I re-installed Appium. Windows is full updated and .NET is already installed.

Thank you in advanced.

Is there a way to improve Selenium Builder performances, for example with plugins?

I'm trying Selenium Builder and I'm having a hard time trying to improve its performances and features because I'm not satisfied with its usability. I'm used to Selenium IDE and there are many plugins to improve it (ex: "Stored Variables", "Highlight Elements"...) Have you tried or heard about ways to improve the plain Selenium Builder? Thank you in advance.

Using slow network emulation in VS2015

I'm trying to run my entire application and test it with a slow network connection. I've read a number of MS articles about setting up a .testsettings file, but its not clear on how to actually use it when I run the client.

Can anyone clarify this for me?

NUnit 3 with generics

I saw this post here NUnit: Parametric test with generic methods for NUnit 2.5:

[TestCase((int)5, "5")]
[TestCase((double)2.3, "2.3")]
public void TestRowTestGeneric<T>(T value, string msg)
{
   Assert.AreEqual(value, ConvertStrToGenericParameter<T>(msg));
}

But looks it's not working anymore for NUnit 3.0?

What would be the right way for this scenario?

[Test]
[TestCase(0)]
[TestCase(FakeEnum.DefaultValue)]
public void should_expect_T_value<T>(T expectedValue)
{
   var result = DoStuff<T>();
   Assert.AreEqual(expectedValue, result);
}

Thanks

org.gradle.api.internal.tasks.testing.TestSuiteExecutionException: Could not start process 'Gradle Test Executor 1'

When running some Unit Tests in gradle I get this output:

org.gradle.api.internal.tasks.testing.TestSuiteExecutionException: Could not start process 'Gradle Test Executor 1'.
    at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.startProcessing(SuiteTestClassProcessor.java:41)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
    at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.messaging.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:32)
    at org.gradle.messaging.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:93)
    at com.sun.proxy.$Proxy2.startProcessing(Unknown Source)
    at org.gradle.api.internal.tasks.testing.worker.TestWorker.startProcessing(TestWorker.java:99)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
    at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.messaging.remote.internal.hub.MessageHub$Handler.run(MessageHub.java:360)
    at org.gradle.internal.concurrent.DefaultExecutorFactory$StoppableExecutorImpl$1.run(DefaultExecutorFactory.java:64)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.AssertionError
    at org.gradle.api.internal.tasks.testing.junit.JUnitTestEventAdapter.<init>(JUnitTestEventAdapter.java:45)
    at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassProcessor.startProcessing(JUnitTestClassProcessor.java:63)
    at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.startProcessing(SuiteTestClassProcessor.java:39)
    ... 21 more

org.gradle.api.internal.tasks.testing.TestSuiteExecutionException: Could not execute test class 'com.ullink.slack.simpleslackapi.impl.TestSlackJSONMessageParser'.
    at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.processTestClass(SuiteTestClassProcessor.java:50)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
    at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.messaging.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:32)
    at org.gradle.messaging.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:93)
    at com.sun.proxy.$Proxy2.processTestClass(Unknown Source)
    at org.gradle.api.internal.tasks.testing.worker.TestWorker.processTestClass(TestWorker.java:105)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
    at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.messaging.remote.internal.hub.MessageHub$Handler.run(MessageHub.java:360)
    at org.gradle.internal.concurrent.DefaultExecutorFactory$StoppableExecutorImpl$1.run(DefaultExecutorFactory.java:64)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.NullPointerException
    at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassProcessor.processTestClass(JUnitTestClassProcessor.java:69)
    at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.processTestClass(SuiteTestClassProcessor.java:48)
    ... 21 more

org.gradle.api.internal.tasks.testing.TestSuiteExecutionException: Could not execute test class 'com.ullink.slack.simpleslackapi.impl.TestSlackJSONSessionStatusParser'.
    at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.processTestClass(SuiteTestClassProcessor.java:50)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
    at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.messaging.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:32)
    at org.gradle.messaging.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:93)
    at com.sun.proxy.$Proxy2.processTestClass(Unknown Source)
    at org.gradle.api.internal.tasks.testing.worker.TestWorker.processTestClass(TestWorker.java:105)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
    at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.messaging.remote.internal.hub.MessageHub$Handler.run(MessageHub.java:360)
    at org.gradle.internal.concurrent.DefaultExecutorFactory$StoppableExecutorImpl$1.run(DefaultExecutorFactory.java:64)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.NullPointerException
    at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassProcessor.processTestClass(JUnitTestClassProcessor.java:69)
    at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.processTestClass(SuiteTestClassProcessor.java:48)
    ... 21 more

org.gradle.api.internal.tasks.testing.TestSuiteExecutionException: Could not execute test class 'com.ullink.slack.simpleslackapi.impl.TestAbstractSlackSessionImpl'.
    at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.processTestClass(SuiteTestClassProcessor.java:50)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
    at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.messaging.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:32)
    at org.gradle.messaging.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:93)
    at com.sun.proxy.$Proxy2.processTestClass(Unknown Source)
    at org.gradle.api.internal.tasks.testing.worker.TestWorker.processTestClass(TestWorker.java:105)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
    at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.messaging.remote.internal.hub.MessageHub$Handler.run(MessageHub.java:360)
    at org.gradle.internal.concurrent.DefaultExecutorFactory$StoppableExecutorImpl$1.run(DefaultExecutorFactory.java:64)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.NullPointerException
    at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassProcessor.processTestClass(JUnitTestClassProcessor.java:69)
    at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.processTestClass(SuiteTestClassProcessor.java:48)
    ... 21 more

I cannot even get the exceptions to be fully shown. I tried

test {   
    testLogging {        
        exceptionFormat = 'full'  
        showStackTraces = "true"
    }   
}

in the gradle.build but that didn't change anything. Any recommendations? Sorry if I missed posts already covering this, I searched here as well as Google but found nothing which pointed me into a direction I could work with.

Testing Lavavel Event Listener

I'm trying to test Event Listener in Laravel. This is my listener:

class FlashNotifier
{

    public function handleMenuItemWasStored()
    {
        Session::flash('flash-status', 'success');
        Session::flash('flash-message', 'Item was stored.');
    }

    public function subscribe($events)
    {
        $events->listen(
            MenuItemWasStored::class,
            '\App\Listeners\Menu\FlashNotifier@handleMenuItemWasStored'
        );
    }
}

And this is the test I came up so far:

public function testEventListenerWasTriggered()
{
    $listener = Mockery::mock('App\Listeners\Menu\FlashNotifier');
    $d = new Dispatcher;
    $listener->shouldReceive('handleMenuItemWasStored')->once();
    $d->fire('App\Events\Menu\MenuItemWasStored');
}

However, I get the following exception:

Mockery\Exception\InvalidCountException: Method     handleMenuItemWasStored() 
from Mockery_1_App_Listeners_Menu_FlashNotifier 
should be called  exactly 1 times but called 0 times.

What am I doing wrong?

MongoDB Server: Simulate Latency for test

I've set up a mongo replica set for testing purposes however I want to slow the speed of one of them right down to simulate a disk error that occurred the other day. Is there a way to force a mongo server to run slow? Any ideas welcome

Phaser game test

I am currently developing a javascript game with the Phaser Framework. I would like to perform unit tests on my game. In order to test this game I need to simulate the creation of a state Phaser.Game. Would you ways to help me in my approach? Thank you in advance !

dimanche 29 novembre 2015

Retrofit Gson APi test for android

I am new to testing environment. For my project I am using retrofit with gson for api call. I want to create a test for the request received whether the response is valid pojo or not and what type of response is obtained. Can you suggest any testing framework or method for a beginner?

Can i test iphone application using selenium webdriver?

I am working with selenium webdriver and performed automation for Web application and Android Application. Can Anyone tell how can i test Iphone Application using Selenium Webdriver ?? Are there any specific jars for that ??

Please share any link for automating iphone application!!

Run simple test and output error on console

I'm running a simple equality test in my code, and if the two values don't match, I want R to print a statement in the console such as

WARNING: Value A does not equal Value B.

Is this possible?

How do you use ShouldThrow

I feel like it should be

Should.Throw<ArgumentNullException>(module.Execute(badArgument));

But when I try that there's no Throw method on the Should class or namespace.

There is however a couple methods, but when I call ShouldThrow

Should.ActionAssertionExtensions
    .ShouldThrow<ArgumentNullException>(() => module.Execute(badArgument));

it says it is an ambiguous call because there are two ShouldThrow method signatures

void ShouldThrow<TException>(this Should.Core.Assertions.Assert.ThrowsDelegate)    
void ShouldThrow<TException>(this System.Action)

Junit test on dependent method

I am trying to test the return value of updateGame method of below code.

package org.psnbtech;

import java.awt.BorderLayout;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.Random;

import javax.swing.JFrame;

/**
 * The {@code Tetris} class is responsible for handling much of the game logic and
 * reading user input.
 * @author Brendan Jones
 *
 */
public class Tetris extends JFrame {

    /**
     * The Serial Version UID.
     */
    private static final long serialVersionUID = -4722429764792514382L;

    /**
     * The number of milliseconds per frame.
     */
    private static final long FRAME_TIME = 1000L / 50L;

    /**
     * The number of pieces that exist.
     */
    private static final int TYPE_COUNT = TileType.values().length;

    /**
     * The BoardPanel instance.
     */
    private BoardPanel board;

    /**
     * The SidePanel instance.
     */
    private SidePanel side;

    /**
     * Whether or not the game is paused.
     */
    private boolean isPaused;

    /**
     * Whether or not we've played a game yet. This is set to true
     * initially and then set to false when the game starts.
     */
    private boolean isNewGame;

    /**
     * Whether or not the game is over.
     */
    private boolean isGameOver;

    /**
     * The current level we're on.
     */
    private int level;

    /**
     * The current score.
     */
    private int score;

    /**
     * The random number generator. This is used to
     * spit out pieces randomly.
     */
    private Random random;

    /**
     * The clock that handles the update logic.
     */
    private Clock logicTimer;

    /**
     * The current type of tile.
     */
    private TileType currentType;

    /**
     * The next type of tile.
     */
    private TileType nextType;

    /**
     * The current column of our tile.
     */
    private int currentCol;

    /**
     * The current row of our tile.
     */
    private int currentRow;

    /**
     * The current rotation of our tile.
     */
    private int currentRotation;

    /**
     * Ensures that a certain amount of time passes after a piece is
     * spawned before we can drop it.
     */
    private int dropCooldown;

    /**
     * The speed of the game.
     */
    private float gameSpeed;

    /**
     * Creates a new Tetris instance. Sets up the window's properties,
     * and adds a controller listener.
     */
    public Tetris() {
        /*
         * Set the basic properties of the window.
         */
        super("Tetris");
        setLayout(new BorderLayout());
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setResizable(false);

        /*
         * Initialize the BoardPanel and SidePanel instances.
         */
        this.board = new BoardPanel(this);
        this.side = new SidePanel(this);

        /*
         * Add the BoardPanel and SidePanel instances to the window.
         */
        add(board, BorderLayout.CENTER);
        add(side, BorderLayout.EAST);

        /*
         * Adds a custom anonymous KeyListener to the frame.
         */
        addKeyListener(new KeyAdapter() {

            @Override
            public void keyPressed(KeyEvent e) {

                switch(e.getKeyCode()) {

                /*
                 * Drop - When pressed, we check to see that the game is not
                 * paused and that there is no drop cooldown, then set the
                 * logic timer to run at a speed of 25 cycles per second.
                 */
                case KeyEvent.VK_S:
                    if(!isPaused && dropCooldown == 0) {
                        logicTimer.setCyclesPerSecond(25.0f);
                    }
                    break;

                /*
                 * Move Left - When pressed, we check to see that the game is
                 * not paused and that the position to the left of the current
                 * position is valid. If so, we decrement the current column by 1.
                 */
                case KeyEvent.VK_A:
                    if(!isPaused && board.isValidAndEmpty(currentType, currentCol - 1, currentRow, currentRotation)) {
                        currentCol--;
                    }
                    break;

                /*
                 * Move Right - When pressed, we check to see that the game is
                 * not paused and that the position to the right of the current
                 * position is valid. If so, we increment the current column by 1.
                 */
                case KeyEvent.VK_D:
                    if(!isPaused && board.isValidAndEmpty(currentType, currentCol + 1, currentRow, currentRotation)) {
                        currentCol++;
                    }
                    break;

                /*
                 * Rotate Anticlockwise - When pressed, check to see that the game is not paused
                 * and then attempt to rotate the piece anticlockwise. Because of the size and
                 * complexity of the rotation code, as well as it's similarity to clockwise
                 * rotation, the code for rotating the piece is handled in another method.
                 */
                case KeyEvent.VK_Q:
                    if(!isPaused) {
                        rotatePiece((currentRotation == 0) ? 3 : currentRotation - 1);
                    }
                    break;

                /*
                 * Rotate Clockwise - When pressed, check to see that the game is not paused
                 * and then attempt to rotate the piece clockwise. Because of the size and
                 * complexity of the rotation code, as well as it's similarity to anticlockwise
                 * rotation, the code for rotating the piece is handled in another method.
                 */
                case KeyEvent.VK_E:
                    if(!isPaused) {
                        rotatePiece((currentRotation == 3) ? 0 : currentRotation + 1);
                    }
                    break;

                /*
                 * Pause Game - When pressed, check to see that we're currently playing a game.
                 * If so, toggle the pause variable and update the logic timer to reflect this
                 * change, otherwise the game will execute a huge number of updates and essentially
                 * cause an instant game over when we unpause if we stay paused for more than a
                 * minute or so.
                 */
                case KeyEvent.VK_P:
                    if(!isGameOver && !isNewGame) {
                        isPaused = !isPaused;
                        logicTimer.setPaused(isPaused);
                    }
                    break;

                /*
                 * Start Game - When pressed, check to see that we're in either a game over or new
                 * game state. If so, reset the game.
                 */
                case KeyEvent.VK_ENTER:
//                  if(isGameOver || isNewGame) {
                    if(isNewGame) {
                        resetGame();
                    }
                    if(isGameOver){
                        System.exit(0);
                    }
                    break;

                }
            }

            @Override
            public void keyReleased(KeyEvent e) {

                switch(e.getKeyCode()) {

                /*
                 * Drop - When released, we set the speed of the logic timer
                 * back to whatever the current game speed is and clear out
                 * any cycles that might still be elapsed.
                 */
                case KeyEvent.VK_S:
                    logicTimer.setCyclesPerSecond(gameSpeed);
                    logicTimer.reset();
                    break;
                }

            }

        });

        /*
         * Here we resize the frame to hold the BoardPanel and SidePanel instances,
         * center the window on the screen, and show it to the user.
         */
        pack();
        setLocationRelativeTo(null);
        setVisible(true);
    }

    /**
     * Starts the game running. Initializes everything and enters the game loop.
     */
    public void startGame() {
        /*
         * Initialize our random number generator, logic timer, and new game variables.
         */
        this.random = new Random();
        this.isNewGame = true;
        this.gameSpeed = 1.0f;

        /*
         * Setup the timer to keep the game from running before the user presses enter
         * to start it.
         */
        this.logicTimer = new Clock(gameSpeed);
        logicTimer.setPaused(true);

        while(true) {
            //Get the time that the frame started.
            long start = System.nanoTime();

            //Update the logic timer.
            logicTimer.update();

            /*
             * If a cycle has elapsed on the timer, we can update the game and
             * move our current piece down.
             */
            if(logicTimer.hasElapsedCycle()) {
                updateGame();
            }

            //Decrement the drop cool down if necessary.
            if(dropCooldown > 0) {
                dropCooldown--;
            }

            //Display the window to the user.
            renderGame();

            /*
             * Sleep to cap the framerate.
             */
            long delta = (System.nanoTime() - start) / 1000000L;
            if(delta < FRAME_TIME) {
                try {
                    Thread.sleep(FRAME_TIME - delta);
                } catch(Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * Updates the game and handles the bulk of it's logic.
     */
    public int updateGame() {
        /*
         * Check to see if the piece's position can move down to the next row.
         */
        if(board.isValidAndEmpty(currentType, currentCol, currentRow + 1, currentRotation)) {
            //Increment the current row if it's safe to do so.
            currentRow++;
            return 0;
        } else {
            /*
             * We've either reached the bottom of the board, or landed on another piece, so
             * we need to add the piece to the board.
             */
            board.addPiece(currentType, currentCol, currentRow, currentRotation);

            /*
             * Check to see if adding the new piece resulted in any cleared lines. If so,
             * increase the player's score. (Up to 4 lines can be cleared in a single go;
             * [1 = 100pts, 2 = 200pts, 3 = 400pts, 4 = 800pts]).
             */
            int cleared = board.checkLines();
            if(cleared > 0) {
                score += 50 << cleared;
            }

            /*
             * Increase the speed slightly for the next piece and update the game's timer
             * to reflect the increase.
             */
            gameSpeed = gameSpeed + 0.035f;
            logicTimer.setCyclesPerSecond(gameSpeed);
            logicTimer.reset();

            /*
             * Set the drop cooldown so the next piece doesn't automatically come flying
             * in from the heavens immediately after this piece hits if we've not reacted
             * yet. (~0.5 second buffer).
             */
            dropCooldown = 25;

            /*
             * Update the difficulty level. This has no effect on the game, and is only
             * used in the "Level" string in the SidePanel.
             */
            level = (int)(gameSpeed * 1.70f);

            /*
             * Spawn a new piece to control.
             */
            spawnPiece();
            return cleared;
        }   
    }

    /**
     * Forces the BoardPanel and SidePanel to repaint.
     */
    private void renderGame() {
        board.repaint();
        side.repaint();
    }

    /**
     * Resets the game variables to their default values at the start
     * of a new game.
     */
    private void resetGame() {
        this.level = 1;
        this.score = 0;
        this.gameSpeed = 1.0f;
        this.nextType = TileType.values()[random.nextInt(TYPE_COUNT)];
        this.isNewGame = false;
        this.isGameOver = false;        
        board.clear();
        logicTimer.reset();
        logicTimer.setCyclesPerSecond(gameSpeed);
        spawnPiece();
    }

    /**
     * Spawns a new piece and resets our piece's variables to their default
     * values.
     */
    private void spawnPiece() {
        /*
         * Poll the last piece and reset our position and rotation to
         * their default variables, then pick the next piece to use.
         */
        this.currentType = nextType;
        this.currentCol = currentType.getSpawnColumn();
        this.currentRow = currentType.getSpawnRow();
        this.currentRotation = 0;
        this.nextType = TileType.values()[random.nextInt(TYPE_COUNT)];

        /*
         * If the spawn point is invalid, we need to pause the game and flag that we've lost
         * because it means that the pieces on the board have gotten too high.
         */
        if(!board.isValidAndEmpty(currentType, currentCol, currentRow, currentRotation)) {
            this.isGameOver = true;
            logicTimer.setPaused(true);
        }       
    }

    /**
     * Attempts to set the rotation of the current piece to newRotation.
     * @param newRotation The rotation of the new peice.
     */
    private void rotatePiece(int newRotation) {
        /*
         * Sometimes pieces will need to be moved when rotated to avoid clipping
         * out of the board (the I piece is a good example of this). Here we store
         * a temporary row and column in case we need to move the tile as well.
         */
        int newColumn = currentCol;
        int newRow = currentRow;

        /*
         * Get the insets for each of the sides. These are used to determine how
         * many empty rows or columns there are on a given side.
         */
        int left = currentType.getLeftInset(newRotation);
        int right = currentType.getRightInset(newRotation);
        int top = currentType.getTopInset(newRotation);
        int bottom = currentType.getBottomInset(newRotation);

        /*
         * If the current piece is too far to the left or right, move the piece away from the edges
         * so that the piece doesn't clip out of the map and automatically become invalid.
         */
        if(currentCol < -left) {
            newColumn -= currentCol - left;
        } else if(currentCol + currentType.getDimension() - right >= BoardPanel.COL_COUNT) {
            newColumn -= (currentCol + currentType.getDimension() - right) - BoardPanel.COL_COUNT + 1;
        }

        /*
         * If the current piece is too far to the top or bottom, move the piece away from the edges
         * so that the piece doesn't clip out of the map and automatically become invalid.
         */
        if(currentRow < -top) {
            newRow -= currentRow - top;
        } else if(currentRow + currentType.getDimension() - bottom >= BoardPanel.ROW_COUNT) {
            newRow -= (currentRow + currentType.getDimension() - bottom) - BoardPanel.ROW_COUNT + 1;
        }

        /*
         * Check to see if the new position is acceptable. If it is, update the rotation and
         * position of the piece.
         */
        if(board.isValidAndEmpty(currentType, newColumn, newRow, newRotation)) {
            currentRotation = newRotation;
            currentRow = newRow;
            currentCol = newColumn;
        }
    }

    /**
     * Checks to see whether or not the game is paused.
     * @return Whether or not the game is paused.
     */
    public boolean isPaused() {
        return isPaused;
    }

    /**
     * Checks to see whether or not the game is over.
     * @return Whether or not the game is over.
     */
    public boolean isGameOver() {
        return isGameOver;
    }

    /**
     * Checks to see whether or not we're on a new game.
     * @return Whether or not this is a new game.
     */
    public boolean isNewGame() {
        return isNewGame;
    }

    /**
     * Gets the current score.
     * @return The score.
     */
    public int getScore() {
        return score;
    }

    /**
     * Gets the current level.
     * @return The level.
     */
    public int getLevel() {
        return level;
    }

    /**
     * Gets the current type of piece we're using.
     * @return The piece type.
     */
    public TileType getPieceType() {
        return currentType;
    }

    /**
     * Gets the next type of piece we're using.
     * @return The next piece.
     */
    public TileType getNextPieceType() {
        return nextType;
    }

    /**
     * Gets the column of the current piece.
     * @return The column.
     */
    public int getPieceCol() {
        return currentCol;
    }

    /**
     * Gets the row of the current piece.
     * @return The row.
     */
    public int getPieceRow() {
        return currentRow;
    }

    /**
     * Gets the rotation of the current piece.
     * @return The rotation.
     */
    public int getPieceRotation() {
        return currentRotation;
    }

    /**
     * Entry-point of the game. Responsible for creating and starting a new
     * game instance.
     * @param args Unused.
     */
    /*public static void main(String[] args) {
        Tetris tetris = new Tetris();
        tetris.startGame();
    }*/

}

My JUnit test code is as below

import static org.junit.Assert.*;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.psnbtech.Tetris;

public class TetrisTest {

    private Tetris tetris;
    @Before
    public void setUp() throws Exception {
        tetris = new Tetris();
        tetris.startGame();
    }

    @After
    public void tearDown() throws Exception {
        tetris = null;
    }

    @Test
    public void testUpdateGame() {
        int i = tetris.updateGame();
        //At any time, the no. of rows cleared should be less than or equal to 4
        assertTrue(i<=4);
    }

}

When I run JUnit test case in Eclipse, I am not getting any results. Can someone please help me where the problem is?

enter image description here

Thanks

Automated end-to-end testing a Meteor app in multiple browsers with Karma or similar

I would like to end-to-end test my Meteor/React app in multiple browsers.

Karma is great for automating tests in multiple browsers, but I don't see any config options to make it load the page to test from my own server, only the option to specify which JS files contain tests and support code.

This is obviously because Karma injects its own test harness HTML and JS. But to end-to-end test my page, I would need it to load the page from Meteor instead of Karma's own embedded server, since Meteor injects a lot of its own JS dependencies into the page.

Bundling the tests into the code served up by Meteor is easy. The problem is how to tell Karma to load a specific URL, and to be able to put script tags or whatever to load and run the Karma test harness into my own HTML code.

I believe it may have been possible with the Velocity test runner for Meteor, but I found it horribly slow and wanted to implement end-to-end testing without it.

Does anyone know if this is possible with Karma or another framework?

I am looking for modules/approaches to QA or validate resulting configuration files in Python

I have a Python script which generates configuration files base on data + template files (not using any template modules - just template text files and variable substitution). Once those configuration files are applied I generate a final "log" (could be 100s in a "batch") and I need to "QA" them. In its simplest form I need to make sure that all the data from the templates exists in the resulting log file. A more sophisticated script would check for the template and look for specific things (this is generally a list of "issues" that changes periodically) that can be broken down to "does this string or regex exist or not?". The full QA effort would incorporate those two areas as well as specific validations based on the original input data. My original thought was to put the template in a list and look for each line but that seems cumbersome and does not address the last "test". Any pointers would be most appreciated!

Testing Play + Slick app

I've a simple CRUD app built with Scala Play 2.4.3 and Play-slick 1.1.0 (slick 3.1.0) that uses a MySQL database for persistent storage.

I was trying to create the tests for my app and I saw 2 main options:

  • mocking database access, that as far as I've seen, requires some code changes
  • make tests use an alternative database (probably, in memory H2).

What's the best approach (vantages and desavantages)?

I prefer the second approach, but I'm finding some difficulties in setting up the tests.

What do I need to do? First, I think that I need to do the tests run with a FakeApplication, right? Do I need any sbt dependency to be able to do that?

After that, how do I specify to use the H2 database?

Regular Expression Doesn not working properly

I am trying to increase security on Email/Password input fields using regular expressions but I am having bad time because I cannot find what I am doing wrong. So basically I'm creating 2 variables where I'm storing my Regex pattern and after that I want to use jquery to catch the submit button and when .on('click') if there is added correct information by users to redirect them to next page for example. I have been testing my regular expression and they are matching my requirements - they are returning true for Email/Password after testing with .test(). Here is my code example of what I am trying to build:

  var userValidation = /^[\w-]+@[\w-]+\.[A-Za-z_-]{2,4}$/;
  var passValidation = /((?=.*d)(?=.*[a-z])(?=.*[A-Z]).{8,15})/gm;
  console.log(userValidation.test('test@gmail.com')); // testing
  console.log(passValidation.test('12345678Kksad')); // testing

Actual code which I am trying to run

$('.button').on('click', function(){
        if ($('#user') === userValidation && $('#pass') === passValidation){
            window.location.replace("http://ift.tt/gbk8l4");
        }else{
            console.log('not working properly');
        }
    })

Every time when I enter email and password in both input fields it returning the else statement does not matter if the information is correct or not according my regular expressions.

Any suggestions ?

How to speed up Spark SQL unit tests?

I'm evaluating Spark SQL to implement a simple reporting module (few simple aggregations over Avro data already stored on HDFS). I have no doubt that Spark SQL could a good fit for both my functional and non-functional requirements.

However, on top of production requirements I want to make sure the module will be testable. We follow a BDD approach with very focused scenarios which means that this module will require to run tens / hundreds of SQL queries over some very simple data (1..10 records).

To get a rough idea of the performance I can expect from Spark SQL in local mode, I have quickly prototyped a few tests:

  1. select count(*) from myTable
  2. select key, count(*) from myTable group by key

The first test takes 100ms on average, but the second one takes 500ms. Such performance is unacceptable this it would make the test suite too slow.

For comparison, I can run the same test in 10ms using Crunch and its MemPipeline (1500ms with MRPipeline in local mode) and also 1500ms with Hive in embedded mode. Spark SQL is thus a bit faster than MR in local mode, but still way to slow to build good test suites.

Is it possible to speed up Spark SQL in local mode ?

Is there a better / faster way to test a Spark SQL module ?

(I have not profiled the execution yet but since a groupBy().countByKey() on a RDD takes 40ms on average I expect to find that the culprit is the query optimizer)


My quick & dirty test code follows:

  SparkConf sparkConf = new SparkConf()
                .setMaster("local[4]")
                .setAppName("poc-sparksql");

  try (JavaSparkContext ctx = new JavaSparkContext(sparkConf)) {
        SQLContext sqlCtx = new SQLContext(ctx);

        for (int i = 0; i < ITERATIONS; i++) {
            Stopwatch testCaseSw = new Stopwatch().start();

            DataFrame df = sqlCtx.load("/tmp/test.avro", "com.databricks.spark.avro");
            df.registerTempTable("myTable");
            DataFrame result = sqlCtx.sql("select count(*) from myTable");

            System.out.println("Results: " + result.collectAsList());
            System.out.println("Elapsed: " + testCaseSw.elapsedMillis());
        }

        for (int i = 0; i < ITERATIONS; i++) {
            Stopwatch testCaseSw = new Stopwatch().start();

            DataFrame df = sqlCtx.load("/tmp/test.avro", "com.databricks.spark.avro");
            df.registerTempTable("myTable");
            DataFrame result = sqlCtx.sql("select a, count(*) from myTable group by a ");

            System.out.println("Results: " + result.collectAsList());
            System.out.println("Elapsed: " + testCaseSw.elapsedMillis());
        }
 }

philosophy behind Unit::Test versus Rspec

I am interested in Test::Unit and Rspec.

Could someone explain me what it the main difference between the two - in terms of principles on which they operate.

Are there any specific advantages to use one over another?

samedi 28 novembre 2015

Disabling console logging with http.get

I have this code:

var should = require('should'),
  http = require('http'),
  apis = {
    baseUrl: 'http://11.0.0.20:4000',
    listLiveMatches: '/api/blah/'
  };
describe('GET ' + apis.baseUrl + apis.listLiveMatches, function () {
  'use strict';
  var liveListUrl = apis.baseUrl + apis.listLiveMatches;
  it('is alive & returning 200', function (done) {
    http.get(liveListUrl, function (res) {
      res.should.be.ok;
      res.should.have.property('statusCode');
      res.statusCode.should.equal(200);
      done();
    });
  });
  it('is emitting json response', function (done) {
    http.get(liveListUrl, function (res) {
      res.should.be.ok;
      res.should.have.property('headers');
      res.headers['content-type'].should.startWith('application/json');
      done();
    });
  });
});

My gulp task looks like this:

gulp.task('test-server', function () {

  return gulp.src('test/rest-api.js')
    .pipe(mocha({
      reporter: 'spec'
    }))
    .on('error', function(){
      console.log('error');
    });
});

My only issue is that with every http.get, the console gets the body of the response logged which I want to prevent, google searches for disabling logging on http.get have yielded nothing.

Confused about why an Elixir Ecto validation test is not working

I have a user model that looks like this:

defmodule MyApp.User do
  schema "users" do
    field :name, :string
    field :email, :string

    field :password, :string, virtual: true
    field :password_confirmation, :string, virtual: true

    timestamps
  end

  @required_fields ~w(name email)
  @optional_fields ~w()

  def changeset(model, params \\ :empty) do
    model
    |> cast(params, @required_fields, @optional_fields)
    |> validate_length(:password, min: 8)
  end
end

And the test in question makes sure the password length validation works.

defmodule MyApp.UserTest do
  use MyApp.ModelCase

  alias MyApp.User
  alias MyApp.Repo

  @valid_attrs %{
    name: "Uli Kunkel",  
    email: "nihilist@example.com", 
  }

  @invalid_attrs %{}

  test "validates the password is the correct length" do
    attrs = @valid_attrs |> Map.put(:password, "1234567")
    changeset = %User{} |> User.changeset(attrs)
    assert {:error, changeset} = Repo.insert(changeset)
  end
end

Only the test fails, even though the password is a character too short. What am I missing?

Mocking Node.js module in Sinon still calls actual module

I'm starting to write tests for a node.js server I'm writing. I'm trying to test this function

exports.get_device_states = function (body, master_callback) {
    var state = new State(body[State.id_key]);
    console.log("STATE: ");
    console.log(state);

    mysqlDao.get_device_states_for_group(state, function(err, result) {
        var resp_json = {
            'error': err,
            'stateList': result
        }

        master_callback(resp_json);
    });
}

I need to mock the 'mysqlDao' module that I use to read/write to my db. but I was unable to do this. Whenever I try. I still get the actual db results back.

messagesTest.js

var sandbox = sinon.sandbox.create();
var stubbedDao = {
    get_device_states_for_group: sandbox.stub().returns("STUBBED")
}

...

describe('messages', function() {

    before(function() {
        mockery.enable();
    });

    beforeEach(function() {
        mockery.registerAllowable('async');
        mockery.registerAllowable('../models/State');
        mockery.registerAllowable('../models/Message');
        mockery.registerMock('../dao/gcmdao', stubbedDao);

        messages = require('../business/messages.js');
    });

    afterEach(function() {
        sandbox.verifyAndRestore();
       mockery.deregisterAll(); 
    });

    after(function() {
        mockery.disable();
    });


    describe('get_device_state', function () {
        it('isNormal', function () {
            var body = {
                "STATE_ID": testData.state_one
            }

            stubbedDao.get_device_states_for_group.yields();

            messages.get_device_states(body, function(resp) {
                console.log("returns");
                assert(stubbedDao.get_device_states_for_group.calledOnce);
                console.log(resp);
            })

        });
    });
});

But instead of returning "STUBBED" Like I want it to. It just returns the Db results. It's not a huge issue for read functions but I need this to work so that I don't modify the db on other tests.

Thanks, A.L

Python setup.py test dependencies for custom test command

To make python setup.py test linting, testing and coverage commands, I created a custom command. However, it doesn't install the dependencies specified as tests_require anymore. How can I make both work at the same time?

class TestCommand(setuptools.Command):

    description = 'run linters, tests and create a coverage report'
    user_options = []

    def initialize_options(self):
        pass

    def finalize_options(self):
        pass

    def run(self):
        self._run(['pep8', 'package', 'test', 'setup.py'])
        self._run(['py.test', '--cov=package', 'test'])

    def _run(self, command):
        try:
            subprocess.check_call(command)
        except subprocess.CalledProcessError as error:
            print('Command failed with exit code', error.returncode)
            sys.exit(error.returncode)


def parse_requirements(filename):
    with open(filename) as file_:
        lines = map(lambda x: x.strip('\n'), file_.readlines())
    lines = filter(lambda x: x and not x.startswith('#'), lines)
    return list(lines)


if __name__ == '__main__':
    setuptools.setup(
        # ...
        tests_require=parse_requirements('requirements-test.txt'),
        cmdclass={'test': TestCommand, 'build_ext': BuildExtCommand},
    )

How can I write an integration test for an endpoint that uses the Storage filesystem in Laravel 5?

I have the following API endpoint (code has been simplified for the purpose of the question):

class TestController{
     public function test(Request $request)
     {
          $this->validate($request, ['picture' => 'required|image']);

          Storage::disk('s3')->put('tests/test.png', file_get_contents($request->file('picture'));

          return 'tests/test.png';
     }

How can I write an integration test for this code in phpunit?
I have a test that works, but the problem is that everytime I run phpunit, it uploads the file to Amazon S3.

How to skip third party or external library in xcode test coverage?

I am taking out test coverage in XCODE , I have includED certain third party tools in my project like TTTAttributed text and external library like Reachability.h. How could I avoid these libraries from Xcode coverage?enter image description here

Cant figure out why rspec is showing these errors. Please help me to configure it correctly

I am new to Rspec. Following Testing with Rspec(codeschool's course). I am getting the errors which are unexpected. (1st error is expected, as there is no Zombie function yet).

Am i doing something wrong? how to fix this configuration errors?

//("Error expected")

Vamsidhars-MacBook-Air:RAILS_APP_SAMPLE Vamsidhar$ rspec spec/lib/zombie_spec.rb /Users/Vamsidhar/Desktop/RAILS_APP_SAMPLE/spec/lib/zombie_spec.rb:2:in `': uninitialized constant Zombie (NameError)

//("The next part of error , unexpected ")

from /Users/Vamsidhar/.rvm/gems/ruby-2.2.1/gems/rspec-core-3.4.1/lib/rspec/core/configuration.rb:1361:in load' from /Users/Vamsidhar/.rvm/gems/ruby-2.2.1/gems/rspec-core-3.4.1/lib/rspec/core/configuration.rb:1361:inblock in load_spec_files' from /Users/Vamsidhar/.rvm/gems/ruby-2.2.1/gems/rspec-core-3.4.1/lib/rspec/core/configuration.rb:1359:in each' from /Users/Vamsidhar/.rvm/gems/ruby-2.2.1/gems/rspec-core-3.4.1/lib/rspec/core/configuration.rb:1359:inload_spec_files' from /Users/Vamsidhar/.rvm/gems/ruby-2.2.1/gems/rspec-core-3.4.1/lib/rspec/core/runner.rb:102:in setup' from /Users/Vamsidhar/.rvm/gems/ruby-2.2.1/gems/rspec-core-3.4.1/lib/rspec/core/runner.rb:88:inrun' from /Users/Vamsidhar/.rvm/gems/ruby-2.2.1/gems/rspec-core-3.4.1/lib/rspec/core/runner.rb:73:in run' from /Users/Vamsidhar/.rvm/gems/ruby-2.2.1/gems/rspec-core-3.4.1/lib/rspec/core/runner.rb:41:ininvoke' from /Users/Vamsidhar/.rvm/gems/ruby-2.2.1/gems/rspec-core-3.4.1/exe/rspec:4:in <top (required)>' from /Users/Vamsidhar/.rvm/gems/ruby-2.2.1/bin/rspec:23:inload' from /Users/Vamsidhar/.rvm/gems/ruby-2.2.1/bin/rspec:23:in <main>' from /Users/Vamsidhar/.rvm/gems/ruby-2.2.1/bin/ruby_executable_hooks:15:ineval' from /Users/Vamsidhar/.rvm/gems/ruby-2.2.1/bin/ruby_executable_hooks:15:in `'

vendredi 27 novembre 2015

Selenium tool for ui testing

org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"css selector","selector":"input.modal hide fade"} Command duration or timeout: 42 milliseconds

Using chaijs to test for correctness of datatypes of function arguments

I am using assert-type module to test for correctness of datatypes of function arguments.

Sample code of what I did;

var cs = require("coffee-script/register");//this line needed to require("assert-type"). Some bug.
var ty = require("assert-type"); //http://ift.tt/1HlV5C9
var T = ty.Assert;

function test_func(file_name, start_time, end_time) {
    T(ty.str, ty.obj.not.null, ty.obj.not.null)(file_name, start_time, end_time);
    //action code
}

What is the corresponding code if I were to use chaijs module? http://chaijs.com/

I went through the documentation but failed to find the corresponding code. Should I stick to using assert-type module?

Espresso click menu item

I have a menu in the actionbar which I create through:

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    menu.add(Menu.NONE, 98,Menu.NONE,R.string.filter).setIcon(R.drawable.ic_filter_list_white_48dp).setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
    menu.add(Menu.NONE, 99,Menu.NONE,R.string.add).setIcon(R.drawable.ic_add_white_48dp).setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);


    getMenuInflater().inflate(R.menu.menu_main, menu);

    return true;
}

and menu_main.xml looks like:

<menu xmlns:android="http://ift.tt/nIICcg"
    xmlns:app="http://ift.tt/GEGVYd"
    xmlns:tools="http://ift.tt/LrGmb4"
    tools:context=".MainActivity">
    <item
        android:id="@+id/action_settings"
        android:title="@string/action_settings"
        android:orderInCategory="100"
        app:showAsAction="never"
        android:icon="@drawable/ic_settings_white_48dp"/>
</menu>

When testing in Espresso I would like to click on the "add" icon (menuId 99). I tried

@Test
public void testAdd() {
openActionBarOverflowOrOptionsMenu(InstrumentationRegistry.getTargetContext());
    onView(withText(R.string.add)).perform(click());
}

but this fails with a NoMatchingViewException. ( The settings item, which is defined in the xml directly I can click with the same code. )

"Undefined index: localhost" PHPUnit exception in Codeception with Symfony2 module

I've got this very simple acceptance test using Codeception and its Symfony2 module:

public function myTest(AcceptanceTester $I)
{
    $I->wantTo('test something');
    $I->amOnRoute("acme_site_home.es");
    $I->dontSee('hello');
}

When I run it I get an Undefined index: localhost PHPUnit_Framework_Exception triggered by a call to $request->server->get("HTTP_HOST") in my route action.

I already tried the following:

  • Adding this to phpunit.xml:
    <phpunit>
        <php>
            <server name='HTTP_HOST' value='http://some.host.com' />
        </php>
    </phpunit>

  • Adding this to my test:
    $_SERVER['HOST_NAME'] = "some.host.com";

  • Adding this to my test:
    $_SERVER['HTTP_HOST'] = "some.host.com";

None of this works, I always get the same error message.

How could I fix this?


Notes

Just in case, my acceptance suite settings are as follows:

class_name: AcceptanceTester
modules:
    enabled:
        - Asserts
        - Db
        - Symfony2
        - Doctrine2
        - \Tests\Helper\Acceptance

And my Codeception settings:

namespace: Tests
actor: Tester
paths:
    tests: tests
    log: tests/_output
    data: tests/_data
    support: tests/_support
    envs: tests/_envs
settings:
    bootstrap: _bootstrap.php
    colors: true
    memory_limit: 1024M
extensions:
    enabled: [ Codeception\Extension\RunFailed ]
modules:
    config:
        Db:
            dsn: 'mysql:host=localhost;dbname=acme_test'
            user: 'root'
            password: 'blahblah'
            dump: 'tests/_data/dump.sql'
            populate: false
            cleanup: false
        Doctrine2:
            depends: Symfony2
            cleanup: false
        PhpBrowser:
            url: http://acme.com
        WebDriver:
             browser: firefox
             url: http://acme.com
        REST:
            depends: Symfony2
            url: http://acme.com

React refs are not mounting on tests if inside a react-bootstrap component

I am using:

  • "react": "0.13.3"
  • "react-bootstrap": "0.26.4"

Every time when I use a ref in a node inside a <Modal /> or other React Bootstrap component, they are correctly mounted when I run the system normally, but at test environment they just disappear.

I have tried all the render strategies of the react test utils, but seems to have no difference.

NoMatchingRootException Espresso with custom Toast

I'm starting out with Espresso and I've got a custom toast that I show when the user puts in something wrong (I know I can use EditText.setError(), but that's just how it is).

Here's the code for the Toast

 private static void showToast(Context context, String message, boolean isError) {
        if (context != null) {
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            TextView toastView = (TextView) inflater.inflate(R.layout.error_toast_layout, null);
            if (!isError) {
                toastView.setBackgroundColor(context.getResources().getColor(R.color.alert_positive));
            }
            toastView.setText(message);
            Toast errorToast = new Toast(context);
            errorToast.setGravity(Gravity.TOP, 0, 0);
            errorToast.setDuration(Toast.LENGTH_SHORT);
            errorToast.setView(toastView);
            errorToast.show();
        }
    }

and I am writing up a little UI test that will assert that correct Toasts are being shown when the user puts in wrong input

Here's the test

   @RunWith(AndroidJUnit4.class)
    @LargeTest
    public class ForgotPasswordTest extends BaseEspressoTest<ForgotPasswordActivity> {

        @Test
        public void testEmailNotEntered() {
            onView(withId(R.id.email_et)).perform(typeText("w"), closeSoftKeyboard());
            onView(withId(R.id.btn_submit)).perform(click());
            onView(withText(R.string.incorrect_email_dialog)).inRoot(withDecorView(not(mActivityRule.getActivity().getWindow().getDecorView()))).check(matches(isDisplayed()));     
    }
}

this works fine if I substitute my custom Toast for a regular Toast, but fails when I try it with mine. I can see that the Toast is being shown during the test.

Here's the error:

android.support.test.espresso.NoMatchingRootException: Matcher 'with decor view not ' did not match any of the following roots: [Root{application-window-token=android.view.ViewRootImpl$W@2d629b84, window-token=android.view.ViewRootImpl$W@2d629b84, has-window-focus=true, layout-params-type=1, layout-params-string=WM.LayoutParams{(0,0)(fillxfill) sim=#22 ty=1 fl=#8d810100 pfl=0x8 wanim=0x1030461 surfaceInsets=Rect(0, 0 - 0, 0)}, decor-view-string=DecorView{id=-1, visibility=VISIBLE, width=1080, height=1920, has-focus=true, has-focusable=true, has-window-focus=true, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=false, is-selected=false, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=0.0, child-count=1}}]

I've also tried to match the the Toast based on the fact that it's supposed to focus:

onView(withText(R.string.incorrect_email_dialog)).inRoot(isFocusable()).check(matches(isDisplayed()));

but that just says that it can't find it within the view hierarchy:

No views in hierarchy found matching: with string from resource id: <2131165635>[incorrect_email_dialog] value: Please enter a valid email

Webdriver Chrome C# loses style when runned on localhost

I have a site developed in ASP.NET MVC. I run it in IIS. Then I try to do some tests using Webdriver for Chrome, but when I execute it, the site loses its style. Here's the code:

using (IWebDriver driver = new ChromeDriver())
        {
            driver.Navigate().GoToUrl("http://localhost:58178/SomeCoolPage");
            driver.FindElement(By.Id("SomeCoolId")).Click();
        }

Why does that happen? How would I fix it?

Javascript testing stub global variable function

I am writing a few Unit tests for a React application.

In the page header, the 'mixpanel' tracking library is added between <script> tags as documented here: http://ift.tt/1pO14pc. According to their documentation, "The snippet provides a global variable named mixpanel that you can use to send data to the Mixpanel API."

In the React component's code, Mixpanel's track function is called like so:

  showModal: function(evt) {
    evt.preventDefault()
    var modal = this.refs.modal
    modal.showModal()
    mixpanel.track("Login button clicked")
  }

However, in the test, there is an error caused by mixpanel.track not being defined (when showModal is called). I have set up the test environment to use a testdom as explained here: http://ift.tt/1edi0C4 and here http://ift.tt/1zdN5JY.

I believe I need to simulate the track method to at least exist so that an error is not thrown in the test. Is this correct, and what is the best way to do this?

Checking if version in comment is the same as package.json

How can i check if the version in the comment of the main library is the same as the one in package.json file

I'm using Gulp, Mocha, Semver, Should

This is the main file comment:

/*!
 * lib.js 0.0.1

Cross Language Tests

I've written a sort of crypt/decrypt wrappers for libsodium in 3 different languages(php, javascript and .NET), and I would like to programmatically test that what gets crypted in php can get decrypted in .NET, what gets crypted in javascript can get decrypted in php, and so on. I looked up fitnesse, but I'm not sure about how it works and if it is the right solution for me(can't find anything about javascript on the official documentation). Should I stick with fitnesse of are there better solutions? Ps. This isn't probably the best place where to ask this, so if someone want to move this question to a more appropriate StackOverflow community, you're welcome.

JMeter encrypted credentials

I started using Apache Jmeter recently. When I recorded the login process, the password is encrypted in the request, so when I tried to change the credentials by setting the password to plain text, I get 500 response code.

Can anyone help me solve this problem?

What is the difference between eCobertura and Cobertura?

Can I use e-Cobertura for system testing? If not, why?

---------------------------


Mocking an angular service in Protractor

I'm trying to use Protractor's addMockModule to insert mock data in my end-2-end test.

My test is supposed to go to a web site, find a button by css-class and click it. The button click calls the function dostuff() in MyService, which fetches data from the backend.

My code so far: describe('should display validation error', function () {

it('should work', function () {
    browser.get('http://my.url');

    browser.addMockModule('MyService', function () {
            // Fake Service Implementation returning a promise
            angular.module('MyService', [])
            .value({
                dostuff: function () {
                    return {
                        then: function (callback) {
                            var data = { "foo": "bar" };
                            return callback(data);
                        }
                    };
                }
            });
    });

    var button = element(by.css('.btn-primary'));
    button.click();

    browser.sleep(5000);


});

});

The test is accessing the web site and clicking the button. The problem is that real data from the database is displayed, not the mock data. I followed several threads, like this one: How to mock angular.module('myModule', []).value() in Jasmine/Protractor

However, it seems like the function protractor.getInstance() are deprecated.

Anyone got this working?

Sharepoint - How to Generate a Scripting Error in Outlook for Test

Hello,

I am trying to test error supression on Sharepoint but I am having some trouble.

This is my process:

On a relatively plain website (all it contains is a colored-in div), I added this script:

<script>
        var x[] = 0;
        var err = 10/x;
       alert(err);
   </script>

When setting my Outlook homepage to this site, I see this error:

enter image description here

I also have the following script, which suppresses this message (when adding this to my code, the error message doesn't appear):

    <script type="text/javascript">
    window.onerror = function(message, url, lineNumber) {  
        // code to execute on an error  
        return true; // prevents browser error messages  
    };
    </script> 

I want to test this script out on my Sharepoint site, but when I embed the above, error-inducing code onto my Sharepoint homepage and open the page in Outlook, I am not seeing any error messages.

I added the code in the following ways:

1 - Page > Edit > Edit Source > Added the code to the top
2 - Page > Edit > Embed Code > Added the code to various areas of the page

Neither of these methods worked, and the first one actually produced a message telling me that I should use the embed function, which also doesn't seem to work!

I need to generate this error from the Sharepoint page so that I can check **whether the error-suppressing script actually does what it's supposed to. Can **anyone think of what may be going wrong here?

Any help is much appreciated!

Laravel firstOrCreate with filter by selected attribute not working on my testing

i have some problem on testing when i'm using findOrCreate method. This is my example code :

$template = Template::firstOrCreate($temp, ["user_id"=>$id, "project_id"=>$target_id]);       

on my app development, this method is working. Template has created if 'user_id' and 'project_id' not found, but when i'm run via testing with phpunit this code always error like bellow :

Trying to get property of non-object

need help, i'm feeling crazy on this case....

Testing war file using TestNG

I have just created a web service in eclipse and exported as war file like myService.war.Can i make a separate testing tool as jar file which tests myService.war file. I want to use testNG api by which whenever i run that jar file,it tests myService.war .

Component returned failure code: 0x80004003 (NS_ERROR_INVALID_POINTER) [nsIDOMLocation.toString] in selenium

While running selenium test case I could see the below error. It is running without error for sometimes, but sometimes it is going to error.

Component returned failure code: 0x80004003 (NS_ERROR_INVALID_POINTER) [nsIDOMLocation.toString]
    at com.thoughtworks.selenium.HttpCommandProcessor.throwAssertionFailureExceptionOrError(HttpCommandProcessor.java:112)
    at com.thoughtworks.selenium.HttpCommandProcessor.doCommand(HttpCommandProcessor.java:106)
    at com.thoughtworks.selenium.DefaultSelenium.waitForPopUp(DefaultSelenium.java:403)
    at com.sf.httptestselenium.tracker.FilterTrackerSeleniumHttpTest.configureColumns(FilterTrackerSeleniumHttpTest.java:137)

Could you please help me..

jeudi 26 novembre 2015

Robot Framework Test Case Generation from Within a Test Case?

I am using Robot Framework to automate onboard unit testing of a Linux based device.

The device has a directory /data/tests that contains a series of subdirectories, each subdirectory is a test module with 'run.sh' to be executed to run the unit test. For example :

/data/tests/module1/run.sh

/data/tests/module2/run.sh

I wrote a function that collects the subdirectory names in an array, and this is the list of test modules to be executed. The number of modules can vary daily.

@{modules}=     SSHLibrary.List Directories in Directory       /data/tests

Then another function (Module Test) that basically runs a FOR loop on the element list and executes the run.sh in each subdirectory, collects log data, and logs it to the log.html file.

The issue I am experiencing is that when the log.html file is created, there is one test case titled Module Test, and under the FOR loop, a 'var' entry for each element (test module). Under each 'var' entry are the results of the module execution.

Is it possible from within the FOR loop, to create a test case for each element and log results against it? Right now, if one of the modules / elements fails, I do not get accurate results, I still get a pass for the Module Test test case. I would like to log test cases Module 1, Module 2, ... , Module N, with logs and pass fail for each one. Given that the number of modules can vary from execution to execution, I cannot create static test cases, I need to be able to dynamically create the test cases once the number of modules has been determined for the test run.

Any input is greatly appreciated.

Thanks,

Dan.