vendredi 31 mars 2017

IdlingResources doesn't work Espresso Android

I have the problem with idling resources while testing using Espresso.

It doesn't work. It is called only twice and that's all, even if return false.

public class MyIdlingResource implements IdlingResource {

    private boolean mIdle;
    private ResourceCallback mResourceCallback;

    public MyIdlingResource () {
        this.mIdle = false;
        this.mResourceCallback = null;
    }

    @Override
    public final String getName() {
        return ViewAvailabilityClassIdlingResource.class.getSimpleName();
    }

    @Override
    public final boolean isIdleNow() {
        ArrayList<View> views = doStuff();
        mIdle =  views != null && !views.isEmpty();

        if (mIdle) {
            if (mResourceCallback != null) {
                mResourceCallback.onTransitionToIdle();
            }
        }

        return false;
    }

    @Override
    public void registerIdleTransitionCallback(ResourceCallback resourceCallback) {
        mResourceCallback = resourceCallback;
    }

}

So in this case I return false all the time, but it doesn't work either.

What is wrong ?

Exception: x is not one of the net inputs: {'data': (80, 3, 227, 227)} / caffe deploy.prototxt input data

I am trying to test my network on new data, below is the part where I define data in my deploy.prototxt file

input: "data"
input_dim: 80 #16
input_dim: 3
input_dim: 227
input_dim: 227
input: "modaldata"
input_dim: 80 #16
input_dim: 3
input_dim: 227
input_dim: 227
input: "clip_markers"
input_dim: 80 #16
input_dim: 1
input_dim: 1
input_dim: 1

data is the RGB file and modaldata is a modal image of the same file (such as depth).

Using a python script I transform both of the image data, there is no error during transforming "data" however I get an error while transforming the "modaldata" at this line:

modalcaffe_in[ix] = transformer_modal.preprocess('modaldata',inputs)

And the error I get is:

..../python/caffe/io.py", line 136, in preprocess
  self.__check_input(in_)
 File "/.../python/caffe/io.py", line 115, in __check_input
  in_, self.inputs))

Exception: modaldata is not one of the net inputs: {'data': (80, 3, 227, 227)}

Is this a shortcoming of caffe? Are we not allowed to pass multiple image data? If not, what am I doing wrong? Either way, how can I overcome this? I have trained my model and all, all I need is to test on new data. Thx.

Is there a way to easily make a specific directory slow for a unit test?

My goal is to run a test against a file system which is intentionally slow, to test performance metrics in chaotic storage scenarios. In the same sense that there are ways to limit memory and cpu with cgroups in containers, i've considered wether or not there is a io limitation i can impose.

  • Is there a way to mount a simple file system to a directory which is intentionally slowed down ?
  • Alternatively, is there a way to make a docker container limit disk operation qoutas on a container, by issuing a command line operation (not that the command line operation part is important here - because if I run this on a docker container, it will be started inside of kubernetes for me).

Python 2D array i C using ctypes

i'm trying to use a self written c lib to proces 2d array from python but with little success.

Here is my c code:

CamLibC.c

int TableCam(const int x, const int y, int **Array) {
    int i = 0;
    int j = 0;

    for (i; i < x; i++) {
        for (j; j < y; j++) {
            Array[i][j] = 1;
        };

    };
}

cc -nostartfiles -shared -fPIC -o CamLibOS.os CamLibC.c

Now here is my python wrapper:

CamLibPy.py

import os,sys
import ctypes

dirname     = os.path.dirname(os.path.realpath(sys.argv[0]))
CamLibFile  = dirname + '/CamLibOS.os'

_CamLib = ctypes.CDLL(CamLibFile)
_CamLib.TableCam.argtypes = [ctypes.c_int, ctypes.c_int, ctypes.POINTER(ctypes.c_int)]

def TableCam (A) :
    global _CamLib

    x = len(A)
    y = len(A[0])

    print('x: ', x, ' y: ', y);

    arrayType = ((ctypes.c_int * x) * y)
    array = arrayType()

    _CamLib.TableCam(ctypes.c_int(x), ctypes.c_int(y), array)

    print(array)

And my python code where i use the function:

Test.py

import CamLibPy
from numpy import zeros

Anum = zeros((3,3))
print('Start: ', Anum)

CamLibPy.TableCam(Anum)

print('Ended: ', Anum)

In this test program i try to change all the zeros in the array to ones. but as soon as i try to run this is get the following output:

Start: [[ 0. 0. 0.] [ 0. 0. 0.] [ 0. 0. 0.]]

x: 3 y: 3

Traceback (most recent call last): File "/media/pi/USB DISK/Test/Test.py", line 7, in CamLibPy.TableCam(Anum) File "/media/pi/USB DISK/Test/CamLibPy.py", line 21, in TableCam _CamLib.TableCam(ctypes.c_int(x), ctypes.c_int(y), array) ctypes.ArgumentError: argument 3: : expected LP_c_long instance instead of c_long_Array_3_Array_3

it's saying it expected a c_long but i clearly used c_int to make the arrayType

Can somebody tell me what i did wrong?

Do I need test method that is inside the test class

So I have a sample method that I give him a day and it returns me the first and last day of a week in which the day:

public static final DatePeriod thisWeek(LocalDate date) {

    TemporalField dayOfWeek = WeekFields.of(Locale.FRANCE).dayOfWeek();
    LocalDate mon = date.with(dayOfWeek, 1);
    LocalDate sun = date.with(dayOfWeek, 7);

    return new DatePeriod(mon, sun);
}

I have to write a JUnit test (and I did it):

@Test
public void testThisMonth_LocalDate() throws ParseException {
    System.out.println("thisMonth");
    for (String[] date : VALID_TEST_DATES) {
        LocalDate dateLocal = dateToLocal(date[0]);
        DatePeriod expResult = new DatePeriod(dateToLocal(date[5]), dateToLocal(date[6]));
        DatePeriod result = JavaTimeUtils.thisMonth(dateLocal);
        assertEquals(expResult.getLeft(), result.getLeft());
        assertEquals(expResult.getRight(), result.getRight());
    }
}

So, because I used code in dateToLocal() multiple times, I decided to make it in method like this:

public LocalDate dateToLocal(String dateString) throws ParseException {   // Calendar to LocalDate
    DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
    Calendar cal = Calendar.getInstance();
    Date initDate = df.parse(dateString);
    cal.setTime(initDate);
    LocalDate dateLocal = LocalDate.of(cal.get(Calendar.YEAR), Month.of(cal.get(Calendar.MONTH)+1), cal.get(Calendar.DAY_OF_MONTH));

    return dateLocal;
}

And it works. But that is not my question. I was wondering is this the correct way to do things like this (method in this JUnit test), do I need to make Test for this method, do I have to move it in other class (outside the tests)? I know this is strange question, I've already searching in google, unsuccessfully. (maybe I can't ask google right). Thanks :)

Junit Testing for an Android Activity

Does any one have any experience with creating unit-test for the On Create and OnClick method in java, using Android Studio? I use data from my Firebasedatabase. I think I have to use Mock-object, but I don't knot where to start.

Under is the code from my class LoginActivity

public class LoginActivity extends AppCompatActivity implements View.OnClickListener{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        mfireBaseAuth = FirebaseAuth.getInstance();
        mDatabase = FirebaseDatabase.getInstance().getReference();
        mProgressDialog = new ProgressDialog(this);
        editTextEmail = (EditText) findViewById(R.id.editTextEmail);
        editTextPassword = (EditText) findViewById(R.id.editTextPassword);
        buttonSignIn = (Button) findViewById(R.id.buttonSignIn);
        textViewSignUp = (TextView) findViewById(R.id.textViewSignUp);

        buttonSignIn.setOnClickListener(this);
        textViewSignUp.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        if(v == buttonSignIn){
            usersignin();

        }
        if(v==textViewSignUp){
            startActivity(new Intent(this, RegisterActivity.class));
        }
       }

    private void usersignin() {
        String email = editTextEmail.getText().toString().trim();
        String password = editTextPassword.getText().toString().trim();

        if(TextUtils.isEmpty(email)){
            Toast.makeText(this, "Please enter Email", Toast.LENGTH_SHORT).show();
            return;
        }

        if(TextUtils.isEmpty(password)){
            Toast.makeText(this, "Please enter password", Toast.LENGTH_SHORT).show();
            return;
        }

        mProgressDialog.setMessage("Logging in. Please wait...");
        mProgressDialog.show();
        mfireBaseAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {
                mProgressDialog.dismiss();
                if(task.isSuccessful()){
                    getSignedInUserProfile();
                }
            }
        });
    }

    private void getSignedInUserProfile() {

        DatabaseReference reference = mDatabase;//.child("eduback-2feef");
        firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
        userID = firebaseUser.getUid();
        reference.child("Users").child(userID).child("User info").addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                User user = dataSnapshot.getValue(User.class);
                if(user != null) {
                    // Save if the user is student or prof in shared prefs.
                    PreferenceHelper helper = new PreferenceHelper(getBaseContext());
                    helper.setIsStudent(user.isStudent);
                    checkStudentOrProfessor(user);
                }

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                // Ups vis error
            }
        });



    }

    private void checkStudentOrProfessor(User user) {

        Intent i;
        if (user.isStudent ) {
            i = new Intent(this, MainActivityStudent.class);
        } else {
            i = new Intent(this, MainActivityProfessor.class);
        }
        startActivity(i);


    }



}

Automated testing Selenium or iMacros

I need to do many automated tests in a web app and I am wondering what software should I use. I have some experience with Selenium IDE and iMacros (PRO version), but now that I need to choose I can't really tell big differences between them, although I prefer iMacros interface and its wizards.

Is there any big difference among them?

Thanks in advance, Xavi.

how to catch error Recursive looping detected

there are certain tests and crashes randomly way this error, randomly, that is, in different places of the test, I understand that this error falls in a result of the fact that the ui is blocked, and at this moment tries to contact the other threads I see this error, a lot of tests and exactly how to catch is not clear, but it is also not clear to what line my test crashes error

java.lang.IllegalStateException: Recursive looping detected!
    at android.support.test.espresso.core.deps.guava.base.Preconditions.checkState(Preconditions.java:173)
    at android.support.test.espresso.base.UiControllerImpl.loopUntil(UiControllerImpl.java:439)
    at android.support.test.espresso.base.UiControllerImpl.loopMainThreadUntilIdle(UiControllerImpl.java:365)
    at android.support.test.espresso.ViewInteraction$1.run(ViewInteraction.java:119)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:423)
    at java.util.concurrent.FutureTask.run(FutureTask.java:237)
    at android.os.Handler.handleCallback(Handler.java:739)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.support.test.espresso.base.UiControllerImpl.loopUntil(UiControllerImpl.java:470)
    at android.support.test.espresso.base.UiControllerImpl.loopMainThreadUntilIdle(UiControllerImpl.java:365)
    at android.support.test.espresso.ViewInteraction$2.run(ViewInteraction.java:161)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:423)
    at java.util.concurrent.FutureTask.run(FutureTask.java:237)
    at android.os.Handler.handleCallback(Handler.java:739)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5441)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:738)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:628)

Unit testing elixir functions properly

I'm fairly new to elixir and functional programming in general and I'm struggling to properly unit test functions that are composed of other functions. The general question is: when I have a function f that uses other functions g, h... internally, which approach should I take to test the whole?

Coming from the OOP world the first approach that comes to mind involves injecting the functions f depends of. I could unit test g, h... and inject all of those as arguments to f. Then, unit tests for f would just make sure it calls the injected functions as expected. This feels like overfitting though, and as an overall cumbersome approach that is against the functional mindset for which function composition should be a cheap thing to do and you should not be concerning yourself on passing all those arguments around the whole codebase.

I can also unit test g, h... as well as f by treating each of those as black boxes, which feels like the appropriate thing to do, but then the complexity of f's tests increases dramatically. Having simple tests that scale is one of the main purposes of unit testing.

To make the argument more concrete I'll put an example of a function that composes other functions inside and that I don't know how to unit test properly. This in particular is code for a plug that handles the creation of a resource in a RESTful fashion. Note that some of the "dependencies" are pure functions (such as validate_account_admin) but others are not (Providers.create):

  def call(conn, _opts) do
    account_uuid = conn.assigns.current_user.account["uuid"]

    with {:ok, conn}      <- Http.Authorization.validate_account_admin(conn),
         {:ok, form_data} <- Http.coerce_form_data(conn, FormData),
         {:ok, provider}  <- Providers.create(FormData.to_provider(form_data), account_uuid: account_uuid) do
      Http.respond_create(conn, Http.provider_path(provider))
    else
      {:error, reason, messages} -> Http.handle_error(conn, reason, messages)
    end
  end

Thanks!

How to store and fill in with fake data for exploratory testing

I am doing lot of exploratory testing, for which I have to fill in random information manually for email, password, first name, middle name, last name, address and ph#. Which takes considerable amount of time. So I would like to ask is there any chrome extension or application that saves data from http://ift.tt/uAlWXc and refill the saved data when needed.

I tried different chrome extensions like Form Filler, Fake Data, Bug magnet and all. Those didnt help me.

can not extract response body to set environment variable

I have response body from POST method like below

{
    "status": {
        "error": false,
        "code": 200,
        "message": "Login success"
    },
    "result": {
        "data": {
            "name": "vv",
            "email": "gg@gmail.com",
            "session_key": "xxx"
        }
    }
}

Then I want to extract that session key to add in the environment variable I used this code

var jsonData = JSON.parse(responseBody);
postman.setEnvironmentVariable("session", jsonData.sesssion_key);

But on the environment variable still return with "undefined" value Please help, Thanks

Printing statements in thenReturn of mockito

I am using Mockito to mock a certain class while writing my test cases. Is there a way to print some statements before returning a value;

when(x.callFunction(10).thenReturn(new String("Hello"));

The above statement works, however I am not able to do the following:

when(x.callFunction(10).thenReturn({
   System.out.println("Mock called---going to return hello");
   return new String("Hello");});

How does one write a good unit test without mocking everything?

I have read that mocking everything is bad.
Test Smell: Everything is mocked
Mock Everything Is a Good Way to Sink

I have also read that unit tests look at a single component whilst Integration tests test an entire system working together.
Writing Great Unit Tests: Best and Worst Practices

This confuses me. As I understand it, to write a proper unit test one needs to isolate a single component by mocking everything but the S.U.T. If one uses real objects throughout the test, doesn't that test become an integration test?

How does one write a good (isolated) unit test without mocking everything?

Testing interactive ICommand in C#

I want to test some commands in my WPF project which contain user interaction needed parts.

This is the viewmodel:

class MainViewModel : ViewModelBase
{
    public ICommand Export { get; private set; }
    public MainViewModel()
    {
        Export = SynchronousCommand.Create((o) => ExportModel(o));
    }

    private void ExportModel(object parameter)
    {
        string exportPath = null;
        SaveFileDialog fileDialog = new SaveFileDialog();
        fileDialog.Filter = "UDPROJ (*.udproj) |*.udproj";
        if (fileDialog.ShowDialog() == true)
        {
            exportPath = fileDialog.FileName;
        }

        // Other logic which should run in test...
    }
}

So I want to call this Export command from a test project without calling the SaveFileDialog. My first idea was that I have to send some command parameters through parameter but I would like to ask you, is there a more elegant way (becuase I have to get the command parameters in every case where the command contains some dialog calling)?

jeudi 30 mars 2017

Is there a monkey testing framework for Mac apps?

I've found several monkey testing libraries for web apps, and a few for iOS and Android. Is there one for the Mac?

My app is sandboxed, so there should be no way that a crazy monkey could hurt the rest of my system. I just want to run a monkey all night and find ways to crash it.

maven test on scala code return successful build but There are no tests to run

I have the problem using mvn test to run the test code in my maven scala code. Here are the settings: . ├── pom.xml ├── run └── src ├── main │   └── scala │   └── com │   └── myCompany │   └── scala │   └── MaxPrice.scala ├── resources │   └── JCudaMultiplyBy2.ptx └── test ├── resources │   └── JCudaMultiplyBy2.ptx └── scala └── MyTest.scala JCudaMultiplyBy2.ptx is the file will be used in MyTest.scala.
Here is my pom.xlm:

<project xmlns="http://ift.tt/IH78KX" xmlns:xsi="http://ift.tt/ra1lAU" xsi:schemaLocation="http://ift.tt/IH78KX http://ift.tt/HBk9RF">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.myCompany.scala</groupId>
  <artifactId>sparkExample</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>jar</packaging>
  <properties>
    <scala.version>2.10.5</scala.version> <!-- Well we can use 2.11 scala, but scala-maven-plugin may have issue with that, so if to use mvn -q scala:run, then keep 2.10 scala, otherwise, have to spark-submit -->
  </properties>
  <dependencies>
    <dependency>
      <groupId>org.scala-lang</groupId>
      <artifactId>scala-library</artifactId>
      <version>${scala.version}</version>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.4</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.scala-tools</groupId>
      <artifactId>maven-scala-plugin</artifactId>
      <version>2.11</version>
    </dependency>
    <dependency>
      <groupId>org.apache.spark</groupId>
      <artifactId>spark-core_2.10</artifactId>
      <version>1.6.1</version>
    </dependency>
    <dependency>
      <groupId>org.jcuda</groupId>
      <artifactId>jcuda</artifactId>
      <version>0.8.0</version>
    </dependency>
    <dependency>
      <groupId>org.jcuda</groupId>
      <artifactId>jcublas</artifactId>
      <version>0.8.0</version>
    </dependency>
  </dependencies>
  
  <build>
    <sourceDirectory>src/main/scala</sourceDirectory>
    <testSourceDirectory>src/test/scala</testSourceDirectory>
    <plugins>
      <plugin>
        <groupId>org.scala-tools</groupId>
        <artifactId>maven-scala-plugin</artifactId>
        <executions>
          <execution>
            <goals>
              <goal>compile</goal>
              <goal>testCompile</goal>
            </goals>
          </execution>
        </executions>
        <configuration>
          <scalaVersion>${scala.version}</scalaVersion>
          <args>
            <!--arg>-target:jvm-1.5</arg-->
          </args>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>2.8.1</version>
        <configuration>
                    <includes>
                        <include>**/*Spec.class</include>
                        <include>**/*Test.class</include>
                    </includes>
                </configuration>
      </plugin>
   </plugins>
  </build>
  <reporting>
    <plugins>
      <plugin>
        <groupId>org.scala-tools</groupId>
        <artifactId>maven-scala-plugin</artifactId>
        <configuration>
          <scalaVersion>${scala.version}</scalaVersion>
        </configuration>
      </plugin>
    </plugins>
  </reporting>
</project>

  
The MyTest.scala code is the same as the MaxPrice.scala code, and if I run mvn compile and then run mvn -q scala:run -DmainClass=com.myCompany.scala.MaxPrice -DaddArgs="local[*]", it works perfectly. Now I change the Object name of MaxPrice.scala into MyTest and also its file name into MyTest.scala. Putting MyTest.scala under src/test/scala and run mvn test, it doesn't work and give this results:
[INFO] Scanning for projects...
[WARNING] 
[WARNING] Some problems were encountered while building the effective model for com.myCompany.scala:sparkExample:jar:1.0-SNAPSHOT
[WARNING] 'build.plugins.plugin.version' for org.scala-tools:maven-scala-plugin is missing. @ line 48, column 15
[WARNING] 
[WARNING] It is highly recommended to fix these problems because they threaten the stability of your build.
[WARNING] 
[WARNING] For this reason, future Maven versions might no longer support building such malformed projects.
[WARNING] 
[INFO]                                                                         
[INFO] ------------------------------------------------------------------------
[INFO] Building sparkExample 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO] 
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ sparkExample ---
[WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory /home/yuxin/OwensGroup/MavenPract/maven-sparkJcublas/src/main/resources
[INFO] 
[INFO] --- maven-compiler-plugin:3.2:compile (default-compile) @ sparkExample ---
[INFO] Nothing to compile - all classes are up to date
[INFO] 
[INFO] --- maven-scala-plugin:2.15.2:compile (default) @ sparkExample ---
[INFO] Checking for multiple versions of scala
[WARNING]  Expected all dependencies to require Scala version: 2.10.5
[WARNING]  com.myCompany.scala:sparkExample:1.0-SNAPSHOT requires scala version: 2.10.5
[WARNING]  com.twitter:chill_2.10:0.5.0 requires scala version: 2.10.4
[WARNING] Multiple versions of scala libraries detected!
[INFO] includes = [**/*.java,**/*.scala,]
[INFO] excludes = []
[INFO] Nothing to compile - all classes are up to date
[INFO] 
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ sparkExample ---
[WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] Copying 1 resource
[INFO] 
[INFO] --- maven-compiler-plugin:3.2:testCompile (default-testCompile) @ sparkExample ---
[INFO] Nothing to compile - all classes are up to date
[INFO] 
[INFO] --- maven-scala-plugin:2.15.2:testCompile (default) @ sparkExample ---
[INFO] Checking for multiple versions of scala
[WARNING]  Expected all dependencies to require Scala version: 2.10.5
[WARNING]  com.myCompany.scala:sparkExample:1.0-SNAPSHOT requires scala version: 2.10.5
[WARNING]  com.twitter:chill_2.10:0.5.0 requires scala version: 2.10.4
[WARNING] Multiple versions of scala libraries detected!
[INFO] includes = [**/*.java,**/*.scala,]
[INFO] excludes = []
[INFO] Nothing to compile - all classes are up to date
[INFO] 
[INFO] --- maven-surefire-plugin:2.8.1:test (default-test) @ sparkExample ---
[INFO] Surefire report directory: /home/yuxin/OwensGroup/MavenPract/maven-sparkJcublas/target/surefire-reports

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
There are no tests to run.

Results :

Tests run: 0, Failures: 0, Errors: 0, Skipped: 0

[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 6.202 s
[INFO] Finished at: 2017-03-30T14:52:29-07:00
[INFO] Final Memory: 25M/592M
[INFO] ------------------------------------------------------------------------

Also if I run mvn test -Dtest=MyTest, it still gives the same result: no tests to run.

Anyone has an idea? I have search a lot but couldn't find the answer, help!

Unit Testing Pig Script with streaming to a python script

I have a pig script and I am using org.apache.pig.pigunit.PigTest. I am streaming data through two scripts (a python script and an awk script) in my pig script. This works in my functional tests and when I manually run it, but it does not work in my unit test.

These are the function definitions:

DEFINE AWK `$AWK_SCRIPT` ship('$AWK_SCRIPT');
DEFINE PY `$PYTHON_BIN $PYTHON_SCRIPT` ship('$PYTHON_SCRIPT');

This gives me the error:

org.apache.pig.impl.logicalLayer.FrontendException: ERROR 1066: Unable to open iterator for alias bid_recommendation_model_1. Backend error : java.lang.IllegalStateException: Job in state DEFINE instead of RUNNING

If I remove the ship statement (which I can have my unit tests do for testing), I instead get "unable to open iterator," but with no explanation.

Basically all the pig script does is load the data and stream it through those scripts and outputs the union, eg:

py_output = STREAM input THROUGH PY as (...);
awk_output = STREAM input THROUGH AWK as (...);
result = UNION py_putput, awk_output;
STORE result INTO ...;

Testing UWP Bluetooth Application

I am trying to develop some tests for a Windows 10 UWP application which uses Windows.Devices.Bluetooth.BluetoothLEDevice. I have a plain class that is part of my application which has a private BluetoothLEDevice type field.

class MyDevice
{
    private Windows.Devices.Bluetooth.BluetoothLEDevice bluetoothLEDevice;

    ...


    // Additional methods which rely on `bluetoothLEDevice`
}

The methods of said class use the events and methods of bluetoothLEDevice, some are private and others are public. How can I test the public methods of MyDevice?

I have tried something like this which I think could work, but I can see that it will take hundreds of lines of code and quite a few extra classes because I would need to implement a lot of stuff in FakeBluetoothLEDevice in orde for it to work properly.

private void ValueChangedEventDataParsingTest()
{
    var device = new FakeBluetoothLEDevice();

    var myDevice = new MyDevice(device);

    device.InvokeValueChanged("this is the value for a fake ValueChangedEvent");

    Assert.Equals(probe.SomeProperty, "expected");
}

Are there any frameworks that would help me achieve what I want? Or even a better approach that would save me some pain?

Mockito when() on method of field

I'm trying to test with Mockito the interactor in simple application, that works as Finite state machine.

public class Machine {

private OnActionListener mListener;
private ArrayList<State> mStates;
private FSMJsonParser parser;

private State mCurrentState;

public Machine(String jsonConfig, OnActionListener listener, FSMJsonParser parser) throws IOException {

    this.mListener = listener;
    this.parser = parser;
    initStates(jsonConfig);
    mCurrentState = getStateByName("AlarmArmed_AllLocked");
}

private void initStates(String jsonConfig) throws IOException{

    mStates = parser.parseFSMFromJson(jsonConfig);
}

There is test:

@RunWith(PowerMockRunner.class)
@PrepareForTest(FSMJsonParser.class)
public class FSMtest {

@Mock
State state;

@Mock
ControlPresenter presenter;

@Mock
FSMJsonParser parser;

@InjectMocks
Machine machine;

@Before
public void setUp() throws IOException {

    when(parser.parseFSMFromJson(anyString())).thenReturn(parseFSMFromJson(readConfig()));
}

@Test
public void testAlarmArmedAllLockedStateActions() throws IOException{

    machine.lock();
    verify(machine, times(1)).setCurrentState(anyString());

    machine.lockx2();
    verify(machine, times(1)).setCurrentState("AlarmArmed_AllLocked");

    machine.unlock();
    verify(machine, times(1)).setCurrentState("AlarmDisarmed_DriverUnlocked");

    machine.unlockx2();
    verify(machine, times(1)).setCurrentState("AlarmDisarmed_AllUnocked");
}

I provide a parse JSON (with states description, stored in assets) with method parseFSMFromJson(readConfig()). When ran test with debug mode, JSON was parsed properly. But fields of Machine mock object didn't initialized, and was null and all tests failed. I need to initialize ArrayList mStates for correct work of Machine class. How to test this class properly??

ruby on rails using fixtures

I am using fixtures in testing.

For example:

post bookings_path, params: { journal: { from_account_number: "1",
                                         from_account: "Test",
                                         from_amount: "12",
                                         to_account_number: "2",
                                         to_account: "Test2",
                                         to_amount: "12"
      } }

Is it possible to replace

from_account_number: "1",
from_account: "Test",
from_amount: "12",
to_account_number: "2",
to_account: "Test2",
to_amount: "12"

with one fixture call?

nUnit 3 C# - TestCaseSource - TestData - Testing that exceptions are thrown

In scenarios where I am testing methods that receive more complex objects, I normally use something similar to this to test the method against many test cases:

[TestFixture()]
public class DataTransmitterFactoryTests
{
    [Test, TestCaseSource(typeof(DataTransmitterFactoryTestCases), "CreateDataTransmitterFactoryTestCases")]
    public void CreateTransmitterForStateTest(bool isException, Type type, IDataConfigurationData config)
    {
        var vtf = new DataTransmitterFactory();
        if (isException)
        {
            Assert.That(() => vtf.CreateTransmitterForState(config), Throws.TypeOf(type));
        }
        else
        {
            var xmitter = vtf.CreateTransmitterForState(config);
            Assert.IsInstanceOf(type, xmitter);
        }
    }
}

I use an IEnumerable to feed the test cases into my test:

public class DataTransmitterFactoryTestCases
{
    public static IEnumerable CreateDataTransmitterFactoryTestCases
    {
        get
        {
            yield return new TestCaseData(false, typeof(DataFileTransmitter),
                FuncMocks.DataConfigurationDataMock(x =>
                {
                    x.DataState.Returns(DataState.PA);
                    x.TransmissionType.Returns(DataTransmissionType.File);
                    return x;
                })).SetName("CreateDataTransmitterFactoryTest - PA - FileTransmitter");
            yield return new TestCaseData(false, typeof(DataWebServicePostTransmitter),
                FuncMocks.DataConfigurationDataMock(x =>
                {
                    x.DataState.Returns(DataState.PA);
                    x.RunMode.Returns(DataRunMode.Production);
                    x.TransmissionType.Returns(DataTransmissionType.WebServicePost);
                    return x;
                })).SetName("CreateDataTransmitterFactoryTest - PA - WebServicePost");
            yield return new TestCaseData(true, typeof(NotImplementedException),
                FuncMocks.DataConfigurationDataMock(x =>
                {
                    x.DataState.Returns(DataState.PA);
                    x.TransmissionType.Returns(DataTransmissionType.RestWebService);
                    return x;
                })).SetName("CreateDataTransmitterFactoryTest - PA - RestWebService");
            yield return new TestCaseData(true, typeof(NotImplementedException),
                FuncMocks.DataConfigurationDataMock(x =>
                {
                    x.DataState.Returns(DataState.PA);
                    x.TransmissionType.Returns(DataTransmissionType.Unknown);
                    return x;
                })).SetName("CreateDataTransmitterFactoryTest - PA - Unknown");
        }
    }
}

However, often, I would like to include a test case that throws an Exception. In nUnit 2, it appears that you could just add .Throws(typeof(ArguementException) as an extension method, and the TestCase would look for that.

Now, it appears that nUnit 3 wants you to use "Assert.That(Func..." to test exceptions. In this case, I would have to have a separate test data source for exceptions.

My hack is to pass bool isException, Type type.. into the method and use an if statement to decide if I am using an Assert.That() or Assert.IsInstance(). This seems pretty hacky, but I have not been able to find a better way.

In this case, I am testing to make sure that the resulting factory object throws an Exception if it gets bad data from the factory. The resulting object only has an internal constructor.

How to execute once and expect multiple changes with RSpec?

If I want to test, that an operation produces certain side-effects, how can I execute the operation once and use the change rspec matcher. Example:

expect { some_method }.to change(Foo, :count).by(1)
expect { some_method }.to change(Bar, :count).by(1)
expect { some_method }.to change(Baz, :count).by(1)

How can I execute some_method only once, instead of 3 times?

Or do I need to do something like:

foo_count_before = Foo.count
bar_count_before = Bar.count
baz_count_before = Baz.count

some_method

foo_count_after= Foo.count
bar_count_after= Bar.count
baz_count_after= Baz.count

expect(foo_count_after - foo_count_before).to eq 1
expect(bar_count_after - bar_count_before).to eq 1
expect(baz_count_after - baz_count_before).to eq 1

is laravel cloning my mock object?

Im testing a Soap web service with getMockFromWsdl from phpunit, for unit testing within laravel works fine, but when I try to replace the SoapClient in a feature test, it always fails, like the web service never called, but actually the mock is called.

I suspect that laravel is cloning somewhere my $this->soapClient because if I debug the code, it calls the soap mock and gets what is faked in the mock but always receive the error:

Expectation failed for method name is equal to <string:GetToken> when invoked at least once.
Expected invocation at least once but it never occurred.

My code is like:

public function test_soap_call()
{
    $this->soapClient = $this->getMockFromWsdl(dirname(__FILE__).'/../Mocks/service.wsdl');

    $this->soapClient->expects($this->atLeastOnce())
        ->method('GetToken')
        ->with(['Code' => '03600', 'User' => 'username'])
        ->willReturn(unserialize('O:8:"stdClass":1:{s:26:"GetTokenResult";s:36:"5aae60ec-2bcd-459d-a135-a20eb7c10007";}'));

    $this->app->instance('MySoapClient', $this->soapClient);

    $this->postJson('/api/order', $this->getValidRequest());

}

and in my controller (/api/order) I have

$soap = $this->app->make('MySoapClient');
$soap->GetToken(['Code' => '03600', 'User' => 'username']);

Am I using correctly the Laravel Service Container?

PD: Something similar happened to me, when doing a Spy and using $app->instance, where I was trying to get what was passed to an object, but always got null. I solved it declaring the field of the spy static.

how do I solve this js regex puzzle?

I have to solve this in js and I'm not sure how to approach it . can someone help? I believe the approach here is to use regex, correct?

Please solve this puzzle:\n ABCD\nA--->\nB-=--\nC-<--\nD->--\n

Sending JSON object to a service

I have written a simple service which, if sent the name of a football player, will return the team of said footballer. It's a learning project for myself.

I want to test the accuracy of my service.

I have made a JSON file with a list of footballers and their expected team. I want to send this off to my service and create a report to see how accurate I am.

The JSON looks like this -

{"Team": "Man Utd", "Players": "Ryan Giggs"}
{"Team": "Chelsea", "Players": "John Terry"}
.....

A simple start on my code -

import json
from pprint import pprint

with open('C:\\Users\\ADMIN\\Desktop\\Service_Testing\\service_json.json') as data_file:
    data = json.load(data_file)

pprint(data)

Trying to load it in, however, I get the error -

    raise JSONDecodeError("Extra data", s, end)
json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 47)

What is going wrong here? How can I load my JSON correctly? There are 46k lines in my json file which may be part of the issue !!

Why body match string in postman is passed even string iss not Exits in response?

Following I put in my test to check if ABC string exists or not.

tests["Body matches string"] = responseBody.has("ABC");

so, test pass as ABC was in response now I wanted to test fail so I check

tests["Body matches string"] = responseBody.has("ABC");
tests["Body matches string"] = responseBody.has("XYZ");

but still test pass, how? and if I only check

tests["Body matches string"] = responseBody.has("XYZ");

then it fails.Strange. Is there any way I can check or assert?

Thanks

Get Text from SVG selenium java

I am uable to getText from Text tag in SVG. I am Attaching HTML

<svg width="553" height="200" style="overflow: hidden;" aria-label="A chart.">
     <defs id="defs">
     <rect x="0" y="0" width="553" height="200" stroke="none" stroke-width="0" fill="#ffffff">
     <g>
         <text text-anchor="start" x="77" y="22.85" font-family="Arial" font-size="11" font-weight="bold" stroke="none" stroke-width="0" fill="#000000">Clustering done on Mar 30, 2017 11:13 AM</text>
         <rect x="77" y="13.5" width="400" height="11" stroke="none" stroke-width="0" fill-opacity="0" fill="#ffffff">
     </g>

The get i want to get is Clustering done on Mar 30, 2017 11:13 AM

Ionic 2 : Fail to run Jasmine and Karme test

I try to test my Ionic 2 app with Karma and Jasmine. I try to test a component and I have a lot of errors for one of my tests. I don't understand it and I don't know how to solve it ...

My test file (p-tools.spec.ts) :

import {TestBed, async} from '@angular/core/testing';
import {StatusBar, Splashscreen} from "ionic-native";
import {IonicModule, NavController} from "ionic-angular";
import {MyApp} from "../app/app.component";
import {PTools} from "./p-tools";
import {ToComePage} from "../pages/to-come/to-come";
import {CHeaderComponent} from "../components/c-header/c-header";
import {MedicalEventCardComponent} from "../components/medical-event-card/medical-event-card";
import {PData} from "./p-data";
import {PTranslate} from "./p-translate";
import {IonicStorageModule} from "@ionic/storage";
describe('App', () => {
    let fixture;
    let component;

    beforeEach(async(() => {
        TestBed.configureTestingModule({
            declarations: [MyApp, ToComePage, CHeaderComponent, MedicalEventCardComponent],
            imports: [
                IonicStorageModule.forRoot(MyApp)
            ],
            providers: [
                StatusBar,
                Splashscreen,
                NavController,
                PTools,
                PData,
                PTranslate,
            ]
        })
    }));

    beforeEach(() => {
        fixture = TestBed.createComponent(ToComePage);
        component = fixture.componentInstance;
    });

    it ('should be created', () => {
        expect(component instanceof ToComePage).toBe(true);
    });
});

And there is my console display :

C:\xampp\htdocs\App>npm test

> ionic-hello-world@ test C:\xampp\htdocs\App
> karma start ./test-config/karma.conf.js


webpack: Compiled successfully.
webpack: Compiling...
ts-loader: Using typescript@2.0.9 and C:\xampp\htdocs\App\tsconfig.json
30 03 2017 09:13:22.914:WARN [karma]: No captured browser, open http://localhost:9876/

webpack: Compiled successfully.
30 03 2017 09:13:22.920:INFO [karma]: Karma v1.5.0 server started at http://0.0.0.0:9876/
30 03 2017 09:13:22.920:INFO [launcher]: Launching browser Chrome with unlimited concurrency
30 03 2017 09:13:22.991:INFO [launcher]: Starting browser Chrome
30 03 2017 09:13:26.939:INFO [Chrome 56.0.2924 (Windows 10 0.0.0)]: Connected on socket N3finxHlN66dY3OOAAAA with id 15833092
...Chrome 56.0.2924 (Windows 10 0.0.0) App should be created FAILED
        Error: Template parse errors:
        Can't bind to 'content' since it isn't a known property of 'ion-menu'.
        1. If 'ion-menu' is an Angular component and it has 'content' input, then verify that it is part of this module.
        2. If 'ion-menu' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schemas' of this component to suppress this message.
         ("<ion-menu [ERROR ->][content]="content" side="right">
          <ion-header>
            Menu
        "): MyApp@0:10
        'ion-header' is not a known element:
        1. If 'ion-header' is an Angular component, then verify that it is part of this module.
        2. If 'ion-header' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schemas' of this component to suppress this message. ("<ion-menu [content]="content" side="right">
          [ERROR ->]<ion-header>
            Menu
          </ion-header>
        "): MyApp@1:2
        'ion-content' is not a known element:
        1. If 'ion-content' is an Angular component, then verify that it is part of this module.
        2. If 'ion-content' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schemas' of this component to suppress this message. ("
            Menu
          </ion-header>
          [ERROR ->]<ion-content>
            Menu content
          </ion-content>
        "): MyApp@4:2
        'ion-menu' is not a known element:
        1. If 'ion-menu' is an Angular component, then verify that it is part of this module.
        2. If 'ion-menu' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schemas' of this component to suppress this message. ("[ERROR ->]<ion-menu [content]="content" side="right">
          <ion-header>
            Menu
        "): MyApp@0:0
        Can't bind to 'root' since it isn't a known property of 'ion-nav'.
        1. If 'ion-nav' is an Angular component and it has 'root' input, then verify that it is part of this module.
        2. If 'ion-nav' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schemas' of this component to suppress this message.
         ("
        </ion-menu>
        <ion-nav #content [ERROR ->][root]="rootPage"></ion-nav>
        "): MyApp@9:18
        'ion-nav' is not a known element:
        1. If 'ion-nav' is an Angular component, then verify that it is part of this module.
        2. If 'ion-nav' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schemas' of this component to suppress this message. ("
        </ion-menu>
        [ERROR ->]<ion-nav #content [root]="rootPage"></ion-nav>
        "): MyApp@9:0
            at SyntaxError.BaseError [as constructor] (webpack:///~/@angular/compiler/src/facade/errors.js:27:0 <- karma-test-shim.js:135660:27) [ProxyZone]
            at new SyntaxError (webpack:///~/@angular/compiler/src/util.js:151:0 <- karma-test-shim.js:12662:16) [ProxyZone]
            at TemplateParser.parse (webpack:///~/@angular/compiler/src/template_parser/template_parser.js:140:0 <- karma-test-shim.js:31022:19) [ProxyZone]
            at JitCompiler._compileTemplate (webpack:///~/@angular/compiler/src/jit/compiler.js:362:25 <- karma-test-shim.js:76974:68) [ProxyZone]
            at webpack:///~/@angular/compiler/src/jit/compiler.js:245:47 <- karma-test-shim.js:76857:62 [ProxyZone]
            at Set.forEach (native) [ProxyZone]
            at JitCompiler._compileComponents (webpack:///~/@angular/compiler/src/jit/compiler.js:245:0 <- karma-test-shim.js:76857:19) [ProxyZone]
            at createResult (webpack:///~/@angular/compiler/src/jit/compiler.js:147:0 <- karma-test-shim.js:76759:19) [ProxyZone]
            at JitCompiler._compileModuleAndAllComponents (webpack:///~/@angular/compiler/src/jit/compiler.js:151:0 <- karma-test-shim.js:76763:88) [ProxyZone]
            at JitCompiler.compileModuleAndAllComponentsSync (webpack:///~/@angular/compiler/src/jit/compiler.js:98:0 <- karma-test-shim.js:76710:21) [ProxyZone]
            at TestingCompilerImpl.compileModuleAndAllComponentsSync (webpack:///~/@angular/compiler/bundles/compiler-testing.umd.js:482:0 <- karma-test-shim.js:135326:35) [ProxyZone]
            at TestBed._initIfNeeded (webpack:///~/@angular/core/bundles/core-testing.umd.js:770:0 <- karma-test-shim.js:24096:40) [ProxyZone]
            at TestBed.createComponent (webpack:///~/@angular/core/bundles/core-testing.umd.js:853:0 <- karma-test-shim.js:24179:18) [ProxyZone]
            at Function.TestBed.createComponent (webpack:///~/@angular/core/bundles/core-testing.umd.js:682:0 <- karma-test-shim.js:24008:33) [ProxyZone]
            at Object.<anonymous> (webpack:///src/providers/p-tools.spec.ts:37:26 <- karma-test-shim.js:175730:82) [ProxyZone]
            at ProxyZoneSpec.onInvoke (webpack:///~/zone.js/dist/proxy.js:79:0 <- karma-test-shim.js:130080:39) [ProxyZone]
            at Zone.run (webpack:///~/zone.js/dist/zone.js:113:0 <- karma-test-shim.js:130297:43) [ProxyZone => ProxyZone]
            at Object.<anonymous> (webpack:///~/zone.js/dist/jasmine-patch.js:102:0 <- karma-test-shim.js:129795:34) [ProxyZone]
            at webpack:///~/@angular/core/bundles/core-testing.umd.js:96:0 <- karma-test-shim.js:23422:21 [ProxyZone]
            at AsyncTestZoneSpec.onInvoke (webpack:///~/zone.js/dist/async-test.js:49:0 <- karma-test-shim.js:129385:39) [ProxyZone]
            at ProxyZoneSpec.onInvoke (webpack:///~/zone.js/dist/proxy.js:76:0 <- karma-test-shim.js:130077:39) [ProxyZone]
            at Zone.run (webpack:///~/zone.js/dist/zone.js:113:0 <- karma-test-shim.js:130297:43) [<root> => ProxyZone]
            at AsyncTestZoneSpec._finishCallback (webpack:///~/@angular/core/bundles/core-testing.umd.js:91:0 <- karma-test-shim.js:23417:29) [<root>]
            at webpack:///~/zone.js/dist/async-test.js:38:0 <- karma-test-shim.js:129374:31 [<root>]
            at Zone.runTask (webpack:///~/zone.js/dist/zone.js:151:0 <- karma-test-shim.js:130335:47) [<root> => <root>]
            at ZoneTask.invoke (webpack:///~/zone.js/dist/zone.js:332:0 <- karma-test-shim.js:130516:33) [<root>]
            at data.args.(anonymous function) (webpack:///~/zone.js/dist/zone.js:1149:0 <- karma-test-shim.js:131333:25) [<root>]
        Expected false to be true.
            at Object.<anonymous> (webpack:///src/providers/p-tools.spec.ts:42:48 <- karma-test-shim.js:175734:113) [ProxyZone]
            at ProxyZoneSpec.onInvoke (webpack:///~/zone.js/dist/proxy.js:79:0 <- karma-test-shim.js:130080:39) [ProxyZone]
            at Zone.run (webpack:///~/zone.js/dist/zone.js:113:0 <- karma-test-shim.js:130297:43) [ProxyZone => ProxyZone]
            at Object.<anonymous> (webpack:///~/zone.js/dist/jasmine-patch.js:102:0 <- karma-test-shim.js:129795:34) [ProxyZone]
            at webpack:///~/@angular/core/bundles/core-testing.umd.js:96:0 <- karma-test-shim.js:23422:21 [ProxyZone]
            at AsyncTestZoneSpec.onInvoke (webpack:///~/zone.js/dist/async-test.js:49:0 <- karma-test-shim.js:129385:39) [ProxyZone]
            at ProxyZoneSpec.onInvoke (webpack:///~/zone.js/dist/proxy.js:76:0 <- karma-test-shim.js:130077:39) [ProxyZone]
            at Zone.run (webpack:///~/zone.js/dist/zone.js:113:0 <- karma-test-shim.js:130297:43) [<root> => ProxyZone]
            at AsyncTestZoneSpec._finishCallback (webpack:///~/@angular/core/bundles/core-testing.umd.js:91:0 <- karma-test-shim.js:23417:29) [<root>]
            at webpack:///~/zone.js/dist/async-test.js:38:0 <- karma-test-shim.js:129374:31 [<root>]
            at Zone.runTask (webpack:///~/zone.js/dist/zone.js:151:0 <- karma-test-shim.js:130335:47) [<root> => <root>]
            at ZoneTask.invoke (webpack:///~/zone.js/dist/zone.js:332:0 <- karma-test-shim.js:130516:33) [<root>]
            at data.args.(anonymous function) (webpack:///~/zone.js/dist/zone.js:1149:0 <- karma-test-shim.js:131333:25) [<root>]

Chrome 56.0.2924 (Windows 10 0.0.0) App should be created FAILED
        Error: Template parse errors:
        Can't bind to 'content' since it isn't a known property of 'ion-menu'.
        1. If 'ion-menu' is an Angular component and it has 'content' input, then verify that it is part of this module.
        2. If 'ion-menu' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schemas' of this component to suppress this message.
         ("<ion-menu [ERROR ->][content]="content" side="right">
          <ion-header>
            Menu
        "): MyApp@0:10
        'ion-header' is not a known element:
        1. If 'ion-header' is an Angular component, then verify that it is part of this module.
        2. If 'ion-header' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schemas' of this component to suppress this message. ("<ion-menu [content]="content" side="right">
          [ERROR ->]<ion-header>
            Menu
          </ion-header>
        "): MyApp@1:2
        'ion-content' is not a known element:
        1. If 'ion-content' is an Angular component, then verify that it is part of this module.
        2. If 'ion-content' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schemas' of this component to suppress this message. ("
            Menu
          </ion-header>
          [ERROR ->]<ion-content>
            Menu content
          </ion-content>
        "): MyApp@4:2
        'ion-menu' is not a known element:
        1. If 'ion-menu' is an Angular component, then verify that it is part of this module.
        2. If 'ion-menu' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schemas' of this component to suppress this message. ("[ERROR ->]<ion-menu [content]="content" side="right">
          <ion-header>
            Menu
        "): MyApp@0:0
        Can't bind to 'root' since it isn't a known property of 'ion-nav'.
        1. If 'ion-nav' is an Angular component and it has 'root' input, then verify that it is part of this module.
        2. If 'ion-nav' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schemas' of this component to suppress this message.
         ("
        </ion-menu>
        <ion-nav #content [ERROR ->][root]="rootPage"></ion-nav>
        "): MyApp@9:18
        'ion-nav' is not a known element:
        1. If 'ion-nav' is an Angular component, then verify that it is part of this module.
        2. If 'ion-nav' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schemas' of this component to suppress this message. ("
        </ion-menu>
        [ERROR ->]<ion-nav #content [root]="rootPage"></ion-nav>
        "): MyApp@9:0
            at SyntaxError.BaseError [as constructor] (webpack:///~/@angular/compiler/src/facade/errors.js:27:0 <- karma-test-shim.js:135660:27) [ProxyZone]
            at new SyntaxError (webpack:///~/@angular/compiler/src/util.js:151:0 <- karma-test-shim.js:12662:16) [ProxyZone]
            at TemplateParser.parse (webpack:///~/@angular/compiler/src/template_parser/template_parser.js:140:0 <- karma-test-shim.js:31022:19) [ProxyZone]
            at JitCompiler._compileTemplate (webpack:///~/@angular/compiler/src/jit/compiler.js:362:25 <- karma-test-shim.js:76974:68) [ProxyZone]
            at webpack:///~/@angular/compiler/src/jit/compiler.js:245:47 <- karma-test-shim.js:76857:62 [ProxyZone]
            at Set.forEach (native) [ProxyZone]
            at JitCompiler._compileComponents (webpack:///~/@angular/compiler/src/jit/compiler.js:245:0 <- karma-test-shim.js:76857:19) [ProxyZone]
            at createResult (webpack:///~/@angular/compiler/src/jit/compiler.js:147:0 <- karma-test-shim.js:76759:19) [ProxyZone]
            at JitCompiler._compileModuleAndAllComponents (webpack:///~/@angular/compiler/src/jit/compiler.js:151:0 <- karma-test-shim.js:76763:88) [ProxyZone]
            at JitCompiler.compileModuleAndAllComponentsSync (webpack:///~/@angular/compiler/src/jit/compiler.js:98:0 <- karma-test-shim.js:76710:21) [ProxyZone]
            at TestingCompilerImpl.compileModuleAndAllComponentsSync (webpack:///~/@angular/compiler/bundles/compiler-testing.umd.js:482:0 <- karma-test-shim.js:135326:35) [ProxyZone]
            at TestBed._initIfNeeded (webpack:///~/@angular/core/bundles/core-testing.umd.js:770:0 <- karma-test-shim.js:24096:40) [ProxyZone]
            at TestBed.createComponent (webpack:///~/@angular/core/bundles/core-testing.umd.js:853:0 <- karma-test-shim.js:24179:18) [ProxyZone]
            at Function.TestBed.createComponent (webpack:///~/@angular/core/bundles/core-testing.umd.js:682:0 <- karma-test-shim.js:24008:33) [ProxyZone]
            at Object.<anonymous> (webpack:///src/providers/p-tools.spec.ts:37:26 <- karma-test-shim.js:175730:82) [ProxyZone]
            at ProxyZoneSpec.onInvoke (webpack:///~/zone.js/dist/proxy.js:79:0 <- karma-test-shim.js:130080:39) [ProxyZone]
            at Zone.run (webpack:///~/zone.js/dist/zone.js:113:0 <- karma-test-shim.js:130297:43) [ProxyZone => ProxyZone]
            at Object.<anonymous> (webpack:///~/zone.js/dist/jasmine-patch.js:102:0 <- karma-test-shim.js:129795:34) [ProxyZone]
            at webpack:///~/@angular/core/bundles/core-testing.umd.js:96:0 <- karma-test-shim.js:23422:21 [ProxyZone]
            at AsyncTestZoneSpec.onInvoke (webpack:///~/zone.js/dist/async-test.js:49:0 <- karma-test-shim.js:129385:39) [ProxyZone]
            at ProxyZoneSpec.onInvoke (webpack:///~/zone.js/dist/proxy.js:76:0 <- karma-test-shim.js:130077:39) [ProxyZone]
            at Zone.run (webpack:///~/zone.js/dist/zone.js:113:0 <- karma-test-shim.js:130297:43) [<root> => ProxyZone]
            at AsyncTestZoneSpec._finishCallback (webpack:///~/@angular/core/bundles/core-testing.umd.js:91:0 <- karma-test-shim.js:23417:29) [<root>]
            at webpack:///~/zone.js/dist/async-test.js:38:0 <- karma-test-shim.js:129374:31 [<root>]
            at Zone.runTask (webpack:///~/zone.js/dist/zone.js:151:0 <- karma-test-shim.js:130335:47) [<root> => <root>]
            at ZoneTask.invoke (webpack:///~/zone.js/dist/zone.js:332:0 <- karma-test-shim.js:130516:33) [<root>]
            at data.args.(anonymous function) (webpack:///~/zone.js/dist/zone.js:1149:0 <- karma-test-shim.js:131333:25) [<root>]
        Expected false to be true.
            at Object.<anonymous> (webpack:///src/providers/p-tools.spec.ts:42:48 <- karma-test-shim.js:175734:113) [ProxyZone]
            at ProxyZoneSpec.onInvoke (webpack:///~/zone.js/dist/proxy.js:79:0 <- karma-test-shim.js:130080:39) [ProxyZone]
            at Zone.run (webpack:///~/zone.js/dist/zone.js:113:0 <- karma-test-shim.js:130297:43) [ProxyZone => ProxyZone]
            at Object.<anonymous> (webpack:///~/zone.js/dist/jasmine-patch.js:102:0 <- karma-test-shim.js:129795:34) [ProxyZone]
            at webpack:///~/@angular/core/bundles/core-testing.umd.js:96:0 <- karma-test-shim.js:23422:21 [ProxyZone]
            at AsyncTestZoneSpec.onInvoke (webpack:///~/zone.js/dist/async-test.js:49:0 <- karma-test-shim.js:129385:39) [ProxyZone]
            at ProxyZoneSpec.onInvoke (webpack:///~/zone.js/dist/proxy.js:76:0 <- karma-test-shim.js:130077:39) [ProxyZone]
            at Zone.run (webpack:///~/zone.js/dist/zone.js:113:0 <- karma-test-shim.js:130297:43) [<root> => ProxyZone]
            at AsyncTestZoneSpec._finishCallback (webpack:///~/@angular/core/bundles/core-testing.umd.js:91:0 <- karma-test-shim.js:23417:29) [<root>]
            at webpack:///~/zone.js/dist/async-test.js:38:0 <- karma-test-shim.js:129374:31 [<root>]
            at Zone.runTask (webpack:///~/zone.js/dist/zone.js:151:0 <- karma-test-shim.js:130335:47) [<root> => <root>]
            at ZoneTask.invoke (webpack:///~/zone.js/dist/zone.js:332:0 <- karma-test-shim.js:130516:33) [<root>]
            at data.args.(anonymous function) (webpack:///~/zone.js/dist/zone.js:1149:0 <- karma-test-shim.js:131333:25) [<root>]
Chrome 56.0.2924 (Windows 10 0.0.0): Executed 4 of 4 (1 FAILED) (1.726 secs / 1.329 secs)

My to-come.ts file :

import { Component } from '@angular/core';

import { NavController } from 'ionic-angular';
import {PData} from "../../providers/p-data";
import {DetailsMedicalEventPage} from "../details-medical-event/details-medical-event";
import {PTranslate} from "../../providers/p-translate";
import {PTools} from "../../providers/p-tools";

@Component({
  selector: 'page-to-come',
  templateUrl: 'to-come.html'
})
export class ToComePage {


  constructor(public navCtrl: NavController, public pdata : PData, public translate : PTranslate, public ptools: PTools) {
    this.pdata.getMedicalEvents();
  }

  /**
   * Open a specific medical event page
   * @param guid the guid of the medical event
   */
  openMedicalEvent(guid : string) {
    this.navCtrl.push(DetailsMedicalEventPage);
  }

}

My to-come.html file :

<ion-header>
  <c-header></c-header>
</ion-header>

<ion-content padding>
  <!-- TEMPORAIRE : Ce spinner a pour but d'informer l'utilisateur qu'un chargement est en cours -->
  <div class="alert" *ngIf="this.pdata.spinners['medical_events'] == true">
    <p></p>
    <ion-spinner></ion-spinner>
  </div>
  <div class="alert alert-info" *ngIf="this.pdata.spinners['medical_events'] == false && this.pdata.current_patient.to_come_count === 0">
    
  </div>
  <div *ngFor="let key of this.pdata.keysGetter(this.pdata.medical_events)">
    <medical-event-card
      *ngIf="this.pdata.today < this.ptools.getTime(this.pdata.medical_events[key].date, null, this.translate.i18n)
      && this.pdata.medical_events[key].patient_guid == this.pdata.current_patient.guid"
      [medical_event]="this.pdata.medical_events[key]"></medical-event-card>
  </div>
</ion-content>

I think it's link to Ionic component but I don't know what I have to do to resolve my problem...

Someone had same issues ?

I'm getting NoSuchElement exception error

I have shared the below code please let me know the correction

import org.openqa.selenium.By;
import org.openqa.selenium.ie.InternetExplorerDriver;

public class MyClass {

    public static void main(String[] args) throws InterruptedException {
        // TODO Auto-generated method stub
        /*System.setProperty("webdriver.ie.driver","D:\\Backup\\Documents\\Automation\\drivers\\IEDriverServer.exe");
        InternetExplorerDriver driver = new InternetExplorerDriver();
        driver.get("https://www.google.com");

        WebDriverWait driverWait = new WebDriverWait(driver,50);

        driverWait.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[@id='lst-ib']"))).click();
        driver.findElementByXPath("//*[@id='lst-ib']").sendKeys("Make My Trip");
        driver.findElementById("_fZl").click();
        driverWait.until(ExpectedConditions.elementToBeClickable(By.linkText("MakeMyTrip, India's No 1 Travel Site | Book Hotels, Flights, Holiday ..."))).click();
        Screenshot S1 = new Screenshot();
        S1.Takescreen();*/
        String username = null;
        String password = null;
        MyClass C1 = new MyClass();
        C1.URLs(username, password);
    }

    public void URLs  (String username, String password) throws InterruptedException
    {

        System.setProperty("webdriver.ie.driver","D:\\Backup\\Documents\\Automation\\drivers\\IEDriverServer.exe");
        InternetExplorerDriver driver = new InternetExplorerDriver();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.get("https://google.com");
        driver.findElement(By.className("lst lst-tbb sbibps")).sendKeys("irctc");
        driver.findElement(By.id("_fZl")).click();
        Thread.sleep(10000);
        driver.findElement(By.linkText("IRCTC Next Generation eTicketing System")).click();
        username = driver.findElement(By.id("usernameId")).getTagName();
        password = driver.findElement(By.className("loginPassword")).getTagName();
        System.out.println(username);
        System.out.println(password);           
    }
}

Error :

Exception in thread "main" org.openqa.selenium.NoSuchElementException: Unable to find element with class name == lst lst-tbb sbibps (WARNING: The server did not provide any stacktrace information) Command duration or timeout: 10.45 seconds

Writing Jasmine Test: setTimeout, Modals, events and ajax

I recently wrote a Javascript function that times out the user due to being inactive. My current setTimeout is set for 10 sec for testing purposes. After 10 sec a modal is fired that alerts the user that they have been signed out and directs them to sign back in again. I would now like to write a Jasmine test for this function but I don't know where to start. I've read the docs on jasmine.github.io and I'm still lost. Although my function is small there are a lot of moving parts to test.

My code is below. Any help is greatly appreciated.

App.inactivityTime = function () {
  var t;
$(document).on('mousemove', resetTimer);
$(document).on('keypress', resetTimer);
$(document).ready(resetTimer);

 function logout() {
 $.ajax({
 url: '/users/sign_out',
 type: "DELETE"
}).done(function(){
$('#logoutModal').modal('show');
$('#logoutModal .btn-primary').click(function () {
  window.location.href = '/users/sign_in';
   });
  });
 }

function resetTimer() {
 clearTimeout(t);
t = setTimeout(logout, 10000);
 }
}
 $(function() {
if (window.location.pathname !== '/users/sign_in') {
  App.inactivityTime();
 }
});

mercredi 29 mars 2017

Recommended Pen Testing companies

I'm looking for recommendations for a group that could pen test my web app for a potential client who is requesting a 3rd party pen test.

Using Espresso with Embedded Toolbar

I have the following list item that is used within a RecyclerView that has a vertical LinearLayout Manager. I am using espresso, and I would like to simulate clicking the id/action_save menu item. Below is my latest attempts at figuring this one out. I have tried using onData method combined with onChildView, but a MenuItem is not a View. The onView and withId methods works well if the menu item is located in a toolbar that is in the action bar, but while being embedded inside of a RecyclerView.

List Item

<android.support.v7.widget.CardView xmlns:android="http://ift.tt/nIICcg"
    xmlns:app="http://ift.tt/GEGVYd"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:cardCornerRadius="0dp"
    app:cardUseCompatPadding="true">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <android.support.v7.widget.Toolbar 
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/colorPrimaryDark"
            android:elevation="4dp"
            android:minHeight="?attr/actionBarSize"
            app:popupTheme="@style/MyDarkToolbarStyle"
            app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" />


        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1">

            <ProgressBar
                android:id="@+id/progress"
                style="@style/Widget.AppCompat.ProgressBar"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerInParent="true"
                android:indeterminate="true" />

            <android.support.v7.widget.AppCompatImageView
                android:id="@+id/imgPalette"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:minHeight="250dp" />
        </RelativeLayout>

        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:layout_marginTop="-2dp"
            android:elevation="4dp"
            android:outlineProvider="bounds"
            android:paddingTop="2dp">
            <FrameLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="@color/colorPrimaryDark">

                <android.support.v7.widget.RecyclerView
                    android:id="@+id/recyclerView"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent" />
            </FrameLayout>
        </FrameLayout>
    </LinearLayout>
</android.support.v7.widget.CardView>

Menu

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://ift.tt/nIICcg"
xmlns:app="http://ift.tt/GEGVYd">
    <item
       android:id="@+id/action_save"
       android:title="@string/save"
       app:showAsAction="never" />
</menu>

Main Layout

 <RelativeLayout xmlns:android="http://ift.tt/nIICcg"
    xmlns:app="http://ift.tt/GEGVYd"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    ...
    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/banner" />
    ...
    </RelativeLayout>

Java (Espresso / JUnit Test Case)

...
// mProducts is a list that is backed by the adapter and is of Type Product
for (int i = 0; i < mProducts.size(); i++) {
        onView(allOf(withId(R.id.recyclerView), withParent(withId(R.id.container))))
                .perform(actionOnItemAtPosition(i, clickOverflow(R.id.toolbar)));

        // Add delay for system to respond to overflow being opened
        SystemClock.sleep(1000);
        onView(withId(R.id.recyclerView)).perform(actionOnItemAtPosition(i, clickMenuItem(R.id.toolbar, R.id.action_save)));
    }
...
public static ViewAction clickMenuItem(final int toolbarId, final int id) {
    return new ViewAction() {
        @Override
        public Matcher<View> getConstraints() {
            return null;
        }

        @Override
        public String getDescription() {
            return "Click on a child view with specified id.";
        }

        @Override
        public void perform(UiController uiController, View view) {
            Toolbar toolbar = (Toolbar) view.findViewById(toolbarId);
            for (int i = 0; i < toolbar.getChildCount(); i++) {
                if (toolbar.getChildAt(i) instanceof ActionMenuView) {
                    ViewGroup viewGroup = ((ViewGroup) toolbar.getChildAt(i));
                    for (int j = 0; j < viewGroup.getChildCount(); j++) {
                        if (viewGroup.getChildAt(j).getId() == id) {
                            viewGroup.getChildAt(j).performClick();
                            break;
                        }
                    }
                }
            }
        }
    };
}


public static ViewAction clickOverflow(final int toolbarId) {
    return new ViewAction() {
        @Override
        public Matcher<View> getConstraints() {
            return null;
        }

        @Override
        public String getDescription() {
            return "Click on a child view with specified id.";
        }

        @Override
        public void perform(UiController uiController, View view) {
            Toolbar toolbar = (Toolbar) view.findViewById(toolbarId);
            ((ViewGroup) toolbar.getChildAt(0)).getChildAt(0).performClick();
        }
    };
}

Error

android.support.test.espresso.NoMatchingViewException: No views in hierarchy found matching: with id: com.variable.inspire:id/recyclerView
If the target view is not part of the view hierarchy, you may need to use Espresso.onData to load it from one of the following AdapterViews:android.support.v7.widget.MenuPopupWindow$MenuDropDownListView{92d26ac VFED.VC.. .F...... 0,0-515,252}

How to create a test which waits for record appearance in the database?

I have a method which starts generating some report in another thread while the main thread returns a link to a google folder where created report should be uploaded. After report was created, it inserts a record with some information in the database.

public Link startReportCreation(ReportRequest reportRequest) {
    Link link = /** some logic **/;
    taskExecutor.execute(() -> {
        /** report creation logic **/
    });
    return link;

So what is the best way to test the info of the inserted record without modifying the startReportCreation method? Does the scheduled lookup is the only approach here?

Jest acceptance test - mapping array inside async?

I am trying to build an array from text in the td's of a table row and trying to find a less clunky way of doing it.

test('Check first row', async() => {
    let firstRow =[];
    firstRow = await page.evaluate(() => $('table tbody tr:first-child td:nth-child(3)').text());
    firstRow += ', ' + await page.evaluate(() => $('table tbody tr:first-child td:nth-child(4)').text());
    firstRow += ', ' + await page.evaluate(() => $('table tbody tr:first-child td:nth-child(5)').text());
    console.log(firstRow);
    // desired result "firstTdText, nextTdText, nextTdText"
  });

"normalize_opts expects a string or a hash" error testing Stripe in Rails

Im trying to create a test for a method that make a charge in a credit card using Stripe, I have set all the Stripe configurations and already got working other tests like "create stripe customer" and "assign bank account" but when I try to create a charge the test show me the next failure:

1) STRIPE API POST /v1/clinics/:id/pay when the event exist pay event
 Failure/Error: @charge = Stripe::Charge.create( charge_attrs, user.secret_key )

 TypeError:
   normalize_opts expects a string or a hash
 # /.rvm/gems/ruby-2.4.0/gems/stripe-1.58.0/lib/stripe/util.rb:203:in `normalize_opts'


Gemfile

gem 'rails', '~> 5.0.1'
gem 'stripe', '~> 1.31'
gem 'stripe-ruby-mock', '~> 2.4.0', :require => 'stripe_mock'


stripe_spec.rb

  RSpec.describe 'STRIPE API', type: :request do
    describe 'POST /v1/events/:id/pay' do
        let!(:events) { create_list(:event, 2) }
        let(:event_id) { events.first.id }

        let!(:users) { create_list(:user, 2) }
        let(:user_id) { users.first.id }

        let(:auth_headers) { users.first.create_new_auth_token }

        let(:stripe_helper) { StripeMock.create_test_helper }

        context 'when the event exist' do
          before {
            StripeMock.start
            card_token = StripeMock.generate_card_token(last4: "9191", exp_year: 2020)

            post "/v1/events/#{event_id}/pay", params: { token: card_token, user_id: user_id } , headers: auth_headers
          }
          after { StripeMock.stop }

          it "pay event" do
            p json
            expect(response).to be_success
          end
        end
    end
end


events_controller

module Api::V1
  class EventsController < ApiController
    #POST events/{id}/pay/{user_id, token}
    def pay
      @event = Event.all.active.find(params[:id])
    # Find the user to pay.
      user = User.find( params[:id] )
      # Charge fee.
      amount = 10
      user.currency = 'USD'
      # Calculate the fee amount that goes to the application.
      fee = (amount * Rails.application.secrets.fee_percentage).to_i
      begin
        charge_attrs = {
          amount: amount,
          currency: user.currency,
          source: params[:token],
          description: "Pickleball Clinic",
          application_fee: fee
        }
        # Use the user-to-be-paid's access token
        # to make the charge directly on their account
        @charge = Stripe::Charge.create( charge_attrs, user.secret_key )

        json_response(@charge)

      rescue Stripe::CardError => e
        @error = e.json_body[:error][:message]
        json_response(@error)
      end        
    end
end


event.rb

class Event < ApplicationRecord
  validates_presence_of :name
  validates_presence_of :description
  validates_presence_of :created_by
  belongs_to  :admin, :class_name => 'User', :foreign_key => 'created_by'
  scope :active, -> { where( is_active: true ) }

  has_many    :event_participants
  has_many    :participants, :through => :event_participants, foreign_key: "participant_id" do
    def active
      where("event_participants.is_active = ?", true)
    end
  end
end


FactoryGirl

FactoryGirl.define do
  factory :event do
    association :admin, factory: :user
    name        { Faker::Lorem.sentence }
    description { Faker::Lorem.paragraphs(2) }
    status      { Faker::Number.between(0,3) }
    fee         { Faker::Number.between(5,10) }

    created_at  { Faker::Date.between(2.days.ago, Date.today) }
    updated_at  { Faker::Date.between(1.days.ago, Date.today) }
    is_active   { 1 }

    association       :location, factory: :location

    after(:create) do |event|
      create_list(:event_participants, 3, event: event)
    end

  end
end

Mocking not able to mock method call

I am trying to mock a call in my test but I am getting a error as its calling the real method than mocking it.

This is my method

public List<SecurityGroup> getAllSecurityGroups() {          
    AmazonEC2 ec2 = configSetter();     
    return awsService.getAllSecurityGroups(ec2);  
}

protected AmazonEC2 configSetter() {

    ProfileCredentialsProvider credentials = new ProfileCredentialsProvider(nonProdProfile);
    ClientConfiguration clientCfg = new ClientConfiguration();
    clientCfg.setProxyHost(this.proxyHost);
    clientCfg.setProxyPort(Integer.valueOf(proxyPort)); 
    clientCfg.setProtocol(Protocol.HTTPS);
    return new AmazonEC2Client(credentials, clientCfg);       

}

Here is my test class

@InjectMocks
    private AwsConfigurationLocal subject;

    @Mock
    private AwsService awsService;

    @Test
    public void TestgetAllSecurityGroups() throws Exception {

        ec2 = Mockito.mock(AmazonEC2Client.class);
        securityGroup = new SecurityGroup();
        List<SecurityGroup> result = Collections.singletonList(securityGroup);
        Mockito.when(awsService.getAllSecurityGroups(ec2)).thenReturn(result);  
        List<SecurityGroup> actual = subject.getAllSecurityGroups();
        assertThat(actual, CoreMatchers.is(equals(result)));   
    }

The test actually calls the protected method configSetter and fails when setting a proxy. Help me understand what I am doing wrong here.

Methods of testing Simplex (Linear Programming) calculation output

I have been tasked with created a web-based machine for solving real-world issues using Linear Programming techniques, specifically at present, Danzig's Simplex Method. With this in mind I've found a rather nifty bit of C++ code that calculates the results, and with some considerable speed even on this particularly low-end machine.

However, I currently have nothing other than the console output itself attesting the result to be anywhere close to the correct solution for the given problem. Which is an issue if people are being asked to trust the result as being indicative of anything significantly more important than that some digits can be made to flash up on a computer screen.

I will spare you from the full details of the entire program, as it's fairly long, but here's the function responsible for taking the data, just for reference:

void Data() {
    double R1, R2;
    char R;
    int I, J;
    printf("\n LINEAR PROGRAMMING\n\n");
    printf(" MAXIMIZE (Y/N) ? "); scanf("%c", &R);
    printf("\n NUMBER OF VARIABLES OF ECONOMIC FUNCTION ? "); scanf("%d", &NV);
    printf("\n NUMBER OF CONSTRAINTS ? "); scanf("%d", &NC);
    if (R == 'Y' || R == 'y')
        R1 = 1.0;
    else
        R1 = -1.0;
    printf("\n INPUT COEFFICIENTS OF ECONOMIC FUNCTION:\n");
    for (J = 1; J <= NV; J++) {
        printf("       #%d ? ", J); scanf("%lf", &R2);
        TS[1][J + 1] = R2 * R1;
    }
    printf("       Right hand side ? "); scanf("%lf", &R2);
    TS[1][1] = R2 * R1;
    for (I = 1; I <= NC; I++) {
        printf("\n CONSTRAINT #%d:\n", I);
        for (J = 1; J <= NV; J++) {
            printf("       #%d ? ", J); scanf("%lf", &R2);
            TS[I + 1][J + 1] = -R2;
        }
        printf("       Right hand side ? "); scanf("%lf", &TS[I + 1][1]);
    }
    printf("\n\n RESULTS:\n\n");
    for (J = 1; J <= NV; J++)  TS[0][J + 1] = J;
    for (I = NV + 1; I <= NV + NC; I++)  TS[I - NV + 1][0] = I;
}

I can also include the pivot table, formulation and optimisation functions if need be.

I would like to ask for specific techniques which might be employed to ensure that, given a set of coefficients and constraints, the C++ program returns the economic function correctly (I'll have to implement additional checking stages later when the data gets output to the web, but I'll cross that bridge when I come to it).

(For reasons of attribution, I note that the above code was created by Jean-Pierre Moreau in 1982. Coincidentally, 1982 happens to be my birth year, but that's probably not important right now.)

Why Faker does not return Datetime Object?

I am doing Laravel Testing and when I use faker->datetime() or faker->dateTime($max = 'now') for created and updated at but it always give me this error?

Error Message '2017-03-29 14:21:48' does not match expected type "object".

'created_at' => $faker->dateTime($max = 'now'),
'updated_at' => $faker->dateTime($max = 'now')

Nightwatch. Parallel running tests in different folders

I have many tests in different folders and want to parallel run it - one browser for one folder.

-tests
 --first_folder
 --second_folder

How can i correct do this?

Angular 2 npm karma testing - use ng-template instead of template

So an angular 2 class I'm testing with karma (trough npm) doesn't run due to this error:

The <template> element is deprecated. Use <ng-template> instead

("[WARNING ->]<template><div class="mat-autocomplete-panel" role="listbox" [id]="id" [ngClass]="_getClassList()" #p"): 
ng:///MdAutocompleteModule/MdAutocomplete.html@0:0'

Only I don't use a template tag in my view, it seems that on a lower level material design is using it.

So how would I go about solving this seeing as I can't adjust MD code, could I maybe surpress it?

The test does not run and throws a ZoneAwareError.

close testing with cherry in R

I must do a close testing in R with library "cherry", I have two hypothesis that I have test with a two teiled test, than in order to test the global hypothesis I have write the follow code: closed(test,hypotheses,alpha=0.05) Error in is(test, "character") : object 'test' not found What can I do? Thank you

How to test javascript code that calls window objects

I have a bit of javascript that is as follows

  if (Notification.permission !== 'granted') {
    return Notification.permission
  } 

When I run mocha tests on some code that uses this function the test fails:

ReferenceError: Notification is not defined

I thought doing:

    sinon.stub(Notification, 'permission')

would make this work but I still get the same error.

How do I prevent this error?

Sequential Touch Actions throws exception

The problem

I'm trying to scroll on an Ionic App. I would like to scroll until an element is visible. To test the procedure, I've written two sequential actions. While testing just the first one is evaluated, the second one throws an exception Support for this gesture is not yet implemented. How do I scroll, like a user would do, untill an element is visible if I cannot repeat actions?

Environment

  • Appium version 1.6.4-beta
  • Desktop OS/version used to run Appium: OSX Sierra
  • Real device or emulator/simulator: iPad Mini

Code To Reproduce Issue

TouchAction action = new TouchAction(this.driver);  
Thread.sleep(5000);  
action.press(150, 150).moveTo(0, 350).release().perform();  
Thread.sleep(10000);  
action.press(150, 150).moveTo(0, 350).release().perform();

How to write database undependent test plan?

I define test cases when I make assertions that are database dependent.

Eg: Expect user with username:testusr password:pws123456 to be able to authenticate

When databases changes test execution report change.

What are the best practices to have database undependent test plan ?

Why to use where clause even when Having can be used for the same purpose?

It is known that Having clause works same as where clause but where clause only works with present table columns and not aggregate columns.

Can we always use Having and is there some specific functionality which where is preferable than having, like performance issues?

mardi 28 mars 2017

Protractor element not clikable at some point? But same element receiving its click event?

I am doing end to end testing using protractor. I am getting an error like Failed: unknown error: Element ... is not clickable at point (919, 241). Other element would receive the click: ...

It seems like error is telling that same element is receiving click event, then why it is not woking. there are no other clickable elements overlapping on it.

What o do in these type of cases?

What is table to table testing?

What is table to table means in QA industry?

Can we conclude a set might not be random by checking its subset?

Set A includes 1000 numbers. I checked that half of the numbers in this set is even.

I extracted subset B from set A as follow: any number in set A which starts with 1 is also in set B. (All numbers in B start with 1).

I checked that more than half of the numbers in set B is even.

Half of the numbers in A are even so should we expect the same for B? But more than half of B is even. So can conclude that set A is not random?

If 60% of B are even, can we still conclude A is not generated random?

How if 70% of B are odd?

Karma-Mocha - How to test method that listens to DOMContentLoaded event

I am writing tests for an internal framework that my company maintains. In it there is a method that is equivalent to jQuery's $(document).ready(handler) method. The method looks like this:

export function $ready(fn) {
    document.readyState === 'complete' ?
        $exec(fn) :
        document.addEventListener('DOMContentLoaded', function() {
            $exec(fn);
        });
}

I would like to be able to write a test that will execute the event listener callback rather than immediately executing fn, however I do not know of a way to get my test to execute before readyState is set to complete, nor do I know of a way to re-trigger the DOMContentLoaded event. Any recommendations would be appreciated.

How to make an Extended Entry Decision Table for Testing

So I need to make a Decision Table to test a bit of code. The code is simple and straight forward but requires two user inputs to determine two proceeding variables. This is why I need to make this more than a binary (true/false) table.

The user is prompted to input total income, this will, in turn, determine which bracket the user falls into. Then the user is prompted to input the amount of dependents, which will determine the final tax. Depending on the income bracket, a switch statement will then set tax = income * [certain percentage]. After this the amount of dependents will determine what percentage of the tax will be removed.

Essentially what I need to know is how to set up my Conditions, Actions, and Rules.

Here is an example of decision table but this one is binary (true/false)

If anyone can help inform me as to what I should do or where I should look, that would be appreciated. I am willing to provide anymore information if need be!

Thanks!

Code coverage in SimpleTest

Is there any way to generate code coverage report when using SimpleTest similar to PHPUnit.

I have read the documentation of SimpleTest on their website but can not find a clear way on how to do it! I came across this website that says

we can add require_once (dirname(__FILE__).'/coverage.php') to the intended file and it should generate the report, but it did not work!

If there is a helpful website on how to generate code coverage, please share it here.

Thanks alot.

Testing if an event handler has been called when that event handler is an instance method

Using enzyme to test React components, I would like to set an instance method to a mock function so that I can check when it has been called as a result of an event. For example:

class MyComponent extends Component {
  handleClick = e => {
    // ...
  }

  render() {
    return <button onClick={this.handleClick}>Click Me</button>;
  }
}

And the test:

let wrapper = shallow(<MyComponent />);
let mockFn = jest.fn();
wrapper.instance().handleClick = mockFn;
wrapper.simulate('click');
expect(mockFn).toHaveBeenCalled(); // Fails!

Is there any way to solve this? I realize that I can test for possible state changes resulting from the event, but I'd like to be able to test directly whether the event handler was called.

Why adding association mark my model as not valid?

I'm developing a simple weather API in Rails. This API will give the forecast for a given day. The forecast will have hourly data about the wind, temperature, relative humidity, etc.

I have implemented a model for the Forecast. The forecast have an association "has_many" with the other models, for example, the Wind. I have developed the following model for the Wind object:

class Wind < ApplicationRecord
  belongs_to :forecast, foreign_key: true
  validates_presence_of :period
  validates :velocity, numericality: true, allow_blank: true
  validates :direction, length: { maximum: 2 }, allow_blank: true
end

As I am trying to use TDD, I have implemented the following tests (among others):

class WindTest < ActiveSupport::TestCase
  setup do
    @valid_wind = create_valid_wind
    @not_valid_wind = create_not_valid_wind
  end

  test 'valid_wind is valid' do
    assert @valid_wind.valid?
  end

  test 'valid_wind can be persisted' do
    assert @valid_wind.save
    assert @valid_wind.persisted?
  end

  test 'not_valid_wind is not valid' do
    assert_not @not_valid_wind.valid?
  end

  test 'not valid wind cannot be persisted' do
    assert_not @not_valid_wind.save
    assert_not @not_valid_wind.persisted?
  end

  test 'not_valid_wind has error messages for period' do
    assert_not @not_valid_wind.save
    assert_not @not_valid_wind.errors.messages[:period].empty?
  end

  test 'not_valid_wind has error messages for velocity' do
    assert_not @not_valid_wind.save
    assert_not @not_valid_wind.errors.messages[:velocity].empty?
  end

  test 'not_valid_wind has error messages for direction' do
    assert_not @not_valid_wind.save
    assert_not @not_valid_wind.errors.messages[:direction].empty?
  end

  private

  def create_valid_wind
    valid_wind = Wind.new
    valid_wind.direction = 'NO'
    valid_wind.velocity = 2
    valid_wind.period = '00-06'
    valid_wind.forecast_id = forecasts(:one).id
    valid_wind
  end

  def create_not_valid_wind
    not_valid_wind = Wind.new
    not_valid_wind.velocity = 'testNumber'
    not_valid_wind.direction = '123'
    not_valid_wind
  end
end

This bunch of tests was passing before I add the association with forecast:

belongs_to :forecast, foreign_key: true

Indeed, if I remove that line, any test fails. But with that line in the model, the following tests are failing (they are false and the test expects true):

  test 'valid_wind is valid' do
    assert @valid_wind.valid?
  end

  test 'valid_wind can be persisted' do
    assert @valid_wind.save
    assert @valid_wind.persisted?
  end

I am trying to understand why this is happening. Anyone knows why those tests are failing? Also, is there any proper way to test associations?

Thank you in advance.

Node.js: how to use proxyquire for replacing neo4j-driver dependency

I must have some fundamental problem understanding of how proxyquire works or doing something wrong.

For a proof of concept I have this original code connecting to neo4j graphnedb in node.js:

// I am lib/neo4j.js    
var neo4j = require('neo4j-driver').v1;

var graphenedbURL = process.env.GRAPHENEDB_BOLT_URL;
var graphenedbUser = process.env.GRAPHENEDB_BOLT_USER;
var graphenedbPass = process.env.GRAPHENEDB_BOLT_PASSWORD;

var driver = neo4j.driver(graphenedbURL, neo4j.auth.basic(graphenedbUser, graphenedbPass));

Then I have this test:

// I am test/neo4j.test.js
'use strict';
const test = require('tap').test;
const proxy = require('proxyquire');
const sinon = require('sinon');

test('Testing connection to Neo4j', (assert) => {
    const driverStub = sinon.stub();
    const testedModule = proxy('../lib/neo4j', {
         'neo4j': {
            'driver': driverStub,
          },
      });
});

Test is run as npm tap test/*.test.js --conv

Because npm does not provide access to .env for heroku graphnedb the driver won't have any process.env connection variables which should be ok since my expectation is that proxyquire will replace the driver with above defined stub but that's not happening and the test fails on neo4j.driver missing graphnedebURL. What am I doing wrong please?

Test case will only work for one loop

My code does what i want for the first iteration but then when it gets to the "id=username" line it crashes with the errors: [error] modifyWindow: Window was closed! [error] Current window or frame is closed!

I dont understand becuase it works right off the bat for the first iteration and there isnt a frame on this page.

<tr>
    <td>open</td>
    <td>/workforce/Desktop.do</td>
    <td></td>
</tr>
<tr>
    <td>readCSV</td>
    <td>file://D:/Users/user/Desktop/CAON00015.csv</td>
    <td></td>
</tr>
<tr>
    <td>store</td>
    <td>2</td>
    <td>x</td>
</tr>
<tr>
    <td>while</td>
    <td>(${x}&lt;1077)</td>
    <td></td>
</tr>
<tr>
    <td>storeCellValue</td>
    <td>id</td>
    <td>${x}, 1</td>
</tr>
<tr>
    <td>echo</td>
    <td>${id}</td>
    <td></td>
</tr>
<tr>
    <td>type</td>
    <td>id=username</td>
    <td>${id}</td>
</tr>
<tr>
    <td>type</td>
    <td>id=password</td>
    <td>asda</td>
</tr>
<tr>
    <td>clickAndWait</td>
    <td>name=Submit</td>
    <td></td>
</tr>
<tr>
    <td>type</td>
    <td>id=username</td>
    <td>${id}</td>
</tr>
<tr>
    <td>type</td>
    <td>id=password</td>
    <td>sdada</td>
</tr>
<tr>
    <td>clickAndWait</td>
    <td>name=Submit</td>
    <td></td>
</tr>
<tr>
    <td>type</td>
    <td>id=username</td>
    <td>${id}</td>
</tr>
<tr>
    <td>type</td>
    <td>id=password</td>
    <td>aaaaaaaa</td>
</tr>
<tr>
    <td>clickAndWait</td>
    <td>name=Submit</td>
    <td></td>
</tr>
<tr>
    <td>type</td>
    <td>id=username</td>
    <td>${id}</td>
</tr>
<tr>
    <td>type</td>
    <td>id=password</td>
    <td>asda</td>
</tr>
<tr>
    <td>clickAndWait</td>
    <td>name=Submit</td>
    <td></td>
</tr>
<tr>
    <td>type</td>
    <td>id=username</td>
    <td>${id}</td>
</tr>
<tr>
    <td>type</td>
    <td>id=password</td>
    <td>aaaaaaaaa</td>
</tr>
<tr>
    <td>clickAndWait</td>
    <td>name=Submit</td>
    <td></td>
</tr>
<tr>
    <td>type</td>
    <td>id=username</td>
    <td>SuperUser</td>
</tr>
<tr>
    <td>type</td>
    <td>id=password</td>
    <td>Password1</td>
</tr>
<tr>
    <td>clickAndWait</td>
    <td>name=Submit</td>
    <td></td>
</tr>
<tr>
    <td>selectFrame</td>
    <td>EntryFrame</td>
    <td></td>
</tr>
<tr>
    <td>clickAndWait</td>
    <td>id=ext-gen80</td>
    <td></td>
</tr>
<tr>
    <td>selectWindow</td>
    <td>name=mainFrame</td>
    <td></td>
</tr>
<tr>
    <td>type</td>
    <td>id=ext-comp-1021</td>
    <td>${id}</td>
</tr>
<tr>
    <td>click</td>
    <td>id=ext-gen21</td>
    <td></td>
</tr>
<tr>
    <td>click</td>
    <td>css=button.resetPasswordButton</td>
    <td></td>
</tr>
<tr>
    <td>click</td>
    <td>//table[@id='ext-comp-1038']/tbody/tr[2]/td[2]/em</td>
    <td></td>
</tr>
<tr>
    <td>storeEval</td>
    <td>storedVars['x'] = ${x}+1</td>
    <td></td>
</tr>
<tr>
    <td>open</td>
    <td>/workforce/Desktop.do</td>
    <td></td>
</tr>
<tr>
    <td>endWhile</td>
    <td></td>
    <td></td>
</tr>