lundi 30 septembre 2019

Programatically Testing a Stripe SetupIntent

We're creating some automated testing for SetupIntent API in stripe and would like to set up a progamatic test for it. But I'm stuck at the

handleCardSetup step on the client which associates a payment method with the SetupIntent.

I'd like to be able to associate one of the test payment methods with it, but not sure how that could be done without launching the web client and typing in a test code.

How does one use the test payment methods (eg pm_visa_debit_transferFail) with such a flow?

Need help writing a Unit Test in Django

Good day everybody.

I need to test a view, and I got stuck ( I am a django newbie). I got through all other url and view tests, but I'm really not sure how to write this one.

I tried writing it on my own, I read through the testing docs, I even tried testing this using model_mommy ( but I got a custom HTML field in my models ) which is not supported by mommy. I tried with mommy Recipes, also without luck. I really gotta do this test today, it's a part of a task I was given.

here is the view :

class CommentCreateView(CreateView):

    def get(self, request, *args, **kwargs):
        context = {'form': CommentForm()}
        return render(request, 'news/add_comment_to_article.html', context)

    def post(self, request, *args, **kwargs):
        form = CommentForm(request.POST)
        if form.is_valid():
            article = get_object_or_404(Article, pk=kwargs.get('pk'))
            print(article)
            comment = form.save(commit=False)
            comment.post = article
            comment.save()
            return HttpResponseRedirect(reverse('news:article', kwargs={'article_id': article.pk}))
        else:
            form = CommentForm()
            return render(request, 'news/add_comment_to_article.html', {'form': form})

and here are my models:

class Article(models.Model):
    title = models.CharField('title', max_length=200, blank=True)
    slug = AutoSlugField(populate_from='title', default="",
                         always_update=True, unique=True)
    author = models.CharField('Author', max_length=200, default="")
    description = HTMLField()
    is_published = models.BooleanField(default=False)
    article_text = HTMLField('Article text', default="")
    pub_date = models.DateTimeField(default=datetime.now, blank=True)
    article_category = models.ForeignKey(Category, on_delete="models.CASCADE", blank=True, null=True, default="")
    my_order = models.PositiveIntegerField(default=0, blank=False, null=False)

    class Meta(object):
        ordering = ['my_order']

    def __str__(self):
        print(self.image.all())
        return self.title


class ArticleImages(models.Model):
    article = models.ForeignKey(Article, on_delete="models.CASCADE", related_name="image")
    image = models.ImageField("image")
    my_order = models.PositiveIntegerField(default=0, blank=False, null=False)

    def image_tag(self):
        return mark_safe('<img src="/media/%s" width="150" height="150" />' % (self.image))

    image_tag.short_description = 'Image'

    class Meta(object):
        ordering = ['my_order']

    def __str__(self):
        return self.image.url


class Comment(models.Model):
    post = models.ForeignKey('Article', on_delete=models.CASCADE, related_name='comments')
    author = models.CharField(max_length=200)
    text = models.TextField()
    created_date = models.DateTimeField(default=datetime.now, blank=True)
    approved_comment = models.BooleanField(default=False)

    def approve(self):
        self.approved_comment = True
        self.save()

    def __str__(self):
        return self.text

I would REALLY appreciate someone helping me out here. Thank you, and have a good day !

How to make a @ test annotation out of data provider loop?

I have a data provider with name "name" and to the @Test I am passing this. @DataProvider(name = "TC_001")

@Test(dataProvider = "TC_001")

before this @Test I want to run another @Test which need to run only once . I have given the priority like @Test(priority=0)

@DataProvider(name = "TC_001")

@Test(dataProvider = "TC_001",priority=1) But Still the control goes to the second priority instead of first one

Is there any solution for this ?

How do I fake the return of a built-in method in C# unit test?

I have a public static method that uses an object of Random class to generate an integer. The integer is then made the index of a List. I want to test the logic of the method while having control over what a random object's Next method returns.

public class RandomGenerator
  {

    // a static method which produces a random selection from a List
    public static string GetRandomListMember(List<string> anyStringList)
    {
      Random rand = new Random();
      int randomInt = rand.Next(anyStringList.Count);
      return anyStringList[randomInt];
    }
  }

From my MSTest file:

[TestClass]
  public class RandomGeneratorSpec
  {
    [TestMethod]
    public void GetRandomListMember_ListOfStrings()
    {
      List<string> strings = new List<string> { "red", "yellow", "green" }; 

      Mock<Random> mockRandom = new Mock<Random>();
      mockRandom.Setup(rand => rand.Next(strings.Count)).Returns(() => 2); // 2!

      string result = RandomGenerator.GetRandomListMember(strings);

      Assert.AreEqual("green", result);
    }
  }

I want mockRandom.Next to return 2 every time it runs in this test. Obviously, this isn't the way to do it. I've been searching through examples, but they all seem to utilize methods on the object and with instance methods instead of static methods.

How do I control what a built-in method returns while unit testing a method that utilizes it?

MiniDFSCluster: can't get accessRight of self created directories

I would like to test my code evoking an org.apache.hadoop.hdfs.MiniDFSCluster class example. However at the time I call an example of it I get an error informing me that some file is not to be accessed by the process. I followed a stack trace and during debugging I could understand that I cannot get access to folders named "name1", "name2", those that MiniDFSCluster actually had created at the base directory during instantiating.

I'm trying to run a Scala testSuite test file containing a class invocation from Intellij IDEA 2019.2, Windows 7. Some time before I had the same problem as described at Hadoop Mini Cluster Mock (MiniDFSCluster), but fixed it and faced this one left by last user. I saw there are some more users facing the same problem, but could not extract correct solution: error using miniDFSCluster on windows. Stack trace returned to me is very similar to MiniDFSCluster UnsatisfiedLinkError org.apache.hadoop.io.nativeio.NativeIO$Windows.access0

Also I found some guide advising just to fix locally a method which throws an exception, but it seems awkward. https://www.cs.helsinki.fi/u/jilu/paper/hadoop_on_win.pdf

Here is my test:

val HADOOP_HOME="C:\\Local\\hadoop-common-2.2.0-bin-master"
val conf = new Configuration()
conf.set(MiniDFSCluster.HDFS_MINIDFS_BASEDIR, HADOOP_HOME)
System.setProperty("hadoop.home.dir", HADOOP_HOME)

val builder = new Builder(conf)
builder.build()

What I get as a result is following stack trace:

java.lang.UnsatisfiedLinkError: org.apache.hadoop.io.nativeio.NativeIO$Windows.access0(Ljava/lang/String;I)Z

at org.apache.hadoop.io.nativeio.NativeIO$Windows.access0(Native Method)
at org.apache.hadoop.io.nativeio.NativeIO$Windows.access(NativeIO.java:557)
at org.apache.hadoop.fs.FileUtil.canWrite(FileUtil.java:996)
at org.apache.hadoop.hdfs.server.common.Storage$StorageDirectory.analyzeStorage(Storage.java:490)
at org.apache.hadoop.hdfs.server.namenode.FSImage.recoverStorageDirs(FSImage.java:308)
at org.apache.hadoop.hdfs.server.namenode.FSImage.recoverTransitionRead(FSImage.java:202)

I lust for using this tool to test my code, so please, any info can be provided and any help would be appreciated.

If you are to help with the case - just try instantiate a class in Windows environment and tell me what it will return.

How to "pass" an InSpec control similar to the "skip" command?

Is there anyway inside of an InSpec control to just pass a test, similar to the way the "skip" command works? For one of the audits that I am performing I know that we are compliant, its an audit that requires a document review (so nothing code-wise to test). I want to show that the control has passed and give reasoning instead of just "skipped."

Cross platform unit testing on functions using os.system in Python

I want to write (using pytest preferably) a unit test to determine whether the following function successfully clears the terminal across multiple platforms given an os_name ("nt" or something else like "posix"):

    def clear_terminal(os_name):
        code = os.system('cls' if os_name == 'nt' else 'clear')
        print()  # add padding at top of cleared screen

This is tricky because I currently only have access to a UNIX based platform, and I can't think of a straightforward way to test if giving the os_name as 'nt' will work on a Windows machine.

So far I have the following test (where os_name is a pytest fixture that can be one of "nt" or "posix"):

    def test_clear_terminal(os_name):
        with unittest.mock.patch(target='os.system') as os_system:
            clear_terminal()
            assert os_system.called_once_with(os_name)

The issue I have with that test is that it's really just patching the code I'm testing so it's basically useless! What would a rigorous approach to testing this code be? Would you have to just run the test on multiple different platforms or is there another way?

Frameworks to Auto-testing a Webapp

I´m just getting into a new job, and my mission is to search and implement a framework to test a web app in JS. I don´t know a lot about those frameworks but I found those:

  • Jest
  • Mocha
  • Cypress
  • Selenium

Can you suggest to me if are them good?

PS: Are there any frameworks which use Python to automate the testing? Because I like python it´s most familiar to me than JS.

Thanks!

Actions not working when using online devices with selenium

I am currently automating my tests using kobiton for my online devices. I am having an issue however while trying to swipe the screen using the ios online device.

Im using the same java code that i used for the web automation and it seems to be working for android (although im having issues viewing these sessions to confirm)

Actions action = new Actions(driver);
    action.clickAndHold(first_page_paragraph);
    //you need to release the control from the test
    Thread.sleep(2000);
    //action.moveToElement(second_selection).release();
    action.build().perform();

I keep receiving the following error

org.openqa.selenium.WebDriverException: An unknown server-side error occurred while processing the 
command. Original error: Unhandled endpoint: /session/F900A134-DCC3-424F-A037- 
032986694B66/buttondown -- http://localhost:50207/ with parameters {
wildcards =     (
    "session/F900A134-DCC3-424F-A037-032986694B66/buttondown"
);
} (WARNING: The server did not provide any stacktrace information)

Im only using selenium and dont know how to remedy this

Executing Visual Studio Test Task on Azure Pipelines: DontShowUI to 1 failed due to exception

I am executing the Visual Studio Test Task on Azure Pipelines. The agent runs on a Windows Server 2019 Datacenter, however the tests run within a docker container.

Everything works fine and all tests execute, but I see this warning in the output:

[warning]Updating HKCU\SOFTWARE\Microsoft\Windows\Windows Error Reporting\DontShowUI to 1 failed due to exception : System.NullReferenceException: Object reference not set to an instance of an object.

I had a look into the registry and there is actually no value "DontShowUI" in this path. I tried to add it and set the value to 1, but the warning still appears.

How can I get rid of this warning?

How to check TLS configuration with PHP [on hold]

Sites like Whynopadlock can analyze your site and point out a faulty configuration of your TLS. I would like to integrate such functionality in my PHP application.

Are there libraries of websites that can be used for this purpose? Does anyone have experience doing this?

how to setup a test environment for an IOT based application?

I have to setup the Test environment for my organization(both for manual and automation(Selenium) as well).The application is basically based on IOT technology. Please suggest me how to start with this and what are all the possible way of doing this?

Testing a method which return me Null?

was Testing On One of my method In Controller And i was getting null while i am passing all the value of my object I was Getting AID 0 while i am passing all the values in object. It returns me Null on List Plan,Earning ,Member Info,Earning Response What is the Reason?? Get Method have following Repositories.

public class EarningController : BaseApiController
{
    private readonly IEarningRepository _earningRepository;
    private readonly IPlanRepository _planRepository;
    private readonly IAgentRepository _agentRepository;
    private readonly IPromotionRepository _promotionRepository;

    public EarningController(IEarningRepository earningRepository, IPlanRepository planRepository,
        IAgentRepository agentRepository, IPromotionRepository promotionRepository)
    {
        _earningRepository = earningRepository;
        _planRepository = planRepository;
        _agentRepository = agentRepository;
        _promotionRepository = promotionRepository;
    }

    [HttpGet("Get")]
    public async Task<ActionResult> Get()
    {
        List<Earning> earnings = await _earningRepository.GetProducerEarnings(AId);
        List<Plan> plans = await _planRepository.GetAllAsync();
        List<Promotion> promotions = await _promotionRepository.GetAll();
        //pending refer a friend
        List<MemberInfo> members = await _agentRepository.GetMembers(AId);
        List<EarningResponse> earningResponses = new List<EarningResponse>();

        foreach (var member in members)
        {
            var memberPlan = plans.FirstOrDefault(x => x.Id == member.SubscriptionId);

            if (memberPlan != null)
                member.Subscription = memberPlan;

            var e = earnings.Where(x => x.MemberId == member.Id).ToList();
            if (e.Count > 0)
                earningResponses.Add(new EarningResponse(member, e, promotions));
        }

        ReportResponse reportResponses = new ReportResponse(earningResponses);

        return new JsonContentResult { StatusCode = (int)HttpStatusCode.OK, Content = JsonSerializer.SerializeObject(reportResponses) };
    }
}

Here Is My Test Method Which i was Testing

[TestClass]
public class EarningControllerTest
{
    EarningController _earningController;
    EarningRepository _earningRepository;
    PlanRepository _planRepository;
    AgentRepository _agentRepository;
    PromotionRepository _promotionRepository;

    DbContextOptionsBuilder<AgencyPortalDbContext> builder = new DbContextOptionsBuilder<AgencyPortalDbContext>()
               .EnableSensitiveDataLogging()
               .UseInMemoryDatabase(Guid.NewGuid().ToString());


    [TestMethod]
    public async Task Get()
    {

        using (var context = new AgencyPortalDbContext(builder.Options))
        {
            //Arrange
            var _earningRepository = new Mock<EarningRepository>(context);
            _planRepository = new Mock<PlanRepository>(context).Object;
            _agentRepository = new Mock<AgentRepository>(context).Object;
            _promotionRepository = new Mock<PromotionRepository>(context).Object;

            var httpContext = new DefaultHttpContext();
            httpContext.Request.Headers["token"] = "Bearer  //Set header
            var controllerContext = new ControllerContext()
            {
                HttpContext = httpContext,
            };
            _earningController = new EarningController(_earningRepository.Object, _planRepository, _agentRepository, _promotionRepository) { ControllerContext = controllerContext };

            //var Earning = new Earning()
            //{
            //    Id = 1,
            //    Agent = 1,

            //};


            var Earning = new Earning()
            {
                Agent = new Agent
                {
                    Address1 = "London",
                    AccountNumber = "1234567765432",
                    AgencyId = 1,
                    Id = 1,
                    City = "Rwp",
                    ContactNumber = "5555344",
                    LastName = "Khan",
                    Email = "arslanKhanrwp@gmail.com",
                    FirstName = "Arslan",
                },
                Id = 1,
                Amount = 200,
                Date = DateTime.Now,
            };
           _earningRepository.Setup( x => x.GetProducerEarnings(Earning.Id)Returns(new List<Earning>()
            {
                new Earning
                {
                Id = 1, MemberId = 1,
                }
            }

                ); 
             _earningRepository.Setup(x => x.GetProducerEarnings(It.IsAny<int>())).Callback(() => {
                 new List<Earning>()
            {
                new Earning
                {
                    Id = 1,
                    Agent = new Agent { AgencyId=1 }

                     }
                 };
             });

    Assert.AreEqual(0, await context.Contacts.CountAsync());
        }
    }
}

replaced return of long value with value + 1 in PIT mutation test

I have this Utils class:

public final class DateUtils {

    private DateUtils() {
    }

    public static long toEpochMilli(OffsetDateTime dateTime) {
        return (dateTime == null) ? null : dateTime.toInstant().toEpochMilli();
    }
}

and this Test class:

public class DateUtilsTest {


    @Test
    public void assertReturnEpochMilliConvertedWithoutException() {
        OffsetDateTime dateTime = OffsetDateTime.now();
        assertThat(DateUtils.toEpochMilli(dateTime)).isNotNull();
    }

    @Test
    public void assertReturnNullWhenDateTimeIsNull() {
        assertThat(DateUtils.toEpochMilli(null)).isNull();
    }

}

but I have a SURVIVED test on the line return dateTime.toInstant().toEpochMilli();

with the mutation:

1. replaced return of long value with value + 1 for io/bendiciones/buenas/noches/DateUtils::toEpochMilli → SURVIVED

but I don't know what else should I test

Nunit TestCaseSource with setName also shows original test in testexplorer

I'm attempting to use TestCaseSource to re-use the test with different data. Here I'm trying to give my tests their own name with the 'setName' property which works fine. My issue is that the original test also shows up in the testexplorer. It doesn't seem possible to run. How can I get rid of it in the test explorer?

Simple reproduction:

[TestFixture]
public class Tests
{
    [TestCaseSource(nameof(MyTestData))]
    [Category(name: "MyCategory")]
    public void OriginalTest(string first, string second)
    {
        Assert.IsTrue(true);
    }

    private static IEnumerable<TestCaseData> MyTestData
    {
        get
        {
            yield return new TestCaseData("firstString", "secondString").SetName("FirstTest");
            yield return new TestCaseData("firstString", "secondString").SetName("SecondTest");
        }
    }
}

My test explorer looks like this

enter image description here

dimanche 29 septembre 2019

Django - How to test this CBV?

:) I'm near the end of my first django "project". I managed to make tests for everything, but one view.

I'm not really sure how and what to test here, does someone mind helping me out ?

class CommentCreateView(CreateView):

    def get(self, request, *args, **kwargs):
        context = {'form': CommentForm()}
        return render(request, 'news/add_comment_to_article.html', context)

    def post(self, request, *args, **kwargs):
        form = CommentForm(request.POST)
        if form.is_valid():
            article = get_object_or_404(Article, pk=kwargs.get('pk'))
            print(article)
            comment = form.save(commit=False)
            comment.post = article
            comment.save()
            return HttpResponseRedirect(reverse('news:article', kwargs={'article_id': article.pk}))
        else:
            form = CommentForm()
            return render(request, 'news/add_comment_to_article.html', {'form': form})

Thanks for the help !!

Properly proptest pairs of sets related by a constraint

I want to thoroughly test an implementation of the intersection of two BTreeSets. I can write:

use self::proptest::prelude::*;
proptest! {
    #[test]
    fn intersect_this(s1: BTreeSet<i32>, s2: BTreeSet<i32>) {
        ...
    }
}

But this has poor code coverage, because the code is specialized some cases that random sets are unlikely to hit. One of the special cases is sets whose ranges of elements are almost disjoint (one set has values <= x, the other set has values >= x). In Python with hypothesis (in which I'm a little less of a newbie), I'd write:

from hypothesis import given
from hypothesis.strategies import builds, integers, sets
from typing import Set

def touching_ranges(elements: Set[int], split: int):
    return {elt for elt in elements if elt < split}.union({split}), \
           {elt for elt in elements if elt > split}.union({split})

@given(builds(touching_ranges, sets(integers()), integers()))
def test_touching_ranges(sets):
    s1, s2 = sets
    assert len(s1.intersection(s2)) == 1

In Rust, I got no further than stuffing everything inside the body:

    #[test]
    fn touching(mut s1: BTreeSet<i32>, split: i32) {
        let mut s2 = s1.split_off(&split);
        s1.insert(split);
        s2.insert(split);
        prop_assert_eq!(s1.intersection(&s2).count(), 1);
    }

How can I keep the transformation of arbitrary values out of the test case body? I couldn't understand any of the code samples I found regarding strategies and SO is almost untained with proptest (compared to quickcheck).

Travis CI test fail as if no database

I have tested my software, which is a Django app, locally using nose. Running python manage.py test works as expected, but uploading my app onto travis fails.

Running in my local:

export  CM_DATABASE_NAME='cm_db.sqlite3' CM_DATABASE_USERS_NAME='messenger_users_db.sqlite3' CM_DATABASE_ENGINE='django.db.backends.sqlite3' CM_DATABASE_USER='' CM_DATABASE_PASSWORD='' \
    CM_DATABASE_HOST='' CM_DATABASE_PORT='' CM_DATABASE_USERS_ENGINE='django.db.backends.sqlite3'
(venv) tian@Kaji-Ryoji:~/utz/afi/afinidata-content-manager> python manage.py test
engine:  django.db.backends.sqlite3
db name:  cm_db.sqlite3
nosetests --verbosity=3 --with-coverage --cover-tests --cover-package=content_manager,messenger_users,posts
nose.config: INFO: Ignoring files matching ['^\\.', '^_', '^setup\\.py$']
nose.plugins.cover: INFO: Coverage report will include only packages: ['content_manager', 'messenger_users', 'posts']
Creating test database for alias 'default'...
Creating test database for alias 'messenger_users_db'...
nose.selector: INFO: /home/tian/utz/afi/afinidata-content-manager/manage.py is executable; skipped
test_creation_posts (posts.tests.PostsTest) ... ok
test_update_post (posts.tests.PostsTest) ... ok

Name                                   Stmts   Miss  Cover
----------------------------------------------------------
content_manager/__init__.py                0      0   100%
content_manager/settings/__init__.py       1      1     0%
content_manager/settings/base.py          37     37     0%
messenger_users/__init__.py                0      0   100%
messenger_users/admin.py                   1      1     0%
messenger_users/apps.py                    3      3     0%
messenger_users/models.py                119    119     0%
messenger_users/routers.py                17      3    82%
messenger_users/tests.py                   1      0   100%
posts/__init__.py                          0      0   100%
posts/admin.py                             6      6     0%
posts/apps.py                              3      3     0%
posts/models.py                          126    126     0%
posts/tests.py                            21      0   100%
----------------------------------------------------------
TOTAL                                    335    299    11%
----------------------------------------------------------------------
Ran 2 tests in 0.197s

OK
Destroying test database for alias 'default'...
Destroying test database for alias 'messenger_users_db'...

My travis file is:

dist: xenial   # required for Python >= 3.7
language: python
python:
  - "3.7"
env:
  - CM_DATABASE_NAME='cm_db.sqlite3' CM_DATABASE_USERS_NAME='messenger_users_db.sqlite3' CM_DATABASE_ENGINE='django.db.backends.sqlite3' CM_DATABASE_USER='' CM_DATABASE_PASSWORD='' \
    CM_DATABASE_HOST='' CM_DATABASE_PORT='' CM_DATABASE_USERS_ENGINE='django.db.backends.sqlite3'
install:
  - pip install -r requirements.txt
  - pip install .
# command to run tests
script:
  - python manage.py makemigrations && python manage.py migrate auth && python manage.py migrate --database=default && python manage.py migrate --database=messenger_users_db && python manage.py shell -c "from django.contrib.auth.models import User; User.objects.create_superuser('admin', 'admin@example.com', 'adminpass')" &&  python manage.py test --keepdb
  # https://stackoverflow.com/questions/6244382/how-to-automate-createsuperuser-on-django
# Push the results back to codecov
after_success:
  - codecov

The branch in specific is tester.

https://travis-ci.com/afinidata2019/afinidata-content-manager

Access value inside finalize pipe from test

I have component:

isLoading: boolean;
users: User[];
test: number = 1;

ngOnInit() {
  this.isLoading = true;
  this.userService.getUsers()
      .pipe(
        finalize(() => {
          // Disable loading when complete
          this.isLoading = false;
          this.test = 5;
        })
      )
  .subscribe(results => {this.users = results})
}

And I have test for it (.spec.ts)

    it('should be 5 after ngOnInit', () => {
      component.ngOnInit();
      expect(component.test).toBe(5);
    });

I am getting an error for test 'Expected 1 to be 5.' Why there is this error, if I read value after ngOnInit, .finalize is ignored? How do I get value from .finalize block. fixture.detectChanges() does not help also.

I am using espresso to test android application. I am trying to find a way how to manage matching radiobutton id and textview id for click option

<TextView
                android:id="@+id/manifestName"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="0dp"
                android:layout_marginLeft="10dp"
                android:layout_marginTop="0dp"
                android:text="Balmoral"
                android:textColor="@color/colorPrimary"
                android:textSize="16sp"
                android:visibility="visible" />
<RadioButton
                android:id="@+id/radioButton"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textSize="18sp" />

How to mange textview id and radio button id match with each other for selection of radiobutton in Espresso UI automation.

ViewInteraction appCompatRadioButton = onView(
            allOf(withId(R.id.radioButton),
                    childAtPosition(
                            childAtPosition(
                                    withId(R.id.homeBottomLayout),
                                    2),
                            0),
                    isDisplayed()));
    appCompatRadioButton.perform(click());

I'm tried with above Espresso code but for that i got error:

android.support.test.espresso.AmbiguousViewMatcherException:
Problem views are marked with '****MATCHES****' below.

Sime test on twig render method with PHPUnit

I write a little test (dead simple) and it didn't work. I have no idea why ? Here is the test:

<?php

namespace App\Tests\Mailer;

use PHPUnit\Framework\TestCase;
use Twig\Environment;

class MailerTest extends TestCase
{
    public function testConfirmationEmail()
    {
        $twigMock = $this->getMockBuilder(Environment::class)
            ->disableOriginalConstructor()
            ->getMock()
        ;
        $twigMock->expects($this->once())->method('render');
    }
}

I mock the Twig\Environment class and I test if the method render run only once. Nothing really fancy here. Here is my result:

1) App\Tests\Mailer\MailerTest::testConfirmationEmail Expectation failed for method name is equal to 'render' when invoked 1 time(s). Method was expected to be called 1 times, actually called 0 times.

I don't understand why It didn't work. My test should run the render method only once, but it called 0 times. I tested it with PHPUnit 6.5.14 on Symfony 4.3.2.

Thanks everyone

Django Converting to CBV + tests

I'm trying to test my app. I went over the documentation, and managed to make the test for my URL's and all views but one.

I'm having trouble converting it to a class view and I'm not really sure what kind of tests should I do here ?

Anyone mind helping me out ?

here is the view that I'm trying to convert and test :

def add_comment_to_article(request, pk):
    article = get_object_or_404(Article, pk=pk)
    if request.method == "POST":
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.post = article
            comment.save()
            return HttpResponseRedirect(reverse('news:article', kwargs={"article_id": article.pk}))
    else:
        form = CommentForm()
    return render(request, 'news/add_comment_to_article.html', {'form': form})


The view is in charge of adding a comment to my Article post. Thank you !!

Testing number of columns in tidyverse

I wouls like to test if the number of columns of a data frame match the expected number of columns. The code should fit in a tidyverse pipeline.

However, this code did not work:

library(tidyverse)

# does not work:
mtcars %>% 
  select_if(negate(is.numeric)) %>% 
  if(ncol(.) > 0) stop("there should be no non-numeric column!")
#> Error in if (.) ncol(.) > 0 else stop("there should be no non-numeric column!"): argument is of length zero


# does work:
mtcars2 <- mtcars %>% 
  select_if(negate(is.numeric)) 
if(ncol(mtcars2) > 0) stop("there should be no non-numeric column!")

Created on 2019-09-29 by the reprex package (v0.3.0)

In appears that the "dot" (.) is not correctly evaluated/supported by ncol().

Is there a (straightforward) way to test the number of columns within the tidyverse-pipeline style?

Testcafe - Intercept HTTP request made by iframe of different origin

In puppeteer, page.on('response', respHandler) triggers for all the requests/responses from the page irrespective of the origin.

However I am unable to achieve the same using Testcafe, tried using the docs here https://devexpress.github.io/testcafe/documentation/test-api/intercepting-http-requests/logging-http-requests.html#logger-methods

In my case, i need to check the response of a request initiated by iframe of different origin.

laravel testing with data provider not working with refreshDatabase

I have the following tests and validation rules:

/** @var \App\Http\Requests\StorePopularClientRequest*/
private $rules;

/** @var \Illuminate\Validation\Validator */
private $validator;

public function __construct($name = null, array $data = array(), $dataName = '') {
    parent::__construct($name, $data, $dataName);

    $this->createApplication();
}

public function setUp(): void
{
    parent::setUp();
    $this->adminUser = $this->createUser();
    $this->businessUser = $this->createUser('Business');

    $this->popularClients = factory(PopularClient::class, 20)->create()->each(function($client) {
        static $order = 1;
        $client->order = $order;
        $client->save();
        $order++;
    });

    $this->validator = app()->get('validator');

    $this->rules = (new StorePopularClientRequest())->rules();
}

public function validationProvider()
{
    /* WithFaker trait doesn't work in the dataProvider */
    $faker = Factory::create(Factory::DEFAULT_LOCALE);
    $file = factory(Attachment::class)->create(['category' => 'logo']);
    return [
        'request_should_pass_when_data_is_provided' => [
            'passed' => true,
            'data' => [
                'name' => $faker->company(),
                'description' => $faker->sentence($nbWords = 20, $variableNbWords = true),
                'order' => 1,
                'file' => [
                    "id" => $file->id,
                    "name" => $file->name,
                ]
            ]
        ]
    ];
}

/**
 * @test
 * @dataProvider validationProvider
 * @param bool $shouldPass
 * @param array $mockedRequestData
 */
public function validation_results_as_expected($shouldPass, $mockedRequestData)
{
    $this->assertEquals(
        $shouldPass,
        $this->validate($mockedRequestData)
    );
}

protected function validate($mockedRequestData)
{
    return $this->validator
        ->make($mockedRequestData, $this->rules)
        ->passes();
}

And inside StorePopularClientRequest I have the following rules

public function rules()
{
    return [
        "name" => [
            'required','string', 
        ],
        "description" => [
            'required', 'string', 'min:5',
        ],
        'order' => ['required', 'integer'],
        'file' => ['required', 'array'],
        'file.id' => ['required', 'exists:attachments,id'],
        'file.name' => ['required', 'exists:attachments,name'],
    ];
}

All of those rules working properly except exists:attachments, name, exists:attachments,id, because of using RefreshDatabase, I if comment RefreshDatabase it works. So is there any way to not refresh the database before all tests finished, and then refresh the database?

Now the attachment factory works, and create attachment data in attachments table, but when I run the test, attachments table is refreshed before test, and the exists rule for attachment is invalid

samedi 28 septembre 2019

Unittest's subTest doesn't work with Pytest, or am I crazy?

As I understand, pytest should provide parameter information withunittest.TestCase.subtest() if a test fails. So here is something that resembles my code:

class TestStuff(unittest.TestCase):

    def test_foo(self):
        for i in range(0, 100):
            with self.subTest(msg = "seed", i = i):
                np.random.seed(i)
                n = np.random.randint(0, 30)
                self.assertGreaterEqual(28, n)

This ofcourse fails, and prints out the following:

================================================================================================== test session starts ===================================================================================================
platform darwin -- Python 3.7.3, pytest-5.0.1, py-1.8.0, pluggy-0.12.0
rootdir: /Users/foopackage
plugins: openfiles-0.3.2, arraydiff-0.3, doctestplus-0.3.0, remotedata-0.3.1
collected 7 items                                                                                                                                                                                                        

foo.py ......F                                                                                                                                                                                               [100%]

======================================================================================================== FAILURES ========================================================================================================
________________________________________________________________________________________________ TestStuff.test_foo _________________________________________________________________________________________________

self = <foo.test_foo.TestStuff testMethod=test_foo>

    def test_foo(self):
        for i in range(0, 100):
            with self.subTest(msg = "seed", i = i):
                np.random.seed(i)
                n = np.random.randint(0, 30)
>               self.assertGreaterEqual(28, n)
E               AssertionError: 28 not greater than or equal to 29

foo.py:135: AssertionError
=========================================================================================== 1 failed, 6 passed in 1.91 seconds ===========================================================================================

As you can see, there are no message about which seed (value of i) failed the test. I have read everywhere that Pytest is compatible with unittest, so I cant seem to see the problem here. Can someone explain this? Thx

How to get Pytest to identify iteration number when looping test function

I'm using pytest for this test I am doing.

I want to do the same test multiple of times, while altering the seed input. This randomises the test variables, which i thought was a good idea. That way, if the test fails, i can easily recreate the same test in a different environment to see what failed, using the same seed input:

def test_foo():
    for i in range(0, 10):
        foo = random_foo('something', seed = i)

        assert subject_value(foo) == expected_value(foo)

However, if the test fails, Pytest won't tell me the value of i for when the AssertionError occurred, which makes debugging close to impossible. Any way to successfully do this? Or is this bad test code structuring, which in that case, any better methods?

jasmine spy not finding property

I have a file that basically looks like this(shortened)

const octokit = new (require("@octokit/rest"))();
function buildRepo(name) {
  fs.promises
    .readFile("data/settings.json")
    .then(data => JSON.parse(data))
    .then(settings => settings.repositories.find(repo => repo.name === name))
    .then(repo => {
      let repoName = repo.url
        .substring(repo.url.lastIndexOf("/") + 1)
        .slice(0, -4);
      let jobName = repo.name;
      return octokit.repos
        .get({
          owner: "munhunger",
          repo: repoName
        })
        .then(({ data }) => {
          ...
        });
    });
}

module.exports = { buildRepo };

And so I want to write a test for what it does with the data that it get from the octokit.repos.get function. But since that function will go out to the internet and look at github repositories, I want to mock it.

I have a few tests running with jasmine, and I read up slightly on it and it seems as if jasmine should be able to mock this for me.

However the test that I have written seems to fail.

const builder = require("./index");

describe("spyOn", () => {
  it("spies", () => {
    spyOnProperty(builder, "octokit");
    builder.buildRepo("blitzbauen");
  });
});

With the error octokit property does not exist. What am I doing wrong here? would I need to add octokit to module.exports?(which seems rather insane)

How to get the debugger in node.js working with inspect

I have an algorithm to test in node.js so I want to inspect a for loop with the debugger:

for (let char in charMap) {
   debugger;
}

I tried to inspect the file with 'node inspect [path]' command, but i got this:

$ node inspect .\maxChar.js
Timeout (2000) waiting for 127.0.0.1:9229 to be free

Then, i tried the following command to change the port to 9230, but it's still not working:

$ node --inspect=127.0.0.1:9230 inspect .\maxChar.js
Debugger listening on ws://127.0.0.1:9230/6ff23aac-0979-4399-a3e3-a076239253e1
For help, see: https://nodejs.org/en/docs/inspector
Timeout (2000) waiting for 127.0.0.1:9229 to be free

How can i get the node inspect to work ?

Spring Controller Testing Added Objects NullPointerException

I've ran into this problem in different parts of my projects. It happens whenever there's a list being initialized in the controller itself, and I can't seem to understand how to mock it for the test.

I tried to instantiate the list inside of the test, add values to it.

given(user.getOrderList()).willReturn(userOrderList)

I also tried passing it as a flashAttr, requestAttr to the mockMvc.

This is the method I'm trying to test

@GetMapping("/account")
public ModelAndView account(Principal principal) {

    User user = userService.findByUsername(principal.getName());

    ModelAndView mav = new ModelAndView("profile");

    mav.addObject("user", user);
    mav.addObject("userPaymentList", user.getPaymentList());
    mav.addObject("userAddressList", user.getAddressList());
    mav.addObject("classActiveAccount", "active");

    mav.addObject("userOrderList", userOrderListSortedById(user));

    return mav;
}


private List<Order> userOrderListSortedById(User user){

    List<Order> orderList = user.getOrderList();
    orderList.sort(Comparator.comparing(Order::getId));
    Collections.reverse(orderList);

    return orderList;
}

And this is the test method

@Test
void testAccountPage() throws Exception {
    User user = new User();
    given(userService.findByUsername(anyString())).willReturn(user);

    mockMvc.perform(get("/account"))
            .andExpect(status().is3xxRedirection())
            .andExpect(model().attributeExists("userPaymentList"))
            .andExpect(model().attributeExists("userAddressList"))
            .andExpect(model().attribute("classActiveAccount", "active"))
            .andExpect(view().name("profile"));
}

I don't think the problem is with the private method, if I change the value of userOrderList to user.getOrderList(), the problem is the same.

In another method I was trying to test, I had the same problem when there was a list I could not figure out how to initialize and add the model.

if (bookList.getTotalPages() > 0) {

        List<Integer> pageNumbers = IntStream.rangeClosed(1, 
bookList.getTotalPages())
                .boxed().collect(Collectors.toList());

        mav.addObject("pageNumbers", pageNumbers);
    }

In this one, first I was failing even the check for 0, cause the list was null, and then I couldn't test pageNumbers, cause that was null.

How do I solve a problem like that?

Interface in Java for Testing Framework: Interview Question

Often times I get a question where I used interface in my framework. I can explain the concept but in real life as a tester for 1 year I have not encountered interface implementation. Can someone please give a brief idea where you have used it, please. Thanks

How to test passport LocalStrategy with jest

Stock with express passport LocalStrategy test, probably on mocking request.

test('should Test password Login auth', async (done) => {
  const response = jest.fn((arg)=> console.log('args', arg));
  const next = jest.fn();
  let mockReq = {body: { username: "test@gmail.com", password: "tets"}}
  let mockRes = {send: function(ats){console.log("mockResFunc", ats), response()}};

  passport.authenticate('local', ()=> response())(mockReq, mockRes);

  expect(next).not.toHaveBeenCalled();
  expect(response).toHaveBeenCalled();

but callback is never called as well as i didn't found password and username goes to passport function. Does anyone ideas how to mock credentials using jest(i think here is clue)?

passport.use(new LocalStrategy(
    async function(username, password, done) {
            const existingUser = await User.findOne({ 'email' :  username })
            console.log('credits', username, password, existingUser.email)
    if (existingUser) {
        let validUsr = existingUser.validPassword(password);
        if (existingUser && validUsr) {
            console.log('passport',existingUser.email)
          return done(null, existingUser);
        }
    }
    return done(null, false, { message: 'Wrong credentials.' });
    }
  ));

Sonarqube exclusion on Test Data

Fellow Members, I am trying to configure Sonarqube on my service. For tests, I have extracted testData (setup) into a separate class - testData.java class.

My question is, how should I analyse my testData.java using Sonar. Since Sonar mandates all the files under test package to end with *Test.java. Therefore if I try to rename the file to something say testDataTest.java it asks me to add a Test to the class. Since my class is a final class and does not contain any test, I have to add a hack to add a meaning less @Test. I would like to understand what are the best practices here and how could I improvise.

Thanks

vendredi 27 septembre 2019

How to test multiple service calls

I'm trying to increase my code coverage on Android. But I can't find the correct way to test this presenter. The onSelectContact makes a service call and later my ServiceFactory.getContactService makes another. How can I mock this calls?

public class ContactListPresenter {

    public void onSelectContact(User user) {
        getCorrespondingContactCall(user).enqueue(new Callback <JsonElement>() {
            @Override
            public void onResponse(Call<JsonElement> call, Response<JsonElement> response) {
                switch (response.code()) {
                    case case1:
                        goToFirstActivity(user, response);
                        break;
                    case case2:
                        goToSecondActivity(user, response);
                        break;
                    default: showInvalidInput(user);
                        break;
                }
            }

            @Override
            public void onFailure(Call<JsonElement> call, Throwable throwable) {
                if (getView() != null) {
                    getView().showErrorView();
                }
            }
        });
    }

    protected Call<JsonElement> getCorrespondingContactCall(final User user) {
        return StringUtils.isValidEmail(user.getEmail())
                ? ServiceFactory.getContactService().checkContactByEmail(user.getEmail())
                : ServiceFactory.getContactService().checkContactByPhoneNumber(user.getPhoneNumber());
    }     

}

Change Response After a Period of Time

I have a function that makes requests to a URL to check it's status. I need help testing it in Jasmine. Here's what I've tried:

jasmine.clock().install();
jasmine.Ajax.stubRequest(url).andReturn('working');
checkStatus(url, callback); // makes XHR requests to check status (should be 'working')
jasmine.clock().tick(5000);
jasmine.Ajax.stubRequest(url).andReturn('ready');
// callback should be invoked with status 'ready'
jasmine.clock().uninstall();

Call to Query with args [], was not expected in go-sqlmock for compound SQL queries

I was able to successfully mock the query to select from one table like so:

sqlMock.ExpectQuery("^SELECT DISTINCT (.+) FROM myTable1, myTable2").
        WillReturnRows(myResultRows)

But I was not able to mock the following query that checks for the existence of the table in my postgres db:

SELECT EXISTS
        ( SELECT 1
        FROM information_schema.tables
        WHERE table_schema = 'public'
           AND table_name = 'myTable3' );

The combination of:

    existsRows := sqlmock.NewRows([]string{"exists"}).
        AddRow(true)

AND

    slMock.ExpectQuery("^SELECT EXISTS").
        WillReturnRows(existsRows)

I tried mocking SELECT 1 as well but I get the exact same error:

time="2019-09-27T15:49:41-07:00" level=panic msg="db query" error="call to Query 'SELECT EXISTS\n\t\t( SELECT 1\n\t\tFROM information_schema.tables\n\t\tWHERE table_schema = 'public'\n\t\t   AND table_name = 'myTable3' );' with args [], was not expected, next expectation is: ExpectedExec => expecting Exec or ExecContext which......

Packages I am using:

import (
    "database/sql"
    "db"
    "os"
    "testing"

    // not explicitly called
    _ "github.com/denisenkom/go-mssqldb"
    _ "github.com/lib/pq"

    "github.com/DATA-DOG/go-sqlmock"
    "github.com/sirupsen/logrus"
)

Any ideas or pointers are appreciated. I couldn't find relevant examples on the internet

Spring test: Parameter 0 of constructor in BlogService required a bean of type BlogPostRepository

I have a BlogPostRepository which is an interface JpaRepository:

@Repository
@Primary
public interface BlogPostRepository extends JpaRepository<BlogPost, Long> {
    @Query("SELECT p FROM BlogPost p WHERE slug = ?1")
    List<BlogPost> findBySlug(String slug);
}

When I run the following test, Spring is not able to load the BlogPostRepository, according to this error:

Parameter 0 of constructor in com.example.demo.Services.BlogService required a bean of type 'com.example.demo.Repositories.BlogPostRepository' that could not be found.

My test looks like:

@RunWith(SpringRunner.class)
@WebMvcTest(BlogController.class)
@ContextConfiguration(classes = {DemoApplication.class,BlogController.class})
public class BlogControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @Test
    public void test() throws Exception
    {
        MvcResult result = this.mockMvc.perform(get("/blog"))
                //.andDo(print())
                .andExpect(status().isOk())
                .andReturn();
        assertTrue(result.getResponse().getContentAsString().contains("Hello world"));
    }
}

The problem is I cannot define the BlogPostRepository as a bean, since it is an interface:

@Bean
public ExceptionFactory exceptionFactory()
{
    return new BlogPostRepository(); //this does not work! -> cannot construct interface
}

This only occurs during an integration test.

Compare values in Selenium IDE

I am new to Automation Testing and Selenium IDE. I have one testing case which update just the email and another testing case which check if the update email is the same on another page.Test passes if the compared email is the same. So far, I only found an option to update the values and wondering if there is any option to compare the updated values in different page. Any suggestion would be helpful. Just to clarify,

Test case 1(Action): 1. Open HR department page on browser 2. Go to user profile and update user email

Test case 2(Check): 1. Open Employee department page on browser 2. Go to user profile and see if the update email from test case 1 is showing the same.

Because we're using different database for each departments, the test will passed if the email is the same, and the test will failed if the email is not the same on Selenium IDE.

How to stop Trogdor testing Agent + Coordinator service responsible for shutting down Kafka and Zookeeper instances

I have been running stress testing on Kafka. I used trogdor test framework for creating network and IO faults. After testing I tried to kill process agents but the trogdor is running zombie processes which can't be killed by kill -9. The running trogdor service is killing zookeeper and Kafka instances and my cluster can't be active. What is the way to shutdown these service safely without the need to restart Unix server ? I would also appreciate a way to find parent process responsible for this. I currently have to use ps -o ppid=

I've tried killing Trogdor process, AgentClient process, agent and coordinator process

When I try to kill the parent process of any of the above mentioned processes, the connection to SSH server is disconnected and PuTTY is closed

Django deepcopy a model instance to memory

I want to write a test for a Django view that modifies an instance of a model.

In the past there was a problem with the view's code, it was writing on other unconcerned model instances too.

I am looking for a way to "copy" a model's instance in memory, run the view, then compare the memory and database version of the instance.

Pseudo code :

def test_some_view:
    url = reverse('some_view')
    unconcerned_model = MyModel.objecs.get(id=X)
    concerned_model = MyModel.objects.get(id=Y)
    cpy = deepcopy_of(unconcerned_model)  # how can we do that ?
    self.client.post(url, {'mymodel_id':concerned_model.id})
    unconcerned_model.refresh_from_dbs()
    self.assertEqual(cpy, unconcerned_model)

How can the deepcopy be done ? How to compare the 2 versions ?

Not able to install ggplot

Error: package or namespace load failed for ‘ggplot2’ in loadNamespace(j <- i[[1L]], c(lib.loc, .libPaths()), versionCheck = vI[[j]]): there is no package called ‘pkgconfig’

Why do I need to use waitForAngular(false) & browser.sleep(3000)?

We have a website that is built 100% from Angular and I was asked to use Protractor to write rend to end testing. Now the problem that I had encountering is that if I do not use waitForAngular(false) and browser.sleep(3000) my test will fail even I used the ExpectedCondition.

So here is my Scenario:

In the login page, I can find all the element, send-keys to the input box and login. But after login, it fails. It cannot find any element, click any element at all.

My Code looks like this.

describe("/profile", () => {
  let page: Profile;

  beforeAll(async () => {
    page = await login(Profile, user, login);
    await browser.wait(ExpectedConditions.presenceOf(page.element));
    await navigate(path.profile)
  })

  afterAll(async () => {
    logout();
  })

  it("should have navigate to the page", async () => {
    expect(await browser.getCurrentUrl()).toContain("/profile");
  });

  it("should have correct page markup", async () => { 
// this test fails without waitForAngular(false)
// or browser.sleep(3000) in the navigation or OnPrepare in the config
    expect(await page.headerTitle.isDisplayed()).toBe(true);
    expect(await page.headerTitle.getText()).toContain("Profile")
  })
})

How to use value which returned from controller? Testing controllers on NestJs

Controller and method for testing:

import { Controller, Get, Response, HttpStatus, Param, Body, Post, Request, Patch, Delete, Res } from '@nestjs/common';
@Controller('api/parts')
export class PartController {
  constructor(private readonly partsService: partsService) { }

  @Get()
  public async getParts(@Response() res: any) {
    const parts = await this.partsService.findAll();
    return res.status(HttpStatus.OK).json(parts);
  }
}

And this is unit test which must test getParts method:

describe('PartsController', () => {
  let partsController: PartsController;
  let partsService: partsService;

  beforeEach(async () => {
    partsService = new partsService(Part);
    partsController= new PartsController(partsService);
  });

  describe('findAll', () => {
    it('should return an array of parts', async () => {
      const result = [{ name: 'TestPart' }] as Part[];

      jest.spyOn(partsService, 'findAll').mockImplementation(async () => result);

      const response = {
        json: (body?: any) => {
          expect(body).toBe(result);
        },
        status: (code: number) => response,
      };

      await partsController.getParts(response);
    });
  });
});

This test works correctly, but I think this is a bad solution. When I investigated this problem, I saw this option:

const response = {
  json: (body?: any) => {},
  status: (code: number) => response,
};
expect(await partsController.getParts(response)).toBe(result);

But when I try it my test don't work, cause await partsController.getParts(response) // undefined So what should I do to make my test look good?

In solution I use: nodeJS sequelize, nestJS, typescript

How can I configure the .gitlab-ci.yml for Maven tests

I'm newer in GitLab. I have some tests and I want to run them by CI\CD. Can you help me to configure my .yml. I should run testng.xml

This is my project: enter image description here

path to my tests is: src/test/java/tests/"files with tests"

my .yml file:

image: maven:3-jdk-7

build:
  script: mvn install -b

Test Design Techniques | Decision Table

I need to create Decision Table (s) with all Conditions, but i don't know how many columns should be there. I would be glad to receive an explanation of this task

Task:

I need to create Decision Table (s) with all Conditions, but i don't know how many columns should be there I would be glad to receive an explanation of this task Task:

1)Up to 3 conditions could be assigned per one Mega Power Deal.

2)There are 8 possible conditions to be selected:

Location is a Smart Stock subscriber

Location is not a Smart Stock subscriber

Item has never been ordered

Item was ordered more than 13 weeks ago

Item was ordered less than 13 weeks ago

Item was ordered less than 5 times

Item’s Average Order Quantity is less than amount of items

Item’s Average Order Quantity is more than amount of items

enter image description here

enter image description here

enter image description here

Flutter: Widget test a selected Radio button

I can't figure out how to check if a particular Radio button within a list of options is selected or not in a Flutter widget test, anyone knows how?

Kotlin: Test lamda expression callback

I'm trying to write unit for the following rest api call, my method looks like this

fun authenticate(email: String,
                 password: String,
                 onSuccess: () -> Unit,
                 onError: (message: String) -> Unit): Disposable? {

    val mapper = AuthMapper(email, password)
    val request = RestRequest(AuthRestRequestErrorHandler(), this.restService.authenticate(mapper))


    return  request.handleObservable<AuthResponseMapper>(
        onSuccess = { authResponseMapper ->
            this.storeAuthSession(LoginProvider.regular, authResponseMapper)
            onSuccess()
        },
        onError = { error ->
            onError(error.message)
        }
    )
}

The goal is call authentication endpoint, receive auhtorization token and test one more similar method which can be called only with authorization token.

I'm coming from iOS where you have waitForExpectations and expectation.fulfill() methods which help me to wait for api response and check result. So is there anything similar on android or any other suggestions or correct approaches how to do that?

Test detail summary font size too large in Visual Studio 2019

Since upgrading from VS2017 to VS2019 I have noticed that the text in test detail summary windows is comically large making it hard to read test results without a great deal of scrolling. This persists in the latest 16.3.1 version. I assume (and hope) that there is an option I can use to control the font used there but I haven't been able to find it. Does anyone know what/where the option might be? Here's a screenshot. enter image description here

Problem running test on antd table with fixed columns

I have a react antd table. When I add some fixed columns, the jest test starts failing with: TypeError: this.rowRef.getBoundingClientRect is not a function

When I remove the fixed property, the test runs without issue... Anyone had a similar issue? Any idea how to fix?

How to test a program in bash? (functional testing)

For example I have a program gcd that return the greatest common divisor that I call with:

$ ./gcd 42 36
6

I could test these input with:

#!/bin/bash 

[[ $(./a.out 42 36) == "6" ]] || exit 1
[[ $(./a.out 42 11) == "1" ]] || exit 1

Unfortunately with this I do not have any summary such as

ran 11 tests, 0 failures, 11 successful tests

Is there any very simple template/framework to do such testing at program level (not unit testing)?

How are fcgi scripts tested?

I am a newbie so forgive me if this sounds naive. I wrote a script in fastcgi++. And I tested the basic use cases. But like a good software engineer I want to test the script every time I make a change to make sure I don't break things.

This was what I used to do:

This was my directory structure:

script:

 - bin 
 - build (contained the bash script to compile the script)
 - src
 - tests  
    - build (contained bash script to compile the test)
    - src (contained the test file)
    - output

I hacked the way I tested. I used to use curl to call my script and redirect its output to a file in tests/output (using relative path) and compare it with the expected output. I could do that because the tests were compiled by hand and I only executed the tests after changing the directory to tests/build. I recently decided to use a build system. I chose meson. The way you test using meson is by running meson test or ninja test. The problem is now I do not control from where the test is run.

How to test in such circumstance? And how you test your fcgi scripts?

jeudi 26 septembre 2019

Minitest warning: DEPRECAED global use of must_match. Use `_(obj)`

I'm writing the following test with Minitest 5.12.0:

require 'minitest/autorun'
require 'nokogiri'
require 'net/http'

class NetClass; end

describe NetClass do
  attr_accessor :uri, :net
  before do
    @uri=URI('http://example.com/index.html')
    @net=Net::HTTP.get('example.com', '/index.html')
  end

  it 'gets uri' do
    net.must_match /Example Domain/i
  end
end

When running it I get the warning:

DEPRECATED: global use of must_match from net_test.rb:16 Use _(obj).must_match instead. This will fail in Minitest 6

To eliminate the warning I change the line:

net.must_match /Example Domain/i

to

_(net).must_match /Example Domain/i

I have not seen the _(obj) syntax before so my question is what is _() doing in this case.

Android url load testing

Hey guys I've been having trouble with my Android app lately I'm trying to make a android app that takes in the load time,page size,and http request through web view. URLs The way I plan to make it is by allowing the user to load up a bunch of urls and the app will record the responses of the load time and page size similar to the network developer tool panel in chrome.This is a personal project of mine and I'm having trouble finding libraries and documents to do this.I currently can't find anything online that can help me do y'all have any links or places I can do research on that can help me with this side project. Ps:Please don't respond if all your gonna say is that you need a coding question here I'm just looking for libraries and links because right now I don't have any luck.Im not looking for the whole app here.

Testing checkbox in Django as field in form

I have a form with a single field which is a two level checkbox, if I select parent checkbox while no children selected, the parent with all children items will show in my json data after submit. I want to write a test to test this. I'm new to Django test, after reading Django documents, still struggle on manipulating the checkbox. My form looks like this:

class RerunForm(forms.Form):
    items = ItemStatus(
        queryset=models.Container.objects.none(),
        widget=forms.CheckboxSelectMultiple(attrs=dict(checked='')),
        help_text="Select items that you want to rerun.",
    )

    def __init__(self, rerunqueryset, *args, **kwargs):
        super(RerunForm, self).__init__(*args, **kwargs)
        self.fields['items'].queryset = rerunqueryset

class ItemStatus(forms.ModelMultipleChoiceField):
    def label_from_instance(self, obj):
        return "{} ({})".format(obj.name, obj.state)

rerunqueryset is passed from view, which is like this

<QuerySet [<Container: AT1>, <Container: AT1_1>, <Container: AT1_2>, <Container: AT1_3>, <Container: AT1_4>, <Container: AT2>, <Container: AT2_1>

My page looks like this:

In my django test, I want test: 1. check parent level item while no children checked, parent and all children names will show in json after submit 2. check parent level item, and any children item, only checked children show in json data after submit.

Till now, I have codes like client and context to access my checkbox label, my question is how do I set certain checkbox to 'checked', and trigger submit button?

>>>response = client.get('/rerun/1')
>>>response.context['form']['items'][0].data
{u'index': '0', u'name': 'items', u'template_name': u'django/forms/widgets/checkbox_option.html', u'type': u'checkbox', u'selected': False, u'attrs': {'checked': '', u'id': u'id_items_0'}, u'value': 5742, u'label': 'AT1 (PASS)'}

C# way for doing Assert.AreEqual(.,.,delta), but returning a bool

Say we have a Point class.

public class Point {
    public double x;
    public double y;
    ...
    public isEqual(Point p) {
        // here we worry about epsilons
    }
}

Some TestProject computes, say, the median of a triangle and confirms (by comparing x and y coordinates) that the point returned is correct. But we need to introduce tolerances.

Now we're damned if we do, damned if we don't:

Scenario 1

C# conveniently overloads the Assert.AreEqual() to handle tolerances. We put the comparison in the TestProject. We use Assert.AreEqual() and all is good.

But if we write ten different tests in ten different projects, we have not encapsulated point comparison. It is scattered throughout, which is bad.

Scenario 2

We put the comparison along with the Point class. Now any time we need to compare two points we just send the two points to the Point class and we get the answer.

But we can no longer use Assert.AreEqual(). All Asserts must be located in a TestProject.

We have to use our own comparator.

The question then is: what is the C# way for doing Assert.AreEqual(), but returning a bool?

Can I doc-test ELisp functions?

I like the Python feature of doc-tests for testing functions independently. Does Emacs Lisp have something similar, or could I emulate it in some way?

For example, this function gets timestamps from an Org-mode clock segment:

(defun org-get-timestamps (line)
  "Parses a clock segment line and returns the first and last timestamps in a list."
  (let* ((org-clock-regexp (concat "CLOCK: " org-ts-regexp3 "--" org-ts-regexp3))
     (t1 (if (string-match org-clock-regexp line)
         (match-string 1 line)
           (user-error "The argument must have a valid CLOCK range")))
     (t2 (match-string 9 line)))
    (cons t1 (cons t2 '()))))

I would like a doc-test such as:

(org-get-timestamps "CLOCK: [2019-09-26 Thu 00:29]--[2019-09-26 Thu 01:11] =>  0:42")
("2019-09-26 Thu 00:29" "2019-09-26 Thu 01:11")

A test of the user-error would also be nice.

I also would like to ensure that any refactoring passes the doc-test, so it's also a regression test.

Does that exist?

Angular 8+ tsconfig Path Aliases Show Red Squiggles in spec File Imports with Working Tests in VS Code

I am working on some Angular testing and my spec files will not recognize my paths and they give me a red squiggle import warning in VS Code (and show up in Problems) despite the fact that they work in every other way (testing works, etc.).

example imports:

import { EnvService } from '@core/services/env.service';
import { AppService } from '@core/services/app.service';

tsconfig.json paths:

...
   "paths": {
        "core-js/es6/*": [
            "./node_modules/core-js/es/*"
        ],
        "core-js/es7/reflect": [
            "./node_modules/core-js/proposals/reflect-metadata"
        ],
        "@core/*": ["src/app/core/*"],
        "@shared/*": ["src/app/shared/*"],
        "@feature/*": ["src/app/feature/*"],
        "@test/*": ["src/app/test/*"]
    }
...

tsconfig.spec.json and tsconfig.app.json paths (note standard folder structure from angular-cli):

...
  "paths": {
    "core-js/es6/*": [
        "../node_modules/core-js/es/*"
    ],
    "core-js/es7/reflect": [
        "../node_modules/core-js/proposals/reflect-metadata"
    ],
    "@core/*": [
        "app/core/*"
    ],
    "@shared/*": [
        "app/shared/*"
    ],
    "@feature/*": [
        "app/feature/*"
    ],
    "@test/*": [
        "test/*"
    ]
}
...

Versions:

Angular CLI: 8.3.6
Node: 12.3.1
OS: win32 x64
Angular: 8.2.8
... animations, common, compiler, compiler-cli, core, forms     
... language-service, platform-browser, platform-browser-dynamic
... router, service-worker

Package                           Version
-----------------------------------------------------------
@angular-devkit/architect         0.803.6
@angular-devkit/build-angular     0.803.6
@angular-devkit/build-optimizer   0.803.6
@angular-devkit/build-webpack     0.803.6
@angular-devkit/core              8.3.6
@angular-devkit/schematics        8.3.6
@angular/cli                      8.3.6
@angular/pwa                      0.803.6
@ngtools/webpack                  8.3.6
@schematics/angular               8.3.6
@schematics/update                0.803.6
rxjs                              6.5.3
typescript                        3.5.3
webpack                           4.39.2

Stata help: How to test if two independent variables have the same effect when given values

So, I have this question. I need to test if being male has the same effect as aging 10 years, on the total expenditure on health. I have variables age (beginning from 65) and female (1 if female and 0 if male). I have written something like:

regress totexp age female (other indep var) test i0.female=age/10

But I know it's probably incorrect. Can anyone help on this specific issue?

How do I make sure erroneous code does not build in a CI process?

I am writing some C++ library, and I already use some CI (Continuous Integration) process, to make sure the features work. The build is makefile-based, so the CI script holds a make test line. That target will run the automated tests (say, using Catch), and build passes only if it succeeds.

The good practices mandates that a wrong usage of the library by user code should preferably trigger a compile error, instead of a run-time error. So I included lots of static checking.

However, I want to make sure in my automated testing process that this is really the case (that user code using the library erroneously will fail to build).

So I put up a folder holding several .cpp files, each demonstrating an incorrect usage of the library, thus each of them should fail to build.

My problem is that if I add a new target in my makefile to build these, it will return after first failure.

What I want to do is make sure that all these files fail to build, and return 0 only in that case.

How can I write a target that performs this ?

Some (not working) code, that will return after first failure.

SRC_FILES := $(wildcard *.cpp)
OBJ_FILES := $(patsubst %.cpp, %.o, $(SRC_FILES))

all: $(OBJ_FILES)
    @echo "done"

%.o: %.cpp
    $(CXX) -o $@ -c $<

If I basically ignore the failures (prepending line with -), I won't be able to check that all of the files are incorrect.

How to create a Spec-Flow test for a Prism 7 app?

I'm in the process of creating a new windows desktop app with Prism 7, and I started out with the new PrismApplication base class that replaced the bootstrapper. Everything was fine until I created the (specflow-)tests.

I was used to re-using the original bootstrapper during initialization of the test-app, just modifying the registrations afterwards. That, transformed to the new Application derived system looks like this:

internal partial class App
{
    protected override IContainerExtension CreateContainerExtension()
    {
        var containerExtension = new Prism.Unity.Ioc.UnityContainerExtension();
        containerExtension.Instance.AddExtension( new LogExtension() );
        return containerExtension;
    }

    protected override Window CreateShell()
    {
        return Container.Resolve<MainWindow>();
    }

    protected override void RegisterTypes( IContainerRegistry containerRegistry )
    {
        containerRegistry.Register<IConfiguration, AppSettingsConfiguration>();
        containerRegistry.Register<IWindowsInterface, WindowsInterface>();
        // ... a lot of registrations removed here ...
    }
}

And a derived test-app that does everything but create the shell:

private class MyApp : App
{
    protected override Window CreateShell()
    {
        return null;
    }
}

Wrapped up in a BeforeScenario hook to initialize the test-app:

[BeforeScenario]
public void InitializeApp()
{
    var app = new MyApp();
    app.Initialize();
    var containerRegistry = (IContainerRegistry)app.Container;

    containerRegistry.RegisterSingleton<TestWindowsInterface>();
    containerRegistry.Register<IWindowsInterface,TestWindowsInterface>();
    // ... some registration overrides removed here ...

    _objectContainer.RegisterInstanceAs<App>( app );
}

And a step to create the main window (CreateShell replacement):

[When( @"I start the software" )]
public void WhenIStartTheSoftware()
{
    _container.RegisterInstanceAs( _container.Resolve<App>().Container.Resolve<MainWindowViewModel>() );
}

So far, so good, this works. But only as long as you have just one scenario. As soon as the second scenario starts, we get an exception:

Cannot create more than one System.Windows.Application instance in the same AppDomain.

In the old days, this wasn't a problem, because the Bootstrapper was just a regular class, as opposed to the PrismApplication which is enforced to be a singleton by the framework.

Of course, I can move the whole registration stuff into a regular class, and use that to initialize the test-app, but this means essentially creating my own version of the bootstrapper on top of the PrismApplication. Using the classic Bootstrapper makes more sense to me, yet it will be dropped in a future release (as it's marked obsolete today).

Is there any official guide or unofficial statement from the Prism team on how to test applications built with the new style?

IBM Rational Integration Tester (RIT) make two service call and compare result

I have two services to test using RIT. One is the legacy service and another is the new service. Is it possible to make two service call for one test data from RIT and compare the result of those two calls? I just want to make sure that two services contract are identical?

Thanks in advance.

How to mock ImagePicker

I use this package: image picker Now, I have this line of code:

File image = await ImagePicker.pickImage(source: ImageSource.camera);

that I would like to mock in my test, but I can't find a way to do it.

How to test an observable stream?

I want to write unit tests in Angular for the following function:

exportToCsv(query: string) {
    this.exportToCsvService.exportDataAndGetCsv(query).pipe(
      first(),
      tap(response => this.fireCsvDownload(response))
    ).subscribe();
  }

The function exportDataAndGetCsv makes a http call and returns a string. I think the test I would write should check if the fireCsvDownload was executed. I tried:

it('should fire fireCsvDownload after exporting data and geting csv ', () => {
    component.exportToCsv(query);
    fixture.detectChanges();
    expect(component.fireCsvDownload).toHaveBeenCalled();
  });

But I get an error: Error: <toHaveBeenCalled> : Expected a spy, but got Function. What should I do? I provide the exportToCsv service to the TestBed and the exportDataAndGetCsv returns of('text').

Check that python list follows a specific repeating pattern

I have a python list which contains only two symbols, let us say they are a and b and the list looks like so:

L = ['a','b','a','b','a','b','a','b','a','b','a','b','a','b','a','b']

Now in my application, I have thousands of these lists, and they vary in length (typically a few hundred long). But what they all have in common is that they have the repeating pattern (a,b).

I should say that they all should have that pattern. I am looking for an efficient way, a test, that can determine that each list does in fact have this repeating pattern. And if not throw an error or something e.g.

assert my_fancy_test(L), 'the list does not follow the correct pattern'

I think I am looking for sub-sequence matching, but my google searches are coming up short.

test a server with python scripts

forgive the trivial question, but I am embarking on a type of project that I have never done before. I have a complex app with a front and back end. I need to make sure that everything is running all the time smoothly. I am running several services that I need to monitor constantly like nginx, etc. To test this particular service, I use a script like:

sudo systemctl status nettle

I have many of this to test the individual services and report their status. I want to build an app that monitor all these services and inform the global state of the system. My aproach would be to put asynchronous calls in a timer. Is that the right approach, or is there another clever way to achieve the same objective?

Thank you for your help

What part need to be done in ZAP after configuration in mobile?

What part need to be done in ZAP after configuration in mobile. As I am not able to see anything in ZAP after I did the mobile configuration and opened my application in Mobile device.

How to pass TestRunParameters to "dotnet test" command directly from command line

Below is runsettings files, having custom parameters defined. <?xml version="1.0" encoding="utf-8"?> <RunSettings> <TestRunParameters> <Parameter name="publishResults" value="true" /> </TestRunParameters> </RunSettings>

This is how I run command from command line dotnet test MyTests --settings develop.runsettings --no-build

I want to avoid .runsettings and like to run like this dotnet test MyTests --publishResults true --no-build

Is it possible?

Laravel 5.8 UploadedFile fake not working in test as expected

I have an api call where I upload some files, I am writing a test for this api call and I do this:

$response = $this->postJson(
    $url,
    [
        'uploadedFile' => UploadedFile::fake()->create('test.csv', 512),
    ]
);

When I do this in my code, not my test:

$request->uploadedFile->getClientOriginalName()

I get the following error when I run my test:

Call to a member function getClientOriginalName() on string

When I do my api call with postman everything works great.

How do I test an asmx webservice function with a complex object being its parameter?

I have a webservice with a parameter of type class e.g.

[Webmethod]
public string functionA(ClsParams objParam)
{

}

The class has reference to another class object in it and functions.

Now before handing it over to the client, I want to test it. I don't want to develop a UI for this but want to use the default asmx testing UI that appears in browser but for complex objects it is not giving me the text boxes like it does in case of params like string param1, string param2 to the function.

How do I test it?

I want to Automate on Active Inactive Buttons with this aria-hidden="true"

Want to click on Active inactive buttons on webtable having following Css

Tried with //td[contains(text(),'100003')]/following-sibling::td/div/ul/li/a/i[@id='active'] xpath

public

public

Tried with //td[contains(text(),'100003')]/following-sibling::td/div/ul/li/a/i[@id='active'] xpath

mercredi 25 septembre 2019

Intune Managed Browser Test Automation(Both Android and iOS)

I have requirement to automate MobileWeb use cases using "Intune Managed Browser" in both Android and iOS. Is it possible to do this using appium or any other tool? If yes please help me through this.

Find the Count of Random Serial Numbers from response data and Find Duplicate Numbers from Response data in Jmeter

i have query on how to find the count of the random serial numbers which are getting in Jmeter response and find the duplicate serial numbers from the generated serial numbers.

Jmeter Response Data:

C5FV55WGJC

C5FX1N257P

C5G0F54VPN

C5G77R09CD

C5G7L33Y2T

C5G7X7NWYF

C5FX1N257P

From above response data i need to count the numbers and find the duplicate numbers from response.

can you please help me out on this. Thanks in advance!

How do I resolve this bean defninition override?

I've upgraded from Spring Boot 1.5 to Spring Boot 2.1.8. I had some tests that were working but are now failing. I also was using maven-surefire plugin at version 2.9 and it worked, but I upgraded that to 2.22.0 as well, if that matters.

@ExtendWith(SpringExtension.class)
@WebMvcTest(value = ElementController.class, secure = false)
@ContextConfiguration(classes = TestSite1Config.class)
public class ElementControllerSite1IT {
  @Autowired
  protected MockMvc mvc;
  @MockBean
  ElementService elementService;
  @BeforeEach
  public void setup() {
    when(elementService.getElementTable( ... )) //skipping args for brevity
       .thenReturn(new ElementTable());
  }

  @Configuration
  public static class TestSite1Config {
    @Bean
    @Autowired
    public ElementController elementController(final ElementService elementService) {
      return new ElementController(elementService, new ElementControllerProperties(DeploymentLocation.SITE1));
  }

  @Test
  public void failSite1ValidationWithoutId() throws Exception {
    ElementParameters params = getParams(false);
    mvc.perform(post("/element")
      .contentType(JSON)
      .andExpect(status().isBadRequest());
  }

  //more tests, but doesn't matter.
}

There's another class like above, but replace Site1 with Site2.

There is an ElementController & Service class as well.

I get this exception:

Caused by BeanDefinitionOverrideException: Invalid bean definition with name 'elementController' defined in class path resource [ui/v2/web/ElementControllerSite1IT$TestSite1Config.class]: Cannot register bean definition [Root bean: class [null]; ... defined in class path resource [ui/v2/web/ElementControllerSite1ITConfig.class] for bean 'elementController': There is already [Generic bean: class [ui.v2.web.ElementController]; .. defined in file [...ui/v2/web/ElementController.class]] bound.

I didn't write the tests, it's code that I've inherited, in a code base that I'm just getting spooled up on.

How to mock RequestEntity.put() and restTemplate.exchange() in Spock groovy

Java code for api call

I want to know how to test the below two lines of code.

private void api(){
    //Code to call an API and i want to test this in groovy spock
    HttpHeaders httpHeaders = new HttpHeaders();      
    httpHeaders.setAccept(Arrays.asList(MediaType.APPLICATION_JSON); 
    httpHeaders.setContentType(MediaType.APPLICATION_JSON);
    RestTemplate restTemplate = new RestTemplate();
    String url ="url";
    String body ="body";
    //How to mock below line
    RequestEntity<String> requestEntity = RequestEntity.put(new URI(url)).contentType(MediaType.APPLICATION_JSON).body(body);
    //And this line
    ResponseEntity<String> responseEntity = restTemplate.exchange(requestEntity,String.class);
    HttpStatus StatusCode = responseEntity.getStatusCode();
}

Writing unit tests for I/O functions in Rust [duplicate]

In C++, I have often used the following pattern to create testable functions:

MyType readfile(std::ostream& file) {
    // Read file and do stuff
    return MyType;
}

MyType readfile(const std::string& filename) {
     std::ofstream file(filename);
     return readfile(file);
}

This allows me to test the reading of the file by constructing a file in memory by using a std::stringstream and sending it to the first overload of the function. I could read a secondary test file, but I have found this pattern to be convenient.

Is there any idiomatic way to accomplish the same thing in Rust?

If I have to create some test data, then where is the standard location to keep this data in a Rust project?

I need the graph to be ramp up,hold for sometime,rampdown (not all the way down)then rampup,hold for sometime,rampdown for a total of 4hrs test

I am using ultimate thread group in jmeter.I need the cycle should be a 5 minute rampup, followed by by a 10 minute peak usage,followed by a 5 minute ramp down for a total of 4hrs run time.

How to get url to action method from ModelViewSet(Django Rest Framework) with reverse function?

I have this ModelViewSet class:

class DriveInvoiceViewSet(viewsets.ModelViewSet):
    filter_fields = ('location_id', 'logical_deleted')
    permission_classes = (UserCanManageFacilityPermission,)
    pagination_class = None

    def get_serializer_class(self):
        ...

    def get_queryset(self):
        ...

    @action(detail=False, methods=['GET'])
    def get_subtotals_by_unit(self, request):
        invoices_list = self.filter_queryset(self.get_queryset())
        grouped_invoices = get_subtotals_by_unit(invoices_list)

        return Response(grouped_invoices)

How can I get the URL from reverse function to test the get_subtotals_by_unit action?

The ViewSet registred by the router router.register('drive_invoices', DriveInvoiceViewSet, base_name='drive_invoices')

Illegal reflective access on selenium tests

I having a strange issue with my selenium test

When im opening my chrome browser im receiving 2 errors:

[1569419754.430][WARNING]: Timed out connecting to Chrome, retrying...

[1569419759.899][WARNING]: Timed out connecting to Chrome, retrying...

before the browser actually opens. I also noticed at the end of the test there are numerous warnings:

WARNING: An illegal reflective access operation has occurred

WARNING: Illegal reflective access by org.openqa.selenium.os.ProcessUtils

WARNING: Please consider reporting this to the maintainers of org.openqa.selenium.os.ProcessUtils

WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations

WARNING: All illegal access operations will be denied in a future release

Ive tried updating the the

    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>3.0.1</version>
    </dependency>

but it then broke all my tests and i couldnt initialize the browser, anyone else have this issue?

Does snapshot testing replace css regression test?

I've been working with React and use SnapShot testing in order to figure out any unintentional changes could happen to the code. Recently I figure out a term called CSS regression testing, so I'm wondering what's the difference/s between those testing/solution?

JavaScript for-in Loop Stuck

I'm writing this looping test in Mocha, trying to get it to visit a url taken from sitesObj, do a test, then repeat with the others. The only problem is the url variable is "https://www.example.com/about" throughout all of the tests.

In short: test.describe(site... is working in the loop, but driver.get(url... is not.

My code is below. Any help is very much appreciated!

//Driver + test setup
var sitesObj = {
    "Homepage": "https://www.example.com",
    "About Page": "https://www.example.com/about"
}

for (site in sitesObj) {
    var cid;
    var pageName = site;
    var url = sitesObj[site];

    test.describe(site + ' CID Cookie Set Test', function() {

        test.beforeEach(function(done) {
            //Driver stuff
            cid = Math.random().toString(36).substring(2, 6);

            console.log(url + '?cid=' + cid);  //URL is ALWAYS ...site.com/about... 
            driver.get(url + '?cid=' + cid);   //URL is ALWAYS ...site.com/about...

            driver.manage().timeouts().implicitlyWait(10000);
            done();
        });

        //afterEach, quit, done
        //Test 1, done
        //Test 2, done
    });
}

Angular jasmine toHaveBeenCalledWith with queryParams not working

I have this test:

it('should redurect to admin programs', () => {
    ...

    expect(navigateSpy).toHaveBeenCalledWith(['/admin/programs', {queryParams: {pub_status: 'active'}}]);
});

And its throwing this error:

Error: Expected spy navigate to have been called with 
[ [ '/admin/programs', Object({ queryParams: Object({ pub_status: 'active' }) }) ] ] but actual calls were 
[ [ '/admin/programs' ], Object({ queryParams: [ pub_status: 'active' ] }) ].

How do I solve it? This annotation is very strange:

{ queryParams: [ pub_status: 'active' ] } <-- wtf this is not a proper array

Thanks!!

Cypress cy.request() does not set Cookies from response

I am trying to is to log in to the testing environment programatically like in the Best Practices.

I've came to the point that I am making valid requests to obtain authorization token and other data like cookies etc - I have this data at the console:

example results

As far as I know cookies at "set-cookie" key from requests' response should be set at the browser. That is not happening - and I think this is the problem why after making these requests I cannot navigate to subpages of the development server of the app.

My investigation led me here: https://github.com/github/fetch/issues/386 -- but I couldn't make use of it. Folks there are saying that there is a problem when you don't define baseUrl. But I did, tried again and still no luck. My cookies are still empty.

This is my code:

the code

as you can see my API URL differs from the server URL - maybe it is useful info.

Content in reactstrap modal continues to exist after closing using enzyme/jest

I'm trying to do some testing with enzyme and jest in react, and things work fine when I open a modal e.g. input fields in the modal aren't there and the modal state is false (as intended) when I try to find them using

expect(wrapper.find("input")).toHaveLength(0);

and do exist after I've opened the modal using

const edit = wrapper.find("Button.update-button");
edit.simulate("click");
expect(wrapper.find("input")).toHaveLength(2);

which all works (including the modal state turning to true after it opens) as intended. But when I close the modal, the state gets toggled off correctly, but the modal content (e.g. the input boxes and buttons in the modal) still exist when I try:

expect(wrapper.find("input")).toHaveLength(0);

I still somehow have 2 input fields that shouldn't be there as the modal is closed.

Here is my code for the component I am trying to test if that helps:

/*
    Artefact Component displays just UI for the Artefact itself and it's information.
*/

import React, { Component } from "react";

import DeleteArtefact from "../DeleteArtefact";
import UpdateArtefact from "../UpdateArtefact";

import {
    Card,
    CardImg,
    CardTitle,
    CardBody,
    ButtonGroup,
    Button,
    CardFooter
} from "reactstrap";

class Artefact extends Component {
    // Initialise State
    state = {
        updatemodal: false,
        deletemodal: false
    };

    // Toggle function for toggling modal open/close
    toggleUpdate = () => {
        this.setState({
            updatemodal: !this.state.updatemodal
        });
    };

    toggleDelete = () => {
        this.setState({
            deletemodal: !this.state.deletemodal
        });
    };

    prepareUpdateState = () => {
        this.props.editUpdate(this.props.artefact);
        this.toggleUpdate();
    };

    render() {
        const {
            artefact,
            onChange,
            onUpdateClick,
            editUpdate,
            onDeleteClick
        } = this.props;
        return (
            <Card>
                <CardImg
                    src={artefact.img}
                    alt={`Image for Artefact ${artefact.name}`}
                />
                <CardBody>
                    <CardTitle>
                        <h6>{artefact.name}</h6>
                    </CardTitle>
                </CardBody>
                <CardFooter>
                    <ButtonGroup>
                        <Button
                            className="update-button"
                            color="dark"
                            onClick={this.prepareUpdateState}
                        >
                            Edit
                        </Button>
                        <Button
                            className="delete-button"
                            color="dark"
                            onClick={this.toggleDelete}
                        >
                            Delete
                        </Button>
                    </ButtonGroup>
                    <UpdateArtefact
                        artefact={artefact}
                        onChange={onChange}
                        onUpdateClick={onUpdateClick}
                        editUpdate={editUpdate}
                        toggle={this.toggleUpdate}
                        modal={this.state.updatemodal}
                    />
                    <DeleteArtefact
                        _id={artefact._id}
                        onDeleteClick={onDeleteClick}
                        toggle={this.toggleDelete}
                        modal={this.state.deletemodal}
                    />
                </CardFooter>
            </Card>
        );
    }
}

export default Artefact;

And here is the UpdateArtefact Component that has the modal I'm trying to test:

/*
    UpdateArtefact Component is a child Component of ArtefactGallery and
    creates a new Artefact by using functions onChange() and updateClick() 
    and editUpdate() which are passed as props from ArtefactGallery and 
    passes state back up and makes api calls using axios.
*/

import React, { Component } from "react";
import {
    Button,
    Modal,
    ModalHeader,
    ModalBody,
    Form,
    FormGroup,
    Label,
    Input
} from "reactstrap";

class UpdateArtefact extends Component {
    // Passes state up to ArtefactGallery component and updates the artefact.
    onSubmit = e => {
        e.preventDefault();
        this.props.onUpdateClick(this.props.artefact._id);
        this.props.toggle();
    };

    // Sets state in ArtefactGallery to the initial values of the artefact
    // to prepare for any edits to be made in the case that some fields have
    // no change, so that there are no null fields.
    prepareUpdateState = () => {
        this.props.editUpdate(this.props.artefact);
        this.props.toggle();
    };

    render() {
        const { artefact } = this.props;
        return (
            <div style=>
                <Modal isOpen={this.props.modal} toggle={this.props.toggle}>
                    <ModalHeader toggle={this.props.toggle}>
                        Edit Artefact
                    </ModalHeader>
                    <ModalBody>
                        <Form onSubmit={this.onSubmit}>
                            <FormGroup>
                                <Label>Artefact</Label>
                                <Input
                                    type="text"
                                    name="name"
                                    id="artefactName"
                                    defaultValue={artefact.name}
                                    onChange={this.props.onChange}
                                />
                                <Label>Image</Label>
                                <Input
                                    type="text"
                                    name="img"
                                    id="artefactImg"
                                    defaultValue={artefact.img}
                                    onChange={this.props.onChange}
                                />
                                <Button
                                    className="modal-submit-button"
                                    color="dark"
                                    style=
                                    block
                                >
                                    Submit
                                </Button>
                            </FormGroup>
                        </Form>
                    </ModalBody>
                </Modal>
            </div>
        );
    }
}

export default UpdateArtefact;

So basically I just want to know what the reason if for why the modal content is still being picked up by enzyme and how to fix this. I've tried searching all over but couldn't find an answer so I'm guessing there's something obvious that I'm missing.