Code Bug Fix: How to Use Assert.Contain on C#, Selenium

Original Source Link

How can I check if a name on a headline is the same as a specific text?

Assert.Contains("Text", _driver.FindElement(By.CssSelector("body > div.content > header > h1")));

This is not correct :(.

Second question is, how can I choose (IWebElement and click on it) to open a dropdown menu? I tried finding the element through XPath, CssSelecton, TagName, etc, but nothing seems to happen.

The attribute from my question is:

<a href="javascript:;" class="nav-link header-dropdown-link" data-toggle="dropdown" aria-expanded="true">
    <span class="cell">Обучения</span>
</a>

Maybe you can do this :

Assert.AreEqual(text, driver.FindElement(By.CssSelector("body > div.content > header > h1")).Text);

Or Contains :

Assert.True(driver.FindElement(By.CssSelector("body > div.content > header > h1")).Text.Contains("Text you want check"));

Or Equals :

Assert.True(driver.FindElement(By.CssSelector("body > div.content > header > h1")).Text.Equals("Text you want check"));

I hope this can help you.

Tagged : / /

Code Bug Fix: Jest integration with Adonis V5

Original Source Link

I’m developing an application with Adonis v5 but its test runner isn’t finished. So, my workaround is to apply Jest in its place. I got this working but I’m having trouble importing types from Adonis.

In any model, I have the following import:

import { BaseModel, column } from '@ioc:Adonis/Lucid/Orm'

To solve the alias, I added this rule in jest.config.js:

moduleNameMapper: {
  '^App(.*)$': '<rootDir>/app$1',
  '^@ioc:Adonis/Lucid/Database$': '@adonisjs/lucid/build/src/Database/index.js',
  '^@ioc:Adonis/Lucid/Orm$': '@adonisjs/lucid/build/adonis-typings/orm.d.ts',
  //'^@ioc:Adonis/Core/Validator$': '',
},

The third rule points to the previous import. Inside of the pointed file, I found the declaration of a module which exports the desired types.

declare module '@ioc:Adonis/Lucid/Orm' {
    import { ScopeFn, LucidModel, HooksDecorator, ...
    ...

The complete file is this.

When I run Jest, I get this error. What am I missing? Before I forget, I’m using ts-jest to define the settings of Jest.

enter image description here

Tagged : / / / /

Code Bug Fix: How do I test Sentry tags that are sent from a Django app exception?

Original Source Link

Our Django application is configured to send all logger.errors and logger.exceptions to Sentry. I’m trying to implement something where in some cases, I can assign a custom tag to the event in question before the exception hits and have that event be tagged appropriately. Since I’m using it in more than one place, I want to make a function like this:

from sentry_sdk import push_scope

def set_sentry_custom_tag(key: str, value: str) -> None:
    with push_scope() as scope:
        scope.set_tag(key, value)
        logger.info(f'Set sentry custom tag -> {key}:{value}')

…and use it like so:

try:
    check_widget_factory()
except Exception as e:
    set_sentry_custom_tag('my-tag-key', 'my-tag-value')
    logger.exception(f'Widget check failed: {e}')

I think this will work but not sure if the push_scope needs to be directly in the method where the exception happens– I’m a little fuzzy on how the Scope works for Sentry and if it is in some context in the immediate frame before getting passed on to the logger handling which sends the event to Sentry.

I’m trying to write some tests to ensure that this tag is set appropriately and attached to the event when an exception is raised, but coming up empty so far as to how to get the local scope and verify that the tag is set. I can modify the function to return the scope and then examine it like that, but ideally that’s not how it’s going to behave in production. I need something along the lines of this:

def test_set_sentry_custom_tag(self):
    set_sentry_custom_tag(key='test-key', value='test-value')
    scope = find_the_current_scope_somehow()
    self.assertIn('test-key', scope._tags.keys())
    self.assertEqual(scope._tags['test-key'], 'test-value')

Anyone done some custom tagging in Sentry for cases like this, and can share how testing was done?

Quite frankly I believe your last example is not a particularly useful unit test. I would much rather mock check_widget_factory() to throw an exception and assert that an event got sent through. To do that, consider this:

events = []
init(transport=events.append)
# <mock check_widget_factory() here>

# call your try-except code here

assert events[0]['tags']['my-tag-key'] == 'my-tag-value'

This is not significantly slower than checking whether setting the tag actually set the tag and does not rely on private APIs in the SDK.

Tagged : / / /

Code Bug Fix: Multiple hypothesis testing using replicate data in R

Original Source Link

In the following data frame, I want to calculate p-values for each protein comparing the ‘control’ replicates and the ‘treated’ replicates. I am very new to using R and I just want to see if I can shift away from using Excel for tasks like these. In reality, I’ll have thousands of proteins. I’ll then use p.adjust() to correct for the multiple hypothesis testing.

I’d be very grateful for any advice.

Protein Control_1 Control_2 Control_3 Treated_1 Treated_2 Treated_3
1       1      7.15      7.16      7.11      6.91      6.88      6.92
2       2      6.64      6.61      6.59      6.37      6.35      6.41
3       3      3.68      3.78      3.81      2.40      2.09      2.17
4       4      5.04      5.01      4.69      3.43      3.52      3.66
5       5      6.92      6.81      6.90      7.12      7.21      7.27

Desired: –

Protein Control_1 Control_2 Control_3 Treated_1 Treated_2 Treated_3 P-value
1       1      7.15      7.16      7.11      6.91      6.88      6.92      0.000413
2       2      6.64      6.61      6.59      6.37      6.35      6.41      0.000742
3       3      3.68      3.78      3.81      2.40      2.09      2.17      0.001010
4       4      5.04      5.01      4.69      3.43      3.52      3.66      0.001262
5       5      6.92      6.81      6.90      7.12      7.21      7.27      0.004306

Updated with @StupidWolf’s comment.

Since you are new to R I am providing an easy to understand and modify solution.

# Generate data that looks like yours
df <-  data.frame(Protein=1:5,Control_1=rnorm(5,5),Control_2=rnorm(5,5),
           Control_3=rnorm(5,5),Treated_1=rnorm(5,5),Treated_2=rnorm(5,5),
           Treated_3=rnorm(5,5))
p_vals <- rep(NA,nrow(df))
for(i in 1:nrow(df)){
  i.p_val <- t.test(df[i,grep("Control",colnames(df))],
                    df[i,grep("Treated",colnames(df))])$p.value
  p_vals[i] <- i.p_val
}
df <- cbind(df,Pvalue=p_vals)
df

should give you

  Protein Control_1 Control_2 Control_3 Treated_1 Treated_2 Treated_3    Pvalue
1       1  5.813581  5.149145  4.662203  5.481839  6.424654  5.503664 0.2621811
2       2  4.191440  6.155372  5.773128  3.941712  5.945056  4.182457 0.4769504
3       3  4.654504  4.598808  5.258675  4.101895  6.135411  4.276641 0.9993112
4       4  5.426672  4.520739  6.293757  3.787395  5.274740  3.847900 0.1909877
5       5  5.614929  6.993289  3.786346  5.193352  5.362928  4.746676 0.7353676

You can change it from t.test() to other tests like non-parametric ones if you like.

Tagged : / /

Code Bug Fix: Docker testcafe is not redirecting URL

Original Source Link

In my test I am getting a URL from emails.

For some reason I dont have any issue on local to run the test and redirect the URL.

But when I try to open

http://link.novemberfirst.com/ls/click?upn=xv2uBCiA-2BCPo8h2-2F2dXgSrKknBTgupgeogOdcsRpYXuG4cjYbJP1rkCCJ1zjXTj38aokCt-2BgUcrLMVeDJ0JrF7Ry6Ee0aZxSmG0XBUT-2BfpLXK1QwUbsPzLWqmCI45mm6FVK4qQ4FeVr5G-2FPGZPIh3V4uSvjAAVesvyFS70sNYMmEuHwijMEm15Rt-2B-2FXdpqN9QwJk_RF7xy92VlUUZPAd3I4NLqBUoMbDzj54KyMFdERKAfBSrROBp9LUCJ8-2BKihq3WlzdQqHhDJoeaQIbj0IyYe1ZWIJZFL3VhIxjYS2DFnc8l81Xk2gFmeuMrUrCgkvgbjPvLFOuWsVBzmzzenAuX79EDOgwJtZzz3MyXdUlI4i9jp2PZbjylmky69iNt73-2F52qpGCZ6-2BxhbIEnBTiXJSyh-2BvM1ZRz0gdXcXqFm9xykFWpI-3D

It wont open the link inside a container environment.

await t.navigateTo(url);

I tried both on Firefox and Chrome.

Tagged : / / / /

Code Bug Fix: Toast not showing in espresso test

Original Source Link

I wanted to test a Toast message using Espresso, but when I am calling the method to show toast, the toast is not showing.
It shows when I run the app normally, but when I run the test, no toast shows up.

fun Context.showMessage(@StringRes message:Int){
    Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
}

I am calling showMessage() in the TestFragment’s showMessage method which is called in FragmentScenario’s onFragment

override fun showMessage(message: Int) {
    context?.showMessage(message)
}
val scenario = launchFragmentInContainer<TestFragment>()
scenario.onFragment {
     it.showMessage(R.string.test_string)
     onView(withText(it.context.getString(R.string.test_string))
          .inRoot(ToastMatcher())
          .check(matches(isDisplayed()))
}

The test case is just stuck at

check(matches(isDisplayed()))

and I guess its because there is no toast displayed.

Move the espresso assertion outside of onFragment().

scenario.onFragment { it.showMessage(R.string.test_string) }
onView(withText(R.string.test_string))
     .inRoot(ToastMatcher())
     .check(matches(isDisplayed()))

ps: withText() accepts String resources ids.

Tagged : / / / /

Code Bug Fix: Why does Go test with blocked channel not reporting deadlock

Original Source Link

I met a strange issue when doing test with channels.

In a normal main function, the following code will report the deadlock error.

package main

import (
    "fmt"
)

func main() {
    c := make(chan int)
    c <- 1
    fmt.Println(<-c)
}

But on my machine, this simple test seems deadlocked or blocked forever or just fails to exit for whatever reason I don’t know. I invoked the test in both Emacs and terminal, and I got the same result. The command is go test -run TestChan$ . -v -count=1. I tried with a simpler command (go test -run TestChan) but still got the same result. I tried it on Go playground (here) and it reported the deadlock error. Is there something wrong with my Go environment?

package main

import (
    "fmt"
    "testing"
)

func TestChan(t *testing.T) {
    c := make(chan int)
    c <- 1
    fmt.Println(<-c)
}

—————————————————————————————————-

Update

Looks like I haven’t made my question clear. The situation is: the same test behaves differently on my machine and on Go playground. Now I set -timeout 5s, but the error message is different from that on Go playground.
Another thing I found different with my local is that the test runner seems different from my local. It’s under package go-faketime.

local output

$ go test main_test.go -timeout 5s
panic: test timed out after 5s

goroutine 17 [running]:
testing.(*M).startAlarm.func1()
    /usr/local/go/src/testing/testing.go:1460 +0xdf
created by time.goFunc
    /usr/local/go/src/time/sleep.go:168 +0x44

goroutine 1 [chan receive]:
testing.(*T).Run(0xc000108120, 0x1141975, 0x8, 0x114a528, 0x1075a96)
    /usr/local/go/src/testing/testing.go:1044 +0x37e
testing.runTests.func1(0xc000108000)
    /usr/local/go/src/testing/testing.go:1285 +0x78
testing.tRunner(0xc000108000, 0xc000066e10)
    /usr/local/go/src/testing/testing.go:992 +0xdc
testing.runTests(0xc00000c060, 0x1236220, 0x1, 0x1, 0x0)
    /usr/local/go/src/testing/testing.go:1283 +0x2a7
testing.(*M).Run(0xc000106000, 0x0)
    /usr/local/go/src/testing/testing.go:1200 +0x15f
main.main()
    _testmain.go:44 +0x135

goroutine 6 [chan send]:
command-line-arguments.TestChan(0xc000108120)
    /Users/james/prog/allez/mtest/main_test.go:10 +0x59
testing.tRunner(0xc000108120, 0x114a528)
    /usr/local/go/src/testing/testing.go:992 +0xdc
created by testing.(*T).Run
    /usr/local/go/src/testing/testing.go:1043 +0x357
FAIL    command-line-arguments  5.013s
FAIL

Go playground output

=== RUN   TestChan
fatal error: all goroutines are asleep - deadlock!

goroutine 1 [chan receive]:
testing.(*T).Run(0xc00011a120, 0x4f71c0, 0x8, 0x4ff688, 0x498336)
    /usr/local/go-faketime/src/testing/testing.go:1043 +0x37e
testing.runTests.func1(0xc00011a000)
    /usr/local/go-faketime/src/testing/testing.go:1284 +0x78
testing.tRunner(0xc00011a000, 0xc000066df8)
    /usr/local/go-faketime/src/testing/testing.go:991 +0xdc
testing.runTests(0xc00010c040, 0xc00010c020, 0x1, 0x1, 0x0)
    /usr/local/go-faketime/src/testing/testing.go:1282 +0x2a7
testing.(*M).Run(0xc000118000, 0x0)
    /usr/local/go-faketime/src/testing/testing.go:1199 +0x15f
testing.Main(0x4ff690, 0xc00010c020, 0x1, 0x1, 0x0, 0x0, 0x0, 0x5e8860, 0x0, 0x0)
    /usr/local/go-faketime/src/testing/testing.go:1126 +0xd4
main.main()
    /tmp/sandbox970213620/prog.go:24 +0x9c

goroutine 18 [chan send]:
main.TestChan(0xc00011a120)
    /tmp/sandbox970213620/prog.go:10 +0x59
testing.tRunner(0xc00011a120, 0x4ff688)
    /usr/local/go-faketime/src/testing/testing.go:991 +0xdc
created by testing.(*T).Run
    /usr/local/go-faketime/src/testing/testing.go:1042 +0x357

My questions are

  • Why does Go test with blocked channel not reporting deadlock?
  • If it’s work-as-design (because there are other goroutines running meanwhile), then how does the same test in Go playground reports the same error message as if the code is run in a main func? (this question diverges from the domain of Go channel to how Go Playground handles test)
Tagged : / / / /

Code Bug Fix: Testing spring-cloud-stream with their test-binder always throws MessageDeliveryException: Dispatcher has no subscribers for channel

Original Source Link

I’m trying to write tests for my message producers. But whenever i try to send a message using the injected Bindings i get following error

Caused by: org.springframework.integration.MessageDispatchingException: Dispatcher has no subscribers, failedMessage=GenericMessage [payload=..., headers={spanTraceId=0761b2d61b665041, spanId=e3b298682fefe198, spanParentSpanId=549ea87126d2484d, nativeHeaders={X-B3-TraceId=[0761b2d61b665041], spanTraceId=[0761b2d61b665041], X-B3-SpanId=[e3b298682fefe198], spanId=[e3b298682fefe198], X-B3-ParentSpanId=[549ea87126d2484d], spanParentSpanId=[549ea87126d2484d], X-B3-Sampled=[0], spanSampled=[0]}, X-B3-SpanId=e3b298682fefe198, X-B3-ParentSpanId=549ea87126d2484d, X-B3-Sampled=0, X-B3-TraceId=0761b2d61b665041, id=0c885a37-a1b1-fc0a-1314-e403ec1bffdb, spanSampled=0, contentType=application/json, timestamp=1589551815143}]
    at org.springframework.integration.dispatcher.UnicastingDispatcher.doDispatch(UnicastingDispatcher.java:138)
    at org.springframework.integration.dispatcher.UnicastingDispatcher.dispatch(UnicastingDispatcher.java:105)
    at org.springframework.integration.channel.AbstractSubscribableChannel.doSend(AbstractSubscribableChannel.java:73)
    ... 42 more

Since I’m testing the message producers there naturaly are no consumers in my code. How can i fix this exception?

Here is a minimal test class i created that shows the same behaviour:

@RunWith(SpringRunner.class)
@ActiveProfiles("test")
@SpringBootTest(classes = {MessagingTest.SampleConfiguration.class, Application.class, EventMockConfiguration.class})
public class MessagingTest {

    @Autowired
    private LibraryMessageSource libraryMessageSource;

    @Autowired
    private InputDestination input;

    @Autowired
    private OutputDestination output;

    @Test
    public void test() throws Exception {
        libraryMessageSource.creations().send(MessageBuilder.withPayload("test").build());
    }

    @SpringBootApplication
    @Import({TestChannelBinderConfiguration.class})
    public static class SampleConfiguration {

    }
}

Note: Application.class the main class for my app and EventMock overwrites a bean in the context with a specific mock.

public interface LibraryMessageSource {

    String LIBRARY_CREATE = "messages-library-create";
    String LIBRARY_UPDATE = "messages-library-update";

    @Input(LIBRARY_CREATE)
    MessageChannel creations();

    @Input(LIBRARY_UPDATE)
    MessageChannel updates();
}

Since I’m testing the message producers

Your application has a consumer, not a producer

    @Input(INPUT)
    MessageChannel events();

and you have no @StreamListener subscribed to it.

    @Test
    public void test() throws Exception {
        libraryMessageSource.events().send(MessageBuilder.withPayload("test").build());
    }

Tagged : / / /

Code Bug Fix: How to configure Test Outcomes in TestPlans in Azure Devops

Original Source Link

I’m new to using TestPlans in Azure DevOps and need a couple more Test Outcomes than the standard ones provided. How do I configure the available Test Outcomes. I need to add ‘Queried’, ‘Concession’ and ‘ReTest’.

In our current Test Management software we use ‘Queried’ for where someone has expressed the test incorrectly (since this isn’t a fail), ‘Concession’ for allowing failures into a release and ‘ReTest’ to signal that a defect has been fixed.

How do I manage this in TestPlans in Azure DevOps?

As far as I know, we cannot customize the Test Outcomes in Azure DevOps. We can only use the existing ones (passed, failed, blocked or not applicable). Please refer to New Test Plans page for details.

However, you can try to tag the test cases. Please refer to Q: Can I tag test cases so that I can see only tests with specific tags? for details.

Tagged : /

Code Bug Fix: Spring SecurityContextHolder getPrincipal model.User vs. userDetails.User

Original Source Link

During runtime, when i retrieve autheticated user like this:

SecurityContextHolder.getContext().getAuthentication().getPrincipal()

I get User from the model of my application:

test.package.model.User

When i retrieve user during testing, i get user from UserDetails:

org.springframework.security.core.userdetails.User

I’am testing my beans with MockMvc as autheticated User.
During the test, i’am using InMemoryUserDetailsManager:

    @SuppressWarnings("unchecked")
    private Collection<UserDetails> users = Collections.emptyList();

    @Bean
    @Primary
    public UserDetailsService userDetailsService() {

        /** User from application model, not userDetails.User type */
        User user = new User("bob")
        users = Arrays.asList(user);
        InMemoryUserDetailsManager inMemoryUserDetailsManager = new InMemoryUserDetailsManager(users);
        return inMemoryUserDetailsManager;
    }

    public Collection<UserDetails> getUsers() {
        return users;
    }

And my Request during the test looks like this:

@WithUserDetails("bob") 
public void showUser() throws Exception {
    this.mockMvc.perform(get("/user"))
                .andDo(print());
}

I would like to keep it consistent during runtime and testtime.
Which User-Type should i work with? And why?

without sending a request to you application you have the default context

so the user stocked in this context is an instance of

org.springframework.security.core.userdetails.User

but when yo send a request to your application the context will change.

Tagged : / / /