mercredi 31 juillet 2019

Test scenario for monthly tasksheet?

Can someone tell me test scenarios for monthly task sheet ?I was asked this question in the last interview, for which I wasn't able to answer.

TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node' in JEST

Hi I am new to Jest and I have a test as follows

test('Description', () => {
    document.body.innerHTML = '<div id=\'holder\'></div>';
    const dynamicData = {
        dialogTitle: 'Testing innderDialog.show() method',
        bodyContent: '<div>sample text</div>'
    };
    const onCloseMock = jest.fn();
    const holder = document.querySelector('#holder');
    console.log(holder.appendChild);
    mymodule.show(dynamicData, document.querySelector('#holder'), onCloseMock, [], window);
});

mymodule's show method is as follows

show (dynamicData, holder, onClose, onCloseArg, onCloseCtx) {
    holder.appendChild(/*generatedHTML*/);
}

This appendChild is throwing error. But when I try the samething in Jest test file it is working.

What am I doing wrong here? Am I missing something?

Postman query to an API endpoint which queries another page- possible to have $_SESSION variables on that second page?

I have been using Postman to query a vanilla PHP API, it has been fine, until $_SESSION variables, or just variables in general come into the mix.

The current project setup uses an AJAX query on the front end to set a method, which is then handled by the PHP API.

Take the example of the method "getcounteddates":

var counteddates = $("#counteddates").DataTable({
  responsive: true,
  ajax: {
    url: "ajax_request.php", //Request the data
    dataSrc: function(json) {
      //var old = JSON.stringify(json).replace(/<br\/>/gi, "\"\<\/td\>\<td\>\""); //convert to JSON string
      //var json1 = JSON.parse(old);
      //alert(JSON.stringify(json1));
      return json.data.result; //Return the required data to the datatable
    },
    serverSide: false, //Prepare for when server side processing is turned on
    type: "POST",
    dataType: "json",
    data: function() {
      var data = { method: "getcounteddates" };
      return data;
    }
  },

This will then hit a giant if/else statement in ajax_request.php:

    } else if ($_POST['method'] == 'getcounteddates') {
        $arr = new stdClass();
        //Get array of ESPs
        if (isset($_POST['data'])) {

            $arr->data = json_decode($web_api->Query('/counteddateslist/', 'GET', json_encode(array('data' => $_POST['data']))));
        } else {
            $arr->data = json_decode($web_api->Query('/counteddateslist/', 'GET'));
        }
        echo json_encode($arr);

$web_api is located in api.php, and using the param "/counteddateslist/", will select the function "counteddatesfetch":

    public function counteddatesfetch($path, $method, $query_string)
    {
        if (isset($_SESSION['case_id'])) {
            $caseid = $_SESSION['case_id'];
        }
        list($q, $error) = $this->dbQuerySafe("SELECT  TO_CHAR(TO_DATE(call_date, 'YYYY-MM-DD HH24:MI:SS'), 'DD-MON-YYYY HH24:MI:SS') call_date,
                    TO_CHAR(TO_DATE(call_date -  30, 'YYYY-MM-DD HH24:MI:SS'), 'DD-MON-YYYY HH24:MI:SS')  min_30,
                    TO_CHAR(TO_DATE(call_date - 60, 'YYYY-MM-DD HH24:MI:SS'), 'DD-MON-YYYY HH24:MI:SS')  min_60,
                    TO_CHAR(TO_DATE(call_date - 90, 'YYYY-MM-DD HH24:MI:SS'), 'DD-MON-YYYY HH24:MI:SS')  min_90,
                    TO_CHAR(TO_DATE(call_date - 365, 'YYYY-MM-DD HH24:MI:SS'), 'DD-MON-YYYY HH24:MI:SS')  min_365
                 FROM caseq
                WHERE case_id = :caseid", 's', array(':caseid' => $caseid));
        if (!$error) {
            return array($q, false);
        } else {
            echo 'Error';
            return array(false, $error);
        }
    }

The problem is setting the $caseid. The postman request comes back with "Undefined variable: caseid in /opt/lampp/htdocs/wam_test/api.php on line 1351"

I have tried several options in postman: Manually setting a "Cookie" header to "caseid=170613418". Either setting the same to Variables or Globals in Postmans' environment quick look options.

I believe the problem may be that the request is being sent to ajax_request.php, which then sends a request to api.php.

Api.php is the file which needs access to the caseid variable, but I feel like manually setting it in Postman only gives ajax_request.php access to that variable. Is there any way around this?

How to handle passing a mutably borrowed struct to function closure?

I am using the proptest crate to run some property tests in a no_std environment doing bare metal development on ARM. proptest's default test_runner::TestRunner::run() impl takes some input (as a Strategy or ValueTree object defined in proptest) and a function closure as parameters so you can run however many tests you want with the values in the value tree or strategy.

My problem is that I need to test a function call that takes as an argument a mutably borrowed struct. This wont compile, and the compilation error that results is:

error[E0596]: cannot borrow `*<obj>` as mutable, as it is a captured variable in a 'Fn' closure

where obj is the struct passed to the test_runner, passed via a function call one level up as a mutably borrowed object.

Digging into the src code for proptest I believe the error is due to the function signature for test_runner::TestRunner::run(), as the test parameter needs to be implemented as FnMut so that captured variables can be mutable in the function call. Here is the function signature for test_runner::TestRunner::run()

pub fn run<S: Strategy>(
        &mut self,
        strategy: &S,
        test: impl Fn(S::Value) -> TestCaseResult,
    ) -> TestRunResult<S> {

As I mentioned above Im doing bare metal development with no_std as prereq. So far I have found that I am unable to get custom test frameworks to work correctly, possibly because I have a main() func defined, but ultimately the main() that is supposedly generated by the feature never is set up and none of the test functions are ever collected. This may be partly because I am using xargo to compile, as it adequately handles the complex linking needs I have which I was unable to get to work using cargo xbuild (at a higher level it seems cargo build is ignoring my linker flag arguments even if i add them to a .cargo/config file)

It is also probably worth noting that I am not able to clone the object because it included metadata with different lifetimes and also objects defined in a third party library that do not implement cloning.

Also relevant background I have only been working with rust for ~6 months and so I know I am probably missing a lot here.

Here is the function passed from a conditionally compiled run func:

fn test_mod(runner: &mut TestRunner, obj: &mut MyObjStruct) -> Result<(), TestError(u32)>>{
    runner.run(&(0x400_0000u32..0xe00_0000u32), |addr| {
        if mod::test::test_page_map(addr, obj).is_ok() {
            Ok(())
        } else {
            Err(TestCaseError::fail(Reason::from("Failed to map address")))
        }
    })
}

Where mod::test::test_page_map takes the obj, uses relevant metadata in the struct, updates that data accordingly, and maps a page to the input address. It returns a result based on whether or not the map succeeded.

Does anyone see a way around this problem that does not involve simply not using proptest? Is there some mechanism available in no_std land like cell or something that I can wrap the mutable object with so it has interior mutability but can be passed as a captured variable to a 'Fn' closure? Or is this something I should implement and submit a PR to the proptest folks for? I suppose I am not completely stuck with proptest, so am also open to any suggestions on other testing frameworks that work in no_std land

How to set FactoryBot to be used by controller when test

Situation:

I can set FactoryBot to register 2 models as follow: When rspec it. It only use FactoryBot called by spec file.But the model that called by one in controller not been use through FactoryBot.

My Question is:

How I can test the with related models using FactoryBot like this situation.

 FactoryBot.define do

     factory :MyTestResults do
         errorCode { 100 }
         resultDesc { "" }
     end

     factory :TestCharts do
         errorCode { 100 }
         resultDesc { "This description from FactoryBot " }
     end

 end

Follow is my spec file to be tested. I code up this test just to ask this issue. 1. Is there any other way to fully test using 2 FactoryBot(models) in spec file and controller.


 # ./spec/factories/My_Work_spec.rb
 require "rails_helper"
 describe WorkerGroup do
   workergroup = WorkerGroup.new
   describe "My Work can do" do

     it "To work result dessc should use same FactoryBot class" do
       my_test_result = FactoryBot.build(:MyTestResults)
       test_charts    = FactoryBot.build(:TestCharts)

       @errorCode     = my_test_result.errorCode

       # Expect workergroup call TestChart using FactoryBot
       # If so should pass the test
       # If not it call TestChart directly
       # The Result ====> Not Pass
       # Why workgroup not use / or how to make it use
       # FactoryBot

       myResultDesc      = workergroup.perform(@errorCode)
       chartResultDesc   = test_charts.resultDesc
       expect(myResultDesc).to eq(chartResultDesc)
     end
   end
 end

This is migration script for model

 rails g model My_Test_Result errCode:int resultDesc:varchar

 rails g model Test_chart errCode:int resultDesc:varchar

In controller or workgroup as follow:

 class WorkerGroup < ActiveJob::Base
     queue_as :hign
     def perform(errorCode)
         if (@testcharts = TestCharts.where(errorCode: errorCode).first)
             @chartResultDesc = @testcharts.resultDesc
         else
            @chartResultDesc = ""
         end
         return @chartResultDesc
     end
 end

The RSpec tested result here:

Failures:

1) WorkerGroup My Work can do To work result dessc should use same FactoryBot class Failure/Error: expect(myResultDesc).to eq(chartResultDesc)

   expected: "This description from FactoryBot "
        got: "This is description from database"

   (compared using ==)
 # ./spec/jobs/My_Work_spec.rb:28:in `block (3 levels) in <top (required)>'

Top 1 slowest examples (1.43 seconds, 98.7% of total time):
WorkerGroup My Work can do To work result dessc should use same FactoryBot class 1.43 seconds ./spec/jobs/My_Work_spec.rb:11

Finished in 1.45 seconds (files took 27.47 seconds to load) 1 example, 1 failure

Failed examples:

rspec ./spec/jobs/My_Work_spec.rb:11 # WorkerGroup My Work can do To work result dessc should use same FactoryBot class

Randomized with seed 42268

How to make Go tests Work with Filesystem

I'm currently experiencing some problems testing my go application with VsCode. This is my launch.json


{
  "name": "Test",
  "type": "go",
  "request": "launch",
  "mode": "test",
  "program": "${workspaceFolder}/test",
  "env": {},
  "args": []
}

Now i have the problem that my application is supposed to write files in a subfolder (atm it's ./temp). To do this i have 2 functions the first one is to determine the filepath

func getFilePath() string {
    dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
    if err != nil {
        panic(err)
    }
    return dir + "/temp/ocicd-config.yaml"
}


and another one to Save the file

func SaveToYaml(Config Structs.Project) {
    fmt.Println("Saving Config")
    yaml, err := yaml.Marshal(Config)
    if err != nil {
        panic(err)
    }
    fmt.Println(string(yaml))
    ioutil.WriteFile(getFilePath(), yaml, 0644)
}

as well as to load the file

func Load() Structs.Project {
    fmt.Println("Loading Config")
    file, err := ioutil.ReadFile(getFilePath())
    if err != nil {
        panic(err)
    }
    project := Structs.Project{}
    err = yaml.Unmarshal(file, &project)
    if err != nil {
        panic(err)
    }
    return project
}

Now the problem is that VsCode makes the application run in the ./test subfolder which makes my application try to load from and save to ./test/temp which is not what i want. I tried to change my launch.json to actually use ${workspace} as program and use "./test" as an argument but that makes the tests stop working alltogether. Now I am pretty lost. Any ideas how I could solve this problem?

What is the best way to generate sql query using java from ETL mapping document

I am trying to automate ETL mapping validation using Java. I have to validate a number of interfaces each with one mapping document which has source and target mapping.

My approach was to read source and target tables and fields information, build the query and compare the both data sets.But this approach is becoming very complex when i have to join multiple tables with different combinations.

Is there any better approach to automate this validation, please suggest?

How can I run all Unit Tests from the test directory with Python? (structured packages)

I set up my project in IntelliJ IDEA (or PyCharm) like this:

project_root
  + src
    + business
      - production_code.py (has a random class I want to test)
  + test
    + business
      - test_production_code.py (using unittest module)

I tried multiple solutions I found online, but unfortunately none of them allow me to run all of the tests inside test directory and its subdirectories, without adding __init__.py everywhere (I'd like to avoid that) or changing sources or changing the configured directory structure.

Note that using pytest actually allows me to find all the tests and run them, but then the imports fail. Looks like none of the classes/modules from src could be found from the test directory - I'm guessing because by default src is not added to the test path.

Also note that my tests run fine from the IDE, but I noticed that IntelliJ somehow seems to add the src directory to the path, so that's probably why it works.

What is the significance of the word Correctness in Software Testing?

There is a fact in Software Testing which says :

Testing is used to find errors in the Software but cannot be used to show the correctness of Software . I am unable to get the significance of the Word Correctness here . Also is it true that Correctness is impossible to achieve in a Software ?

Zenject Mono Installer not called in Scene tests under some circumstances

I have a "Main" scene consisting of a softozor game object which is controlled by the player. It's a flappy dinosaur. As a child of that softozor game object, I have setup another game object, Installer, consisting of a Transform component and a PlayerInstaller (Script) component:

image

The PlayerInstaller installs everything necessary for my player's logic. Finally, in the softozor game object, I have added a Game Object Context (Script) where I register the PlayerInstaller:

image

In addition to the softozor game object, I have also defined a SceneContext:

image

You'll notice that all installers lists are empty in that SceneContext. However, without that SceneContext registering nothing, the PlayerInstaller is not triggered. Playing the game with that setup works perfectly well, i.e. the PlayerInstaller is called and I can control my dinosaur to do whatever I want in my game.

So far, so good. Now, consider the following Scene Test:

public class PlayerTests : SceneTestFixture
{
  [Inject]
  private IPlayer _player;

  [UnityTest]
  public IEnumerator TestScene()
  {
    yield return LoadScene("Main");

    _player.Flap();
    yield return new WaitForSeconds(0.01f);
    [...]
  }
}

In that test, the _player member variable is not injected with an object satisfying the IPlayer contract. In fact, the PlayerInstaller.InstallBindings() is not called.

If I, instead, get rid of the Game Object Context (Script) component in my softozor game object, and register the PlayerInstaller in the SceneContext:

image

then I can play the game too, as before, and my test is running, i.e. the PlayerInstaller.InstallBindings() method is called during my Scene Test.

What is wrong with my first attempt where I register the PlayerInstaller in the softozor game object context?

I am working with

  • Zenject ver. 7.3.1
  • Unity 2019.1.8f1 PC, Mac & Linux Standalone

mardi 30 juillet 2019

Widget tests in Flutter work individually but not all together

Hello everyone and thank you already for your time.

I'm trying to run tests on my widgets. Most of my tests work but the first widget test I wrote that need to get a context with mocked providers fails runned together. But if I run them individually, it works well.

I suppose some things in my context don't reset well or it feels like it doesn't have time to rebuild correctly my widget to test it. I tried to make a variable used in each test containing my context. I tried then to tear it down but nothing solved my problem.

utils.dart

class MockThemeProvider extends Mock implements ThemeProvider {}

Widget getMainContext({Widget child, AuthService authService}) {
  AppTranslationsDelegate _newLocaleDelegate =
      AppTranslationsDelegate(newLocale: Locale('fr', ''));

  var _env = Env(
    apiUrl: 'http://url_lynou_test.com',
    deviceId: 1,
    accessTokenKey: 'accessTokenKey',
    refreshTokenKey: 'refreshTokenKey',
    expiresInKey: 'expiresInKey',
  );

  // add Services or Mocked services
  var _authService = authService == null ? AuthService(env: _env) : authService;

  return MultiProvider(
    providers: [
      Provider<AuthService>.value(
        value: _authService,
      ),
      ChangeNotifierProvider<MockThemeProvider>.value(
        value: MockThemeProvider(),
      ),
    ],
    child: MaterialApp(
      theme: ThemeData(
        primaryColor: Colors.red,
      ),
      localizationsDelegates: [
        _newLocaleDelegate,
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
      ],
      supportedLocales: [
        const Locale('en', ''), // English
        const Locale('fr', ''), // French
      ],
      home: child,
    ),
  );
}

login_screen_test.dart

class MockAuthService extends Mock implements AuthService {
  var env = Env(
    apiUrl: 'http://url_lynou_test.com',
    deviceId: 1,
    accessTokenKey: 'accessTokenKey',
    refreshTokenKey: 'refreshTokenKey',
    expiresInKey: 'expiresInKey',
  );

  // Mock up login
  Future<void> login(String email, String password) async {}
}

void main() {

  testWidgets('LoginScreen - Displaying', (WidgetTester tester) async {
    await tester.pumpWidget(getMainContext(
      child: LoginScreen(),
      authService: MockAuthService(),
    ));
    await tester.pumpAndSettle();

    var findByLoginScreen = find.byType(LoginScreen);
    expect(findByLoginScreen.evaluate().isEmpty, false);
  });

  testWidgets('LoginScreen - Click on login with empty inputs',
      (WidgetTester tester) async {
    await tester.pumpWidget(
      getMainContext(
        child: LoginScreen(),
        authService: MockAuthService(),
      ),
    );
    await tester.pumpAndSettle();

    var findByLoginScreen = find.byType(LoginScreen);
    expect(findByLoginScreen.evaluate().isEmpty, false); // Can't find the Login Screen

    var findByLoginButton = find.byType(RoundedButton);
    expect(findByLoginButton.evaluate().isEmpty, false);
     await tester.tap(findByLoginButton.first);
  });
}

On the second test, it can't even find again my LoginScreen widget when it succeed on the first test with the same code. I don't understand what I'm doing wrong.

For more context, here is my code: https://github.com/Appli-chic/lynou/tree/dev

How to test initializer number of arguments in Ruby

I need to autograde a Ruby exercise , testing with Rspec

The class is pure ruby and I only have to validate attributes (existence and accessibility) and the number of arguments that are received in the initializer

# lib/card.rb
class Card
  attr_reader :number, :suit

  def initialize(number, suit)
    @number = number
    @suit = suit
  end
end

# spec/card_spec.rb
require "spec_helper"
require_relative "../lib/card"

describe Card do
  let(:subject) do
    Card.new(1, "D")
  end

  it { expect(Card).to respond_to(:new).with(4).arguments }
end


➜ rspec spec/card_spec.rb
.

Finished in 0.00431 seconds (files took 0.12135 seconds to load)
1 example, 0 failure

Tests are passing despite the fact that the initializer receives 2 arguments and I specify 4 arguments in my test

Testing with AssertJ if two lists are equal (without order)

I want to test if 2 given lists are equal. They should have the same elements, but the order is no matter. I am trying to do this with assertj and the method containsExactlyInAnyOrder(). The test throws an error and shows me what is expected and what is found and i dont see any difference between them. Can you guys explain me the problem here?

@Test
    void test_getAllCalendarEntriesAsList_shouldBeEqualToCreatedFiles() {
        final List<ICalendar> iCalendarList = new ArrayList<>();
        for (int i = 0; i < 1; i++) {
            final ICalendar sampleICalendar = this.createSampleICalendar();
            iCalendarList.add(sampleICalendar);
        }
        storageManager.saveEntries(iCalendarList);

        final List<ICalendar> allCalendarEntriesAsList = storageManager.getAllCalendarEntriesAsList();
        final ICalendar[] iCalendars = iCalendarList.toArray(new ICalendar[allCalendarEntriesAsList.size()]);
        assertThat(allCalendarEntriesAsList).containsExactlyInAnyOrder(iCalendars);
    }

Message:

java.lang.AssertionError: 
Expecting:
  <[biweekly.ICalendar {version=2.0}
  biweekly.property.ProductId [ parameters={} | value=-//Michael Angstadt//biweekly 0.6.3//EN ]
  biweekly.property.Name [ parameters={} | value=Test name ]
  biweekly.component.VEvent
    biweekly.property.Uid [ parameters={} | value=067463ea-9a36-46d8-bbab-460c550cfd18 ]
    biweekly.property.DateTimeStamp [ parameters={} | value=Wed Jul 31 06:59:00 CEST 2019 ]
    biweekly.property.Summary [ parameters={LANGUAGE=[en-us]} | value=Meeting with Team A ]
    biweekly.property.DateStart [ parameters={} | value=Wed Jul 31 00:00:00 CEST 2019 ]
    biweekly.property.DurationProperty [ parameters={} | value=PT1H ]
]>
to contain exactly in any order:
  <[biweekly.ICalendar {version=2.0}
  biweekly.property.ProductId [ parameters={} | value=-//Michael Angstadt//biweekly 0.6.3//EN ]
  biweekly.property.Name [ parameters={} | value=Test name ]
  biweekly.component.VEvent
    biweekly.property.Uid [ parameters={} | value=067463ea-9a36-46d8-bbab-460c550cfd18 ]
    biweekly.property.DateTimeStamp [ parameters={} | value=Wed Jul 31 06:59:00 CEST 2019 ]
    biweekly.property.Summary [ parameters={LANGUAGE=[en-us]} | value=Meeting with Team A ]
    biweekly.property.DateStart [ parameters={} | value=Wed Jul 31 00:00:00 CEST 2019 ]
    biweekly.property.DurationProperty [ parameters={} | value=PT1H ]
]>
elements not found:
  <[biweekly.ICalendar {version=2.0}
  biweekly.property.ProductId [ parameters={} | value=-//Michael Angstadt//biweekly 0.6.3//EN ]
  biweekly.property.Name [ parameters={} | value=Test name ]
  biweekly.component.VEvent
    biweekly.property.Uid [ parameters={} | value=067463ea-9a36-46d8-bbab-460c550cfd18 ]
    biweekly.property.DateTimeStamp [ parameters={} | value=Wed Jul 31 06:59:00 CEST 2019 ]
    biweekly.property.Summary [ parameters={LANGUAGE=[en-us]} | value=Meeting with Team A ]
    biweekly.property.DateStart [ parameters={} | value=Wed Jul 31 00:00:00 CEST 2019 ]
    biweekly.property.DurationProperty [ parameters={} | value=PT1H ]
]>
and elements not expected:
  <[biweekly.ICalendar {version=2.0}
  biweekly.property.ProductId [ parameters={} | value=-//Michael Angstadt//biweekly 0.6.3//EN ]
  biweekly.property.Name [ parameters={} | value=Test name ]
  biweekly.component.VEvent
    biweekly.property.Uid [ parameters={} | value=067463ea-9a36-46d8-bbab-460c550cfd18 ]
    biweekly.property.DateTimeStamp [ parameters={} | value=Wed Jul 31 06:59:00 CEST 2019 ]
    biweekly.property.Summary [ parameters={LANGUAGE=[en-us]} | value=Meeting with Team A ]
    biweekly.property.DateStart [ parameters={} | value=Wed Jul 31 00:00:00 CEST 2019 ]
    biweekly.property.DurationProperty [ parameters={} | value=PT1H ]
]>


    at de.htw.ai.decentralised_calendar.storage.ICalendarStorageManagerTest.test_getAllCalendarEntriesAsList_shouldBeEqualToCreatedFiles(ICalendarStorageManagerTest.java:180)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:567)
    at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:532)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:115)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$6(TestMethodTestDescriptor.java:171)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:72)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:167)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:114)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:59)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$4(NodeTestTask.java:108)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:72)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:98)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:74)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1540)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$4(NodeTestTask.java:112)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:72)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:98)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:74)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1540)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$4(NodeTestTask.java:112)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:72)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:98)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:74)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:220)
    at org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$6(DefaultLauncher.java:188)
    at org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:202)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:181)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:128)
    at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:69)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

Karate json path filter not working when trying to extract elements that meet some filter criteria in API response

I am trying to filter my API response using JSON Path filter using Karate framework to extract a specific value that meets one of the condition using a value from a variable but I am not able to map variable properly, so my filter not working properly. I looked at the documentation and tried multiple ways but couldn't resolve this issue.

Sample response JSON:

  "requestId": "8ehd6-6c32-4766-a253-1c9cdnidc4cec2",
  "searchRefKey": "826879461625",
  "responseStatus": {
    "code": "1",
    "reasonCode": "SUCCESS",
    "message": "Successful Request"
  },
  "passengers": [
    {
      "numOfPax": 5,
      "type": "ADT"
    }
  ],
  "slices": [
    {
      "id": 7591164138534052,
      "duration": {
        "value": 1675,
        "unit": "MINUTE"
      },
      "segments": [
        {
          "id": 1,
          "segmentRefId": 7591164138529651
        },
        {
          "id": 2,
          "segmentRefId": 7591164138531002
        },
        {
          "id": 3,
          "segmentRefId": 7591164138532394
        }
      ]
    }
  ],
  "segments": [
    {
      "id": 23783268357325705,
      "departDateTime": "2019-10-05T19:50:00",
      "arrivalDateTime": "2019-10-06T14:25:00",
      "originAirport": "LAX",
      "destinationAirport": "LHR",
      "duration": {
        "value": 635,
        "unit": "MINUTE"
      },
      "marketingAirline": "BA",
      "operatingAirline": "AA",
      "flightNumber": "1509",
      "equipmentCode": "77W",
      "subjectToGovtApproval": false,
      "numOfStops": 0,
      "stops": []
    }
  ],
  "brands": [],
  "baggageAllowances": [
  ],
  "restrictions": [
  ],
  "trips": []
}```

I am using the below script where I am using variable 'originRefId':

* def originRefId = response.slices[0].segments[0].segmentRefId
* def origin = karate.jsonPath(response, "$.segments[?(@.id=='originRefId')]")
* print 'the value of Origin is:', origin


Expected results  LAX but I am getting an empty array.
17:42:15.119 [main] INFO  com.intuit.karate - [print] the value of Origin is: [
]

How to run k6 tests on amazon cloud

I want to run some load tests but my pc cannot handle more requests than the server. So I would like to run these tests on amazon ecs. Is there a way to run k6 on amazon cloud instead of their loadimpact cloud, if so, how?

VSTS - Run Console Application instead of Unit Test

I'm having trouble finding documentation on how to do this. I have a Class Library project and a Unit Test Project. The Unit Test project tests units of functional code. Amazing, I know. But I also have a Console Application to perform special Integration Tests.

Granted, I could use some frameworks, or even another "Unit Test" project, where I'm not really writing Unit Tests, but hitting third party APIs and such. All I'd have to do is NAME the project "Integration Tests". That's all fine and well, but that's not this question.

My question is, how can I get VSTS to RUN my Console Application and retrieve the output as the Test Results. In running my Console Application, it will perform some integration testing, and output something (I don't care what) to indicate either failure(s), or success.

On Fail or Success, I want VSTS to act just as it would for a Unit Test run.

adding a certain value to Int Array, need optimizing suggestions

I'm a student in my first semester and in my free time and Holidays, I do some java training to keep my mind from rusting...so I downloaded this amazing app and came across the plus One problem and that inspired me to code the plus-Target problem:

Question

Given an Integer Array (non-empty Array) you have to add specific number = target to this array then return an Array to main.

my humble solution: let's assume the following:

int [] x={9,9,9,9}

so, what first came to my mind is that the Elements

  • x[0] represent Mathematically 9000.
  • x[1 ] represent Mathematically 900.
  • x[2] represent Mathematically 90.
  • x[3] represent Mathematically 9.

then turning the array to int by summing 9000+900+90+9.

so now after converting the arrays to number, we can add the target to it. (target can be<0).

After adding the target I had to look upon to scenarios:

  1. if the result is not zero then I convert the int value of temp to string and assign the chars as numbers to a newly made array according to the length of the string minus one.

    2.if the temp is zero which would mean that the target=-9999 in our particular case. so I had to assign each and every element of the forwarded array to zero and then return it.

so now enough talking and here is my code:

private static int [] plusTarget(int[]x,int target){
    int size=x.length;//get the ze of the array
    int toPower=1;//to help set the power of 10..
    int temp=0;//this will have the array value
    char offSet='0';
    String convert=null;
    int []arr=null;
    /*
     * 9000=9*10^4-1
     * where 4 is the size of the forwarded array.
     * and so on...
     */
    for (int i = 0; i < x.length; i++) {
        temp +=x[i]*( Math.pow(10,(size-toPower) ) );
        toPower++;
    }
    System.out.println("the value of the array after turning it to number "+temp);
    temp+=target;
    System.out.println("value after adding target!. "+ temp);

    if(temp!=0){
        convert = Integer.toString(temp);//converting the number to string..
        if (temp>0) {
            arr= new int [convert.length()];
        } else if (temp<0){
            arr= new int [convert.length()-1];//minus one because the string size is more by one because of the minus sign..    
        }

        for (int i = 0; i < arr.length; i++) {
            if (convert.charAt(i)- offSet >0) {
                arr[i]=convert.charAt(i)- offSet;
            }
        }
        if (arr[0]==0) {//if the first emelent is zero then the number is minus..

            for (int i = 0; i < arr.length; i++) {
                if (i+1 != arr.length) {
                    //shifting the elements backwards one step 
                    arr[i]=arr[i+1];
                }
            }
            arr[0]*=-1;//multiplying the first element by -1
        }
        return arr;

    }else{//if (temp+(-target)==0)..then we have to assign zeros to each element of the fowarded array
        for (int i = 0; i < x.length; i++) {
            x[i]=0;
        }
    return x;
    }   
}

tests done:

target=-9999;
output=[0, 0, 0, 0]

target=-19998;
output=[-9, 9, 9, 9]

target=1;
output=[1, 0, 0, 0, 0]

target=-1
output=[9, 9, 9, 8]

I couldn't find any bugs. I might have made some mistakes unintentionally and that's why I'm posting the code here to get some suggestions from you guys.

Pls, feel free to give me feedback and if you see some mistakes in the code I would love to correct them.

my solution for the one plus problem:

private static int [] plusOne(int[]x){
    int size=x.length;
    int power=1;
    int temp=0;
    for (int i = 0; i < x.length; i++) {
        temp +=x[i]*( Math.pow(10,(size-power) ) );
        power++;
    }
    System.out.println("the value of the array after turning it to number "+temp);
    temp++;
    System.out.println("temp after adding one!. "+ temp);
    String convert = Integer.toString(temp);//converting the number to string..
    int [] arr= new int [convert.length()];
    for (int i = 0; i < convert.length(); i++) {
        arr[i]=(int)(convert.charAt(i)-'0'); 
    }
    return arr;
}

the app solution for the plus One case:

private static int [] app (int[]x){
    int n=x.length;
    for(int i=n-1;i>=0;i--){
        if (x[i]<9) {
            x[i]++;
            return x;
        }
        x[i]=0;
    }
    int [] newNumber= new int[n+1];
    newNumber[0]=1;
    return newNumber;
}

please evalute my solution for the plus one problem vs the app solution as well. there is no solution for the plus-Target problem thus it came across my mind after finishing the plus-one exercise.

thanks in advance.

Save complete rendered web page's entire DOM and CSS styles only

I have a need to write tests against a rendered web page. However, getting to the testable screen takes very complicated steps. These include:

  • Logging in
  • Clicking in many different places in certain ways

I considered headless browser solutions like puppeteer or selenium but these will blow up the complexity of tests too much.

Is there a way for me to manually perform these steps to produce the page to look certain way I want to test in and save only the page's current DOM structure and entire CSS styles rendered? I only need to re-create (using puppeteer or selenium) the DOM and CSS state of that instant in time to repeatedly test different code against it.

How Test Null EventHandler

I have this code to test:

public event EventHandler<IMyEventArgs> MyEventHandler;

private void FireMyEvent => MyEventHandler?.Invoke(this, new MyEventArgs)

the piece of code

MyEventHandler?.Invoke(this, new MyEventArgs) 

it's

if(MyEventHandler != null) MyEventHandler.Invoke(this, MyEventArgs)

Now my problem is:

How I can test "MyEventHandler == null"???

How to test that http.Redirect uses correct redirect uri in Go?

I have a backend in Go that uses the net/http module. I have an endpoint that is meant to redirect using http.Redirect to a provided redirect URI with some generated GET params. I simply want to test using net/http/httptest and testing that my endpoint is redirecting to the proper url.

I have executed the request using ServeHTTP and can verify that it does return the correct status code (303 in this case). I then tried accessing the Request URL to find the most recent URL that was accessed (what I assumed to be the redirect url), but I was unable to access this variable.

w := httptest.NewRecorder()
MyRouterMux().ServeHTTP(w, req)
resp := w.Result()

redirectUrl := resp.Request.URL

In this example, I would expect the redirectUrl variable to contain the url that was redirected to, but instead I receive [signal SIGSEGV: segmentation violation ...]

Any idea what could be going on? I know from manual testing that the endpoint works as intended, but I simply need to prove through the tests that it does.

How to test a function inside a default function of a Worker in Jest?

I have a Javascript file, sortWorker.js, of the following format:

export default () => {

    function sortData (data) {
        //some computation here

        return sortedData
    }

    self.addEventListener ("message", e => {
        postMessage(sortData(e.data))
    })
}

I am trying to test the sortData() function in isolation in Jest, but I am struggling to achieve this. Since this is a worker file, I cannot move sortData outside the export default scope. Could someone please help me with this? Thanks!

Looking for software so I can spin up a quick test site with temp URL based on GIT feature branch

I'm looking for some software (web based ideally) that will allow me to spin up quick clones of my live website(s) for client approval/testing purposes on to a temporary URL. Ideally I'd be able to specify a GIT feature branch to deploy to it so my client only sees the exact features they are approving (as there could be lots of work in progress on the current test site).

As an example: My client wants to see what a new module looks like on mysite.com. Currently I would add the module to my local project and test (wamp), commit to GIT feature branch, push, then create a new staging/test server by dumping/tarring, uploading, creating hosting space, etc etc etc. This is really time consuming and expensive.

I don't even know if anything like this even exists but if it does I'd love to hear about it! Thanks.

How can I reuse a function from a _test file inside another _test.go file? [duplicate]

This question already has an answer here:

I want to reuse a function from a _test.go file inside another one.

I have tried importing the package and accessing the function from there, But it was not possible to use the function.

My project structure is like that:

├── a.go
├── a_test.go      # package a
   ├──b.go
   ├──b_test.go    # package b

I am trying to use a function from b_test.go inside a_test.go file. Isn't it possible to import a function from test files in fo? If it's passible how can I do it?

Reference error when running k6: regeneratorRuntime is not defined

I had k6 up and running, but now every time I try and run a test I am getting this error: ReferenceError: regeneratorRuntime is not defined.

I have tried installing and importing babel, which some people have suggested, but it did not work.

import http from "k6/http";
import { check } from "k6";

async function registerHandlers() {
    const dataForBody = 'client_id=LoadTesting&grant_type=client_credentials&' +
      `scope=${encodeURI('StitchApi')}&` +
      `client_secret=${encodeURI(process.env.REACT_APP_CLIENT_SECRET)}`;
    const messageHeaders = {
      'Content-Type': 'application/x-www-form-urlencoded',
    };
    axios({
      method: 'post',
      url: process.env.REACT_APP_STITCH_AUTH_URL,
      headers: messageHeaders,
      data: dataForBody,
    }).then((response) => {
        return response;
    }).catch((error) =>
      global.console.log('axios error: ', error)
    )
  }
// const queries = JSON.parse(open("./easygraphql-load-tester-queries.json"));
const url = "https://mywebsite.net/Api/GraphQL/";
const authorization = registerHandlers();
console.log("AUTH!!!!!!", authorization);
const payload = JSON.stringify({
    query: `
    {
        student(id: "5asdfasdfasdfasdf") {
        name
        }
    }
    ` });
const params = {
    headers: {
        "authorization": "asdfasdfasdfasdfasdfasdfasdf",
        "content-type": "application/json",
    }
}

export default function () {
    // console.log('query: ', queries);
    let res = http.post(url, payload, params);
    check(res, {
        "status is 200": (r) => r.status === 200,
        "is authenticated": (r) => r.json().authenticated === true,
        "is correct user": (r) => r.json().user === "user",
        "caption is correct": (r) => r.html("h1").text() == "Example Domain",
    });
};

I just want my load testing to work!

locust.io sort tasksets in different files and launch them together

I am starting a project with locust.io and I would like to have the task sets sorted in different files. My intention is that any developer can add a task set and this is used when running locust.io

What is the best way to do it?

For example, I have this directory tree:

main.py:

from some1 import TestSteps1 from some2 import TestSteps2

class NewTestSets1(HttpLocust): task_set = TestSteps1

min_wait = 5000
max_wait = 90000

class NewTestSets2(HttpLocust): task_set = TestSteps2

min_wait = 5000
max_wait = 90000

I can run this locust file and run it. This works as I want but I like avoid need to repeat the same code for each task_set

Nightwatch JS and Microsoft WebDriver for Microsoft Edge

So...

Attempting to get tests running following the Nighwatch.js docs. Followed the instructions to the letter and still no joy.

https://nightwatchjs.org/gettingstarted#microsoft-webdriver

So because Microsoft don't make the .exe available - WebDriver for Microsoft Edge is now a Windows Feature on Demand. To install run the following in an elevated command prompt:

DISM.exe /Online /Add-Capability /CapabilityName:Microsoft.WebDriver~~~~0.0.1.0

My config file nightwatch.json is as Nightwatch.s js docs have told me to configure it:

{
  "test_settings" : {
    "default" : {
      "selenium_port"  : 17556,
      "selenium_host"  : "localhost",
      "default_path_prefix" : "",

      "desiredCapabilities": {
        "browserName": "MicrosoftEdge",
        "acceptSslCerts": true
      }
    }
  }
}

I am running Edge 18.17763 and on the Microsoft docs it states "Microsoft WebDriver for Microsoft Edge (EdgeHTML) versions 18 and 19 is a Windows Feature on Demand which ensures that it’s always up to date automatically and enables some new ways to get Microsoft WebDriver. To get started you will have to enable Developer Mode:"

My tests will not launch when I write the 'nightwatch' command. Please help.

Mock WebSecurity dependencies when testing controllers in Spring

To have fast tests for my controller I want to use @WebMvcTest. I wrote server-side unit tests for the controller (See DemoControllerTests in the demo project). These are basically simple unit tests involving the sliced Spring application context:

@WebMvcTest(DemoController.class)
class DemoControllerTests {

    @Autowired
    private MockMvc mockMvc;

    @Test
    @WithAnonymousUser
    void shouldNotHaveAccessWhenAnonymous() throws Exception {
        this.mockMvc.perform(get("/"))
                .andExpect(status().isUnauthorized());
    }

    @Test
    @WithMockUser(username = "pascal", roles = "USER")
    void shouldHaveAccessWithUserRole() throws Exception {
        this.mockMvc.perform(get("/hello"))
                .andExpect(status().isOk())
                .andExpect(content().string("Hello"));
    }
}

But as soon as is start involving more dependencies in my WebSecurityConfig like the MyUserDetailsService (which itself has a dependency on the UserObjectRepository) the problems start to appear.

@Autowired
public WebSecurityConfig(final MyUserDetailsService myUserDetailsService) {
    this.myUserDetailsService = myUserDetailsService;
}

When I run the tests Spring cannot load the ApplicationContext (NoSuchBeanDefinitionException: No qualifying bean of type 'com.example.demo.MyUserDetailsService' available).

This does make sense when I take a look at the documentation of @WebMvcTest. It says that components, services, and repositories will not be auto-configured. But in the last section, it says that Spring Security will be auto-configured when using this annotation. Additional configuration is available using the @AutoConfigureMockMvc.

From my point of view there nothing special to do and even though I want to set the secure config in @AutoConfigureMockMvc it is enabled by default and deprecated. They mention that the secure property is deprecated since 2.1.0 in favor of Spring Security's testing support. But I cannot find more details about a dedicated Spring Security testing support regarding this topic (i already use @WithMockUser etc. in my tests)

 * <p>
 * Using this annotation will disable full auto-configuration and instead apply only
 * configuration relevant to MVC tests (i.e. {@code @Controller},
 * {@code @ControllerAdvice}, {@code @JsonComponent},
 * {@code Converter}/{@code GenericConverter}, {@code Filter}, {@code WebMvcConfigurer}
 * and {@code HandlerMethodArgumentResolver} beans but not {@code @Component},
 * {@code @Service} or {@code @Repository} beans).
 * <p>
 * By default, tests annotated with {@code @WebMvcTest} will also auto-configure Spring
 * Security and {@link MockMvc} (include support for HtmlUnit WebClient and Selenium
 * WebDriver). For more fine-grained control of MockMVC the
 * {@link AutoConfigureMockMvc @AutoConfigureMockMvc} annotation can be used.
 * <p>

The tests are fine in general. They test the controller methods and their method security configuration. The problems only start to roll in when I add more dependencies and separate classes which I then try to inject in my WebSecurityConfig.

How can I mock these dependencies so that my controller tests are working with a sliced context instead of starting the whole application context with @SpringBootTest?

Here is the demo project that shows the problem: https://github.com/pas2al/spring-playground

How to configure spring boot test in maven multi-module project to scan appropriate multi properties(application.yml)

My project structure is as follows

demo-ecommerce/ ├── HELP.md
├── api
│     ├── api.iml
│     ├── pom.xml
│     └── src
│             ├── main
│             │     ├── java
│             │     │     └── com.demoecommerce.api
│             │     │             ├── ApiApplication.java
│             │     │             └── other sub packages
│             │     └── resources
│             │     └── application.yml
│             └── test
│                     ├── java
│                     │     └── com.demoecommerce.api
│                     │     └── ApiApplicationTests.java
│                     └── resources
│                              └── application-test.yml
├── common
│     ├── common.iml
│     ├── pom.xml
│     └── src
│         ├── main
│         │     ├── java
│         │     │     └── com.demoecommerce
│         │     │     ├── CommonApplication.java
│         │     │     └── Other sub packages
│         │     └── resources
│         │     ├── application-core.yml
│         │     └── messages.properties
│         └── test
│                 └── java
│                 └── com.demoecommerce
│                         └── CommonApplicationTests.java
├── demo-ecommerce.iml
├── mvnw
├── mvnw.cmd
├── pom.xml
└── web
        ├── pom.xml
        ├── src
        │     ├── main
        │     │     ├── java
        │     │     │     └── com.demoecommerce.web
        │     │     │             ├── WebApplication.java
        │     │     │             └── Other sub packages
        │     │     └── resources
        │     │             ├── application.yml
        │     │             ├── static
        │     │             └── templates
        │     └── test
        │     └── java
        │     └── com.demoecommerce.web
        │     └── WebApplicationTests.java
        └── web.iml

api

ApiApplication.java

package com.demoecommerce.api;

@SpringBootApplication(scanBasePackages = {"com.demoecommerce.api","com.demoecommerce"})
public class ApiApplication {
    public static void main(String[] args) {
        SpringApplication.run(ApiApplication.class, args);
    }
}

application.yml in api resources

spring:
  profiles:
    include:
      - core
...

ApiApplicationTests.java

package com.demoecommerce.api;

@RunWith(SpringRunner.class)
@SpringBootTest
@ActiveProfiles("test")
public class ApiApplicationTests {

    @Test
    public void contextLoads() {
    }

}

application-test.yml in test api resources

spring:
  profiles:
    include:
      - core
  datasource:
    username: sa
    password:
    url: jdbc:h2:mem:testdb
    driver-class-name: org.h2.Driver
    hikari.jdbc-url: jdbc:h2:mem:testdb
  jpa:
    properties:
      hibernate:
        dialect: org.hibernate.dialect.H2Dialect

common

CommonApplication.java

package com.demoecommerce;

@SpringBootApplication
@PropertySource(value = {"application-core.yml"})
public class CommonApplication {

    public static void main(String[] args) {
        SpringApplication.run(CommonApplication.class, args);
    }
}

application-core.yml in common

spring:
  profiles:
    active: core
  datasource:
    username: demo
    password: 1234
    url: jdbc:mysql://127.0.0.1:3306/demoecommerce?characterEncoding=UTF-8&serverTimezone=UTC
    driver-class-name: com.mysql.jdbc.Driver

  jpa:
    hibernate:
      ddl-auto: update
    properties:
      .hibernate:
        show_sql: true
      hibernate:
        format_sql: true
        dialect: org.hibernate.dialect.MySQL5InnoDBDialect

logging:
  level:
    org:
      hibernate:
        SQL: DEBUG
        type:
          descriptor:
            sql:
              BasicBinder: TRACE
      springframework:
        security: DEBUG

Error

Run 'ApiApplicationTests'

java.lang.IllegalStateException: Failed to load ApplicationContext

 at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:125)
 at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:108)
 at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:190)
 at org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:132)
 at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:246)
 at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:227)
 at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289)
 at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
 at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:291)
 at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:246)
 at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
 at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
 at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
 at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
 at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
 at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
 at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
 at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
 at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
 at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
 at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
 at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
 at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
 at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
 at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: Failed to parse configuration class [com.demoecommerce.api.ApiApplication]; nested exception is java.io.FileNotFoundException: Could not open ServletContext resource [/application-core.yml]
 at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:181)
 at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:315)
 at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:232)
 at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanDefinitionRegistryPostProcessors(PostProcessorRegistrationDelegate.java:275)
 at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:95)
 at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:705)
 at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:531)
 at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:742)
 at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:389)
 at org.springframework.boot.SpringApplication.run(SpringApplication.java:311)
 at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:119)
 at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:99)
 at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:117)
 ... 24 more
Caused by: java.io.FileNotFoundException: Could not open ServletContext resource [/application-core.yml]
 at org.springframework.web.context.support.ServletContextResource.getInputStream(ServletContextResource.java:158)
 at org.springframework.core.io.support.EncodedResource.getInputStream(EncodedResource.java:159)
 at org.springframework.core.io.support.PropertiesLoaderUtils.fillProperties(PropertiesLoaderUtils.java:99)
 at org.springframework.core.io.support.PropertiesLoaderUtils.fillProperties(PropertiesLoaderUtils.java:73)
 at org.springframework.core.io.support.PropertiesLoaderUtils.loadProperties(PropertiesLoaderUtils.java:59)
 at org.springframework.core.io.support.ResourcePropertySource.<init>(ResourcePropertySource.java:67)
 at org.springframework.core.io.support.DefaultPropertySourceFactory.createPropertySource(DefaultPropertySourceFactory.java:37)
 at org.springframework.context.annotation.ConfigurationClassParser.processPropertySource(ConfigurationClassParser.java:452)
 at org.springframework.context.annotation.ConfigurationClassParser.doProcessConfigurationClass(ConfigurationClassParser.java:271)
 at org.springframework.context.annotation.ConfigurationClassParser.processConfigurationClass(ConfigurationClassParser.java:242)
 at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:191)
 at org.springframework.context.annotation.ConfigurationClassParser.doProcessConfigurationClass(ConfigurationClassParser.java:295)
 at org.springframework.context.annotation.ConfigurationClassParser.processConfigurationClass(ConfigurationClassParser.java:242)
 at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:199)
 at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:167)
 ... 36 more



Run 'ApiApplication' is successfully executed.
However, the error happens above when running 'ApiApplicationTests'. I know that's because ApiApplication finds application-core.yml in [com.demoecommerce.api.ApiApplication] instead of [com.demoecommerce], but I don't know why my application finds it in [com.demoecommerce.api.ApiApplication].

For your infomation, Run 'WebApplication causes the same problem. If you need more info, you can ask me any time.

Thank you so much for reading my question!

JUnit test cases requirement for a java code parsing an XML file

I am new to java testing and I made this code (I'll just show the methods) which parses and XML file and modifies tag values/ attribute values according to user. I have been asked to Write down some JUnit cases for the same but I am unable to understand how. I have tried all the tutorials which has given me a theoretical understanding but they've shown tutorials to make JUnit cases for simple addition subtraction programs and I can't think of any for my code.

/**
 * this  method sets the parser for the current file.
 * @param filepath passed from main method.
 * @exception ParserConfigurationException on invalid XML
 * */
public void loadsDoc() throws ParserConfigurationException{

    DocumentBuilder dBuilder;
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();        
    dBuilder = dbFactory.newDocumentBuilder();
    try {
        this.doc = dBuilder.parse(xmlFile);
    }
    catch(Exception e){
        System.out.println("******* The XML string is not properly formatted ******* " + e);
        System.exit(0);
    }
}

/**
 * This method updates the file to match the modified values.
 * @exception TransformerException
 * 
 * */
public void writeToFile() throws TransformerException{
    doc.getDocumentElement().normalize();
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    DOMSource source = new DOMSource(doc);
    StreamResult result = new StreamResult(xmlFile);
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.transform(source, result);
    System.out.println("XML file updated successfully");
}

/**
 * This method is for modifying the attribute of user specified tag.
 * @param tagname this is the name of the tag user wants to change the attribute value of.
 * @param attribute This is the attribute of the tag that the user wants to change the value of
 * @param value This is the third parameter that is the new value of the attribute.
 * @throws CustomException 
 * */
public void modifyAttribute( String tagName, String attribute, String value) throws TransformerException, CustomException{

    Element element = (Element) doc.getElementsByTagName(tagName).item(0);
    if(element==null){
        throw new CustomException(tagName);
    }
    System.out.println(element.getAttribute(attribute));

    element.setAttribute(attribute, value);
    System.out.println(element.getAttribute(attribute));
    Generic g = new Generic();
    writeToFile();

}

/**
 * This method modifies the values of all user specified tag via its xpath
 * @param String path to the xml tag 
 * @throws CustomException 
 * */
public void modify_via_Xpath(String path, String value) throws XPathExpressionException, TransformerException, CustomException{
     NodeList nodes = (NodeList) xpath.evaluate(path, doc,XPathConstants.NODESET);
     if(nodes.getLength()==0){
         throw new CustomException(path);
     }
            for (int i = 0; i < nodes.getLength(); i++) {
              nodes.item(i).setTextContent(value);
            }
    writeToFile();

}

Problems on testing middleware in Laravel with Clousure $next

I have this middleware on my app that checks the user role for a route:

public function handle($request, Closure $next, ...$roles)
{
   if (in_array($request->user()->rol, $roles)) {
        return $next($request);
   } else {
        return redirect()->action('SecurityController@noAutorizado');
   }
}

And I'm triying to make a test for this middleware (phpUnit):

    public function testUsuarioLogadoPuedeAccederAPantallaUsuarios()
{

    $user = UsuariosTestFixtures::unAsignador();
    $this->actingAs($user);
    $request = Request::create('/usuarios', 'GET');

    $middleware = new CheckRole();
    $response = $middleware->handle($request,Closure $next,$user->getRole(), function () {});
    $this->assertEquals($response, true);

}

But i'm retreiving this error: Argument 2 passed to App\Http\Middleware\CheckRole::handle() must be an instance of Closure, null given

I don't know how I have to pass the "Closure $next" on the $middleware->handle

I've tryed this:

public function testUsuarioLogadoPuedeAccederAPantallaUsuarios(Closure $next){...}

But It returns an error: Too few arguments to function UsuarioControllerTest::testUsuarioLogadoPuedeAccederAPantallaUsuarios(), 0 passed in C:\www\APPS\catsa\vendor\phpunit\phpunit\src\Framework\TestCase.php

What's the solution?

Thanks a lot!

Can we automate Electron app with protractor?

There is a application which is built on top of electron.js acts as desktop application, is automated using protractor due to slight changes Dev team is providing build to QA as .exe file.

So I want to use the existing scripts.

Please let me know if there is any possibility that Electron app can be integrated with protractor framework, if not suggest any other open source tool which can we used to automate Electron app other than Spectron.

Element is not clickable at point(x,y) but other element would recieve the click

I am using java and selenium. I have a pop-up that renders every time I click any button in it and after finishing what I want I click "X" button this exception is thrown: org.openqa.selenium.WebDriverException: unknown error: Element is not clickable at point (834, 307). Other element would receive the click:

The problem here is that the "button" and the "img" refers to the same element("X" button). I am getting the Element by the class name.

I tried to wait some time before the click but it fails and throws the same exception frequently. I tried also to make the click on the "img" but it fails and another exception is thrown: org.openqa.selenium.WebDriverException: unknown error: Element is not clickable at point (834, 307). Other element would receive the click:

How to serve a raw response using httptest.NewServer

I am having a text file that contains a raw HTTP response like the following

HTTP/1.1 200 OK
date: Tue, 30 Jul 2019 07:47:54 GMT
content-type: application/json

["Hello, world"]

I want to use directly on my mock httptest.Server somehow like in the following pseudocode

f, err := os.Open("testdata/http.response")
if err != nil {
    t.Fatal("Failed to open mapping response mock file")
}

ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
     w.WriteRaw(f) 
}))

Right now the best solution I found is to parse the response myself and make the actual w.WriteHeader and w.Write calls manually, but I'm wondering if there is an existing utility that will do this for me

The test does not wait for the input number

I am testing phone number verification.

import { expect } from 'chai';
import chai from 'chai';
import chaiHttp from 'chai-http';
import server from '../../src/index';
import readline from 'readline';

chai.use(chaiHttp);

const setEntryId = utils.getentryIds();
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

describe(`Verification Phone Of Users Test`, () => {
    describe('POST /api/users/verifyp', () => {
        it(`Should pass verification users`, (done) => {
            rl.question('You must enter the code from the SMS:', (code) => {
                chai
                    .request(server)
                    .post('/api/users/verifyp')
                    .send({ 'code': code })
                    .end((err, res) => {
                         expect(res).have.status(200);
                         expect(res.body).have.property('message');
                         expect(res.body.message).to.be.an('string');
                         done();
                     });
                 rl.close();
             });
         });
     });
});

Test run script.

SET NODE_ENV=test && mocha -exit --timeout 10000 --require @babel/registe

The problem is that I get an error.

Error: Timeout of 10000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.

How can I make the test wait until I enter the number?

I understand that I have a time out, but I increased it and he also gave an error.

Need to know how to write down some JUnit cases for XML-parser Java code

I am new to java testing and I made this code (I'll just show the methods) which parses and XML file and modifies tag values/ attribute values according to user. I have been asked to Write down some JUnit cases for the same but I am unable to understand how.

I have tried all the tutorials which has given me a theoretical understanding but they've shown tutorials to make JUnit cases for simple addition subtraction programs and I can't think of any for my code.

/** This method modifies the value of all the tags with the user specified name regardless of order * @param tagname this is the name of the tag user wants to change the value of. * @param value This is the second parameter that is the new value of the tag. * @throws CustomException * */ public void modify_All_Occurences(String tagName, String value) throws TransformerException, ParserConfigurationException, SAXException, SAXParseException, IOException, CustomException {

    boolean occuranceFound = false;      

    Element element = doc.getDocumentElement();

    NodeList list = element.getElementsByTagName(tagName);
    for (int i=0;i<list.getLength() && list != null && list.getLength() > 0;i++) {
        NodeList subList = list.item(i).getChildNodes();

        if (subList != null && subList.getLength() > 0) {
            System.out.println("The value of the tag is :- "+subList.item(0).getNodeValue());
            subList.item(0).setNodeValue(value);
            System.out.println("The updated value of the tag is :- "+subList.item(0).getNodeValue());
            occuranceFound=true;
        }
    }

    if(!occuranceFound){
        throw new CustomException(tagName);
    }

    writeToFile();


}

/*********************************************/

/** This method modifies the values of all user specified tag via its xpath * @param String path to the xml tag * @throws CustomException * */ public void modify_via_Xpath(String path, String value) throws XPathExpressionException, TransformerException, CustomException{ NodeList nodes = (NodeList) xpath.evaluate(path, doc,XPathConstants.NODESET); if(nodes.getLength()==0){ throw new CustomException(path); } for (int i = 0; i < nodes.getLength(); i++) { nodes.item(i).setTextContent(value); } writeToFile();

}

/*********************************************/

/** This method is for modifying the attribute of user specified tag. * @param tagname this is the name of the tag user wants to change the attribute value of. * @param attribute This is the attribute of the tag that the user wants to change the value of * @param value This is the third parameter that is the new value of the attribute. * @throws CustomException * */ public void modifyAttribute( String tagName, String attribute, String value) throws TransformerException, CustomException{

    Element element = (Element) doc.getElementsByTagName(tagName).item(0);
    if(element==null){
        throw new CustomException(tagName);
    }
    System.out.println(element.getAttribute(attribute));

    element.setAttribute(attribute, value);
    System.out.println(element.getAttribute(attribute));
    Generic g = new Generic();
    writeToFile();

}

Rust: Replace function on struct

I have the following code which I'm trying to test. My question is how do I replace the function something that's implemented on B? So that under test B.something does nothing, or returns a specified value?

trait DoSomething {
    fn something(&mut self);
}

struct A {}
struct B {}

impl DoSomething for A {
    fn something(&mut self) {
        println!("doing something on A");
        let mut b = B{};
        b.something();
    }
}

impl DoSomething for B {
    fn something(&mut self) {
        println!("doing something on B");
    }
}

fn main() {
    let mut a = A{};
    a.something();
}

The above code is available in the rust playground

Coming from python I would simply patch.object(b, 'something')

Nigthwatch version 1.1.13 Incomplete API commands

Im having problem executing .refresh, .back and .forward commands. I am using Page object model for Nightwatch Tests and Upon checking Nightwatch api's it lacks the above mentioned api commands so as running test it says error undefined function. My code works well unless I used the api commands i mentioned above i got the same error everytime. I have Already submitted a report on nightwatch github.

lundi 29 juillet 2019

WAL2 json plugin -test_decoding not providing correct formatted results... we want to parse these wal event using java code

WAL2 json plugin -test_decoding not providing correct formatted results... we want to parse these wal event using java code.

some example of WAL event

table public.t1:UPDATE: old-key: id[bigint]:3 name[character varying]:'" value of single quote  ''"'

We are using example

https://jdbc.postgresql.org/documentation/head/replication.html#physical-replication

Can we modify format of test_decoding plugin output to get more details ?

I am having hard time writing Jest test for timer

I am trying to write jest test for react-countdown-now timer. It should be pretty simple, but i am new to jest and i am having hard time writing it.

import React from 'react';
import ReactDOM from 'react-dom';
import Countdown, { zeroPad } from 'react-countdown-now';
import "./TimeOut.scss";
 
const renderer = ({ minutes, seconds, completed }) => {
  return <div><span>{zeroPad(minutes, 2)}:{zeroPad(seconds, 2)}</span></div>;
};

class Timer extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      timeout: props.timeout * 60 * 1000
    };
  }

  render() {
    return (
      <Countdown
        date={Date.now() + this.state.timeout}
        renderer={renderer}/>
    );
  }
}

export default Timer;

Selector cannot find Test Controller

I need to pass the test controller to my Selector. I am new to both Typescript and Testcafe. Below are my files:

Locator.ts :

import {Selector, t} from 'testcafe';

export default class Locators {
    elementWithId(id: string) {
        const element = Selector(id => {
            return document.getElementById(id);
        }, {
            boundTestRun: t
        });
        const boundelement = element(id)
        return boundelement      
    };


};

LoginFlow.ts:

import {t} from 'testcafe';
import Locators from './Locators';

const locate = new Locators()

export default class LoginFlow {
    loginEmail : any;
    loginPassword: any;
    loginButton: any;
    searchBar: any;

    constructor(){
        this.loginEmail = locate.elementWithId('email'); 
        this.loginPassword = locate.elementWithId('password');
        this.loginButton = locate.elementWithId('login');
        this.searchBar = locate.elementWithId('searchinput');
    }

    async loginDispatch() {
        await t
        .setPageLoadTimeout(10000)  // 5 seconds
        .typeText(this.loginEmail, 'email')
        .typeText(this.loginPassword, 'password')
        .click(this.loginButton)
        .expect(this.searchBar)
        .ok()
    }
}

Test.ts:

import {t} from 'testcafe';
import LoginFlow from "./PageObjects/LoginFlow";

const lf = new LoginFlow()
fixture('First UI Test')
    .page('<page_url>');

test("Get Social Compose Page", async (t) => {

    await lf.loginDispatch()

});

The error I am currently getting is : The "boundTestRun" option value is expected to be a test controller.

I have tried to use .with({boundTestRun: t}) where i declare boundelement in Locators.ts but that complains that element(id) is not a function.

Unit test compiled dist Angular component?

So I've been looking at some examples over how people unit test their components. It seems that the tests are never really tested on the dist compiled code which ends up in dist/out-tsc but rather the source code that sits in src.

A lot of the unit tests I see do the following:

import { ExampleComponent } from '../../../client/app/components/example-comp/example.component';

This implies that unit testing is done after for example TypeScript compiling but before compiling the app.

I would like to do a npx ng build and then initiate tests on the compiled code which is generated in the dist/out-tsc directory and have nyc coverage. That way I know that the code I will be deploying has been tested.

I'm starting to get the thought that frontend testing is divided into the following three.

  • Unit test -> Done on src code
  • Integration test -> Done on src code
  • E2E test -> Done on compiled code

Would this assumption be correct?

Can we install external ibraries from test suites in robotframework?

I want to add https://github.com/Legrandgroup/robotframework-modbuslibrary library in my project. I have a test suite modbus_test.robot where I want to use the modbuslibrary. I have already cloned this repository in my project modbus. Structure looks like this:

Modbus 
    -- robotframework-modbuslibrary
    -- modbus_test.robot

Can I write a test suite where it first installs the robotframework-library and then do the import things?

'alt+left' for going to previous page doesn't work with testcafe but works fine manually

I'm trying to go back to the previous page from the existing page from my TestCafe code using:

await t.pressKey('alt+left');

But this doesn't seem to work. There is no change in the page. But manually when I verify in the browser, it seems to work fine.

Could someone help me with this, I want to be able to go back to the previous page using keyboard strokes alone.

How do I import an external library from github in robotframework?

I want to import https://github.com/Legrandgroup/robotframework-modbuslibrary library in my project. I have a test suite modbus_test.robot where I want to use the modbuslibrary. There would be no problem if I just pip installed. I have to do without using pip and yet getting access to all the keywords there. How can I achieve this?

Requirements for software of medical equipment

I search legal acts that establish requirements for medical software development and testing in USA and EU. Does it exist?

How to test a method that uses IEnumberables

I'm trying to test a method that takes in an object that has an IEnumberable property but don't know how to make that work in a test.

I've tried Mocking the property which failed because the object isn't mocked.

The method I want to test looks like:

myMethod(MyObject object)

The object has the property:

public IEnumerable<string> EnumProperty { get; set; }

I'm sure(and hoping) I'm just missing something really obvious.

Jest uncovered lines from the start of the file

Jest coverage report in console shows uncovered lines from the end of the file, which is a bit annoying as usually it makes sense to write tests from the beginning of the file.

I can't seem to find any documentation. Obviously I could look at full coverage reports, but that's not that convenient.

Ideally developer would like to see uncovered lines from file beginning.

How do I import a package defined in src/test directory from inside src/it

I have defined a class that I want to use both for normal unit and integration tests. These are currently located in src/test and src/it. I have defined this class in a package inside src/test. But I cannot figure out how to access it from inside tests defined in `src/it/.

build.sbt is like this:

...
  .configs(IntegrationTest)
  .settings(Defaults.itSettings)
...

React Native Component Blackbox testing

Suppose I am developing a todo React app. I can select one or more to do items, and mark them done by clicking a "done" button.

Internally, this makes an API call to patch said items as done, then gets the items again and sets state to update the UI.

I want to test this using React test utils or something of the like by rendering the component and making assertions against the DOM. I don't want to test whether certain API function calls were called, state was changed etc.

Instead I want to test whether the user-facing UI changed after updating the items as done as a result of the internal state change. How do I do this without actually making API calls, or worse yet doing some kind of mocking madness, given that I'd have to stub the patch, and mock the API call to get all the items. This seems too implementation-focused and brittle.

Yes, child components accept just props and are easy to unit-test, but at some point you have a parent component that has to deal with state.

How to use find.byType matching of List in Flutter widget testing

I want to do widget testing for a Stack. Here is the sample code

final List<Widget> children = [];
final stack = Stack(children: children);
await tester.pumpWidget(Container(child: stack));
...

final stackFinder = find.byWidget(stack);
expect(stackFinder, findsOneWidget);

// children should be in Stack
final childrenFinder = find.descendant(
  of: stackFinder,
  matching: find.byType(children.runtimeType),
);
expect(childrenFinder, findsWidgets);

but get error:

Expected: at least one matching node in the widget tree
  Actual: ?:<zero widgets with type "List<Widget>" that has ancestor(s) with type "Stack"

I try to change matching to matching: find.byType([].runtimeType), or matching: find.byType(List<Widget>), but it doesn't work too.

Do you know how to fix it?

Automation testing related

Why automation testing is necessary? And what kind of automation script can we perform? What we can do if designing and alignment related issues generate? For this, Manual testing is the only option?

In what order does beforeEach and beforeAll execute?

I'm using Jest-Puppeteer to end2end test a Rails application. Before these tests I want to run some seeds and to work DRY I tell the server to go to a certain URL before each test.

// imports

describe("user can", () => {
  // here are some constants

  let page;

  beforeAll(async () => {
    await executeSeed(const1);
    await executeSeed(const2);
    await executeSeed(const3);

    page = await newPrivatePage();
    await login(page);
  });

  beforeEach(async () => {
    await page.goto(baseUrl("/some-route"));
  });

  describe("view some great files", () => {

});


I'd expect the seeds to be executed first, since this is beforeAll and if the first test finishes the beforeEach will be done again, but I can't find it in the documentation of jest (https://jestjs.io/docs/en/api#beforeallfn-timeout)

How to expose/access a data store state within a cypress test in an Angular app?

I'm trying to create some Cypress tests for an Angular 7 application which uses ngrx-store. I was hoping to pre-load some data into the store in order to then test the UI. Unfortunately I am not sure how to directly load the required data into the store, without using a dispatch.

I have managed to expose the store, as described in this example (How to expose/access a data store like Redux within a cypress test?) however I would like to manipulate the state directly without dispatching an action. My guess is I somehow need to set a test-specific initial state for the store/state

Here's what I did so far:

    // in app.component
    if (window.Cypress) {
                // @ts-ignore
                window.__appStore__ = store$;
            }

    // in the test
    cy.window().then(w => {
            console.log(w.__appStore__);
    }

The above works fine. I get the store, but can only manipulate it through its API. What I really want is the state of the the store to manipulate it directly.

Can I use balanced subsample for training and imbalanced for testing?

I am working on classification problem and I have highly imbalanced, but huge data set (I have more than 2mio samples). Now my question is: If I choose subsample of only 15% of the data for training, which is chosen to be balanced, is it OK to use the rest of the samples for testing, even if it is highly imbalanced? Of course I can not look at the accuracy, but some other measure which is taking imbalances into account, e.g. balanced accuracy.

Python Mocking the postgres database

MagicMock name='con.cursor.fetchall' id='a121213312' I want to have value when I call read function

db.py

try:
    con = psycopg2.connect(
                    host="yhvh",
                    database="python_db",
                    user="postgres",
                    password="ichoose",
                    )
except:
    print("Unable to connect database")

# Open a cursor to perform database operation
cur = con.cursor()

def read(con):
    """
    Read data in Database
    """
    print("Read")
    cur = con.cursor()

    # execute the query
    data ="SELECT id, name FROM employees"
    cur.execute(
        data
    )
    # fetchall - returns all entries
    rows = cur.fetchall()

    for r in rows:
        print(f"id {r[0]} name {r[1]}")

    return rows


test_db.py

class TestDb(unittest.TestCase):
    """
    Study
        - Mock and Unittes
    """
    def test_read(self):
        expected = (9, 'jibreel')

        with patch("db.con") as mock_connect:
            mock_con = mock_connect.return_value
            mock_cur = mock_con.cursor.return_value
            mock_cur.fetchall.return_value = expected

            result = db.read(mock_connect)
            print(result)
            self.assertEqual(result, expected)



The error when I test it

AssertionError: MagicMock name='con.cursor.fetchall' id='a121213312' != (9, 'jibreel')

dimanche 28 juillet 2019

How can i get/ mock activity while implementing instrumented tests?

I'm trying to implement a test which requires activity as parameter, and i can't find a way to mock activity.

For example, whenever i need context in a test i usually use:

Context context = InstrumentationRegistry.getInstrumentation().getTargetContext();

But can't find something similar for activity. Any idea?

How to run a load test using Jmeter while Fiddler is running?

I want to execute a load test using Jmeter while Fiddler is recording the transactions that is currently happening. How do I do it? And is it possible to send the fiddler trace log during my jmeter test execution? Thank you.

How to test a library against different Python *patch* versions?

I'm writing a library and want to test against different Python patch versions, like 3.7.1, 3.7.2, etc

I've been using tox for a long time, however, according to this answer, it doesn't really support this kind of usage.

Any suggestions?

How can I properly test my React Native OAuth wrapper component?

I have written a React Native "Auth Portal" component, that links with an existing OAuth portal and handles getting the auth-code from the redirect URI and the subsequent token exchange request. It seems to be working well, but clearly I need to test this assumption, so I am trying to write unit/functional tests. How can I properly do this?

I originally considered extracting the functions used in the two useEffects out into separate, isolated functions and taking, for example, the authCode as an argument instead of from state and mocking this input.

However, I believe a better strategy is to test the component as a whole and just mock the response to the axios post request, comparing that mock to what get's stored in the AsyncStorage, as well as mocking a bad request/response to test the error handling.

Is this a good approach?

import axios from 'axios'
import AsyncStorage from '@react-native-community/async-storage'
import React, { useEffect, useState } from 'react'
import { Linking } from 'react-native'
import InAppBrowser from 'react-native-inappbrowser-reborn'
import { LoadingIndicator } from '../LoadingIndicator'

interface AuthPortalProps {
    client_id: string
    scopes: string[]
    client_secret: string
    redirect_uri: string
    onAuthComplete: () => void
    onError: () => void
}

interface ApiDataResponse {
    token_type: string
    expires_in: number
    access_token: string
    refresh_token: string
}

export const AuthPortal = ({
    client_id,
    scopes,
    client_secret,
    redirect_uri,
    onAuthComplete,
    onError,
}: AuthPortalProps) => {
    const [authCode, setAuthCode] = useState()

    const getAuthCodeFromRedirectUri = async (url: string) => {
        if (url.includes('code=')) {
            const regex = /[^=]+$/g
            const code = url.match(regex)!.toString()

            await setAuthCode(code)
        }
    }

    useEffect(() => {
        const getAuthCode = async () => {
            const url = `https://example.com/auth/?response_type=code&client_id=${client_id}&redirect_uri=${redirect_uri}&scope=${scopes}`

            if (!authCode) {
                try {
                    InAppBrowser.openAuth(url, redirect_uri).then(response => {
                        if (response.type === 'success' && response.url && response.url.includes('code=')) {
                            getAuthCodeFromRedirectUri(response.url)
                            Linking.openURL(redirect_uri)
                        }
                    })
                } catch (error) {
                    console.log('Error: ', error.message)
                    onError()
                }
            }
        }

        getAuthCode()
        return () => {
            InAppBrowser.closeAuth()
        }
    }, [authCode, client_id, onError, redirect_uri, scopes])

    useEffect(() => {
        const getAuthRefreshToken = async () => {
            if (authCode) {
                try {
                    const { data }: { data: ApiDataResponse } = await axios.post(
                        'https://example.com/auth',
                        {
                            grant_type: 'authorization_code',
                            client_id: `${client_id}`,
                            code: `${authCode}`,
                            client_secret: `${client_secret}`,
                            redirect_uri: `${redirect_uri}`,
                        }
                    )

                    await Promise.all([
                        AsyncStorage.setItem('access_token', data.access_token),
                        AsyncStorage.setItem('refresh_token', data.refresh_token),
                    ])
                    setTimeout(() => {
                        onAuthComplete()
                    }, 1000)
                } catch (error) {
                    if (error.response) {
                        console.log('Error: ', error.response)
                    } else if (error.request) {
                        console.log('Error: ', error.request)
                    } else {
                        console.log('Error: ', error.message)
                    }
                    onError()
                }
            }
        }

        getAuthRefreshToken()
    }, [authCode, client_id, client_secret, onAuthComplete, onError, redirect_uri])

    return <LoadingIndicator />
}

How to increase Code Quality & testing as a Freelancer

I'm a self-thought dev and I started learning to code around 2 years ago. I'm already comfortable with documentations, many programming concepts. But I feel lacking in code quality & testing. When I look at some other projects it seems like their code is so simple with less lines, but does the same things that I do in more lines of code.

I'm mostly doing nodejs + reactjs. I took some software construction courses online, but they were mostly talk of concepts with very few examples of them. I'm also not working in a company so getting mentorship from a colleague is not an option.

How do you guys think that a freelancer can increase their code quality & testing?

Where can I learn the best coding practices?

Can you offer me any good open-source projects with high code quality and standards? or some books to dive into?

I appreciate every advice.

angular testing, conflicting component selectors

In an angular application unit test I would like to replace an imported component with a stub-component. I must import the module that defines the component because other components from it are required for the test. Simiar question: How to find which components are conflicting? How can I import all components from a module but some? Like a whitelist or blacklist of components.

TestBed.configureTestingModule({
  imports: [
    FormsModule, 
     /*Contains RichTextBoxComponent with selector 'app-rich-text-box'.
       How to import all components from this module but 'app-rich-text-box'.
     */
    UicompsModule],
  declarations: [ 
    ManageQuestionComponent, 
    /*Contains also a selector 'app-rich-text-box'*/
    StubRichTextBoxComponent],
  providers: [  ],
})
.compileComponents();