I come from testig background (selenium ) and am new to spring framework.My current project is using spring framework. Can anyone tell me in laymans language about the spring annotations as @scope(prototype),@autowiring,@bean etc. Thanks in advance.
jeudi 31 mai 2018
Inspec test cases for windows authentication
I am trying to validate (mssql) Sql authentication mode "Integrated" using inspec. I was not able find any reference. How to pass sql query using ruby as i am having sql query which displays the current sql authentication mode.
Angular 6 Unit testing: I want to stub a declared property for my test
I'm using angular version 6 and jasmine.
When I run ng test --sourceMap=false
Error I get is: videojs is not defined
I would like to stub videojs if possible.
My component that I'm testing:
import { AfterViewInit, Component } from '@angular/core';
declare const videojs: any;
@Component({
selector: 'test-details',
templateUrl: './test-details.component.html'
})
export class TestDetailsComponent implements AfterViewInit {
public videoJSplayer: any;
constructor() {}
ngAfterViewInit(): void {
this.initVideo();
}
public initVideo(): void {
this.videoJSplayer = videojs(
document.getElementById('video_player_id'),
{ controls: true, autoplay: false, preload: 'auto' }
);
}
}
My Unit test
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { TestDetailsComponent } from './test-details.component';
declare const videojs: any;
fdescribe('TestDetailsComponent', () => {
let component: TestDetailsComponent;
let fixture: ComponentFixture<TestDetailsComponent>;
beforeEach(
async(() => {
TestBed.configureTestingModule({
imports: [],
declarations: [ TestDetailsComponent ],
schemas: [ CUSTOM_ELEMENTS_SCHEMA ]
}).compileComponents();
})
);
beforeEach(() => {
fixture = TestBed.createComponent(TestDetailsComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(true).toBeTruthy(true);
});
});
How to avoid triggering captcha on Google login in selenium?
I'm doing a test for "login with google" on my website. The problem is that I run the test it works sometimes but often times the Google login popup displays a captcha challenge which fails my test. Is there any way to avoid getting asked for captcha entry in Selenium?
vcr.py store call from twitter api
I want to use https://github.com/bear/python-twitter/ and check API requests https://github.com/kevin1024/vcrpy or https://github.com/agriffis/vcrpy-unittest.
From lines 30:
https://github.com/bear/python-twitter/blob/master/twitter/api.py#L30
30: import requests
and later on:
res = requests.post(url='https://api.twitter.com/oauth2/token',
data={'grant_type': 'client_credentials'},
headers=post_headers)
# ... etc ...
Yet when doing something like:
from vcr_unittest import VCRTestCase
import vcr
import twitter
from django.conf import settings
class TwitterRetrievalAndStorageTests(VCRTestCase):
@vcr.use_cassette()
def test_recorded_session(self):
api = twitter.Api(
consumer_key=settings.TWITTER_CONSUMER_KEY,
consumer_secret=settings.TWITTER_CONSUMER_SECRET,
access_token_key=settings.TWITTER_ACCESS_KEY,
access_token_secret=settings.TWITTER_ACCESS_SECRET)
statuses = api.GetUserTimeline(screen_name='nntaleb')
for s in statuses:
print(s)
Not a cassette file is being created. Is there a way to do this with python-twitter?
Prestashop 1.7 layered navigation block needs to show on other pages too not only category pages
As title said i want to display layered navigation block in other pages like custom search module page. How can i achieve this? Any help is appreciated!
How to hide javascript,web framework version details from weppalyzer
start to testing sonata admin bundle?
Im finding for test sonta forms. but i not have ide. i execute the comand
./vendor/bin/phpunit --debug tests/AppBundle/Controller/ManualTest.php
I habe 2 problems:
- I can't obtain the errors of the form
- I can't add child forms in the form
My test is like this:
/** @var string $uniqid */
$form = $crawler->selectButton('Crear y editar')->form(array(
));
parse_str(parse_url($form->getFormNode()->getAttribute('action'))['query']);
$form["{$uniqid}[fechaEmision]"]->setValue('31/05/2018');
$crawler = $this->client->submit($form);
$this->assertEquals(0, $crawler->filter('.error_list')->count());
I want to learn to make better tests.
unable to write mockito test case for my void method
public class Calculation {
public void logTimeTaken(String label, long estimatedTime, int size, boolean isDebug) { out = label + " took " + TimeUnit.MILLISECONDS.convert(estimatedTime, TimeUnit.NANOSECONDS) + " milliseconds for " + size + " events!"; if (isDebug) { System.out.println(out); } else { System.out.println("if isDebug is false "+out); } }
I need to test this code with mockito(junit) ,I search so many examples google but still not getting any idea,kindly help me in this
How to write integration tests depending on Druid?
I am coding an application that generates reports from a Druid database. My integration tests need to read data from that database.
My current approach involves creating synthetic data for each of the tests. However, I am unable to remove data created from the database (be it by removing entries or completely dropping the schema) as described here.
I think that either I am completely wrong with my approach or there is a way to delete information from the database that I haven't been able to find.
Constructor functionality fails to path jest test
I have the following constructor that should be modified in order to pass JEST testings.
(function() {
var MODULE_NAME = 'shoppingcartModel',
_VATRate = 20,
_getCart;
window[MODULE_NAME] = function() {
_getCart = function() {
return {
products: [],
total: {
beforeVAT: 0,
afterVAT: 0,
VAT: 0
}
};
return {
init: function(VATRate) {
return _Cart.total.VAT = VATRate || 0;
},
getCart: _getCart,
addProducts: function(newOrExistingProducts) {
return _Cart.products.push(newOrExistingProducts);
},
... other stuff
};
};
})()
And the test describes the following way
describe(`NO product added`, () => {
test(`cart`, () => {
const instance = window[MODULE_NAME]();
const emptyCart = {
products: [],
total: {
beforeVAT: 0,
afterVAT: 0,
VAT: 0
}
}
instance.init();
expect(instance.getCart()).toEqual(emptyCart);
});
});
describe(`ONE product added`, () => {
const _VATRate = 20
const _product = {
name: 'product1',
price: 1.50,
quantity: 1
};
let _instance
let _cart
beforeEach(() => {
_instance = window[NETCENTRIC_NAMESPACE][MODULE_NAME]();
_instance.init(_VATRate);
_cart = _instance.addProducts(_product);
});
test(`cart's products`, () => {
expect(_cart.products).toEqual([_product]);
});
});
I've modified the constructor the following way so it passes the 1st part and successfully adds an item.
(function() {
var MODULE_NAME = 'shoppingcartModel',
_VATRate = 20,
_Cart = {
products: [],
total: {
beforeVAT: 0,
afterVAT: 0,
VAT: 0
}
},
_getCart;
window[MODULE_NAME] = function() {
_getCart = function() {
return {
total: _Cart.total,
products: _Cart.products
};
};
return {
init: function(VATRate) {
return _Cart.total.VAT = VATRate || 0;
},
getCart: _getCart,
addProducts: function(newOrExistingProducts) {
return _Cart.products.push(newOrExistingProducts);
}
};
};
})()
var shoppingCart = new window.shoppingcartModel()
shoppingCart.init(20);
shoppingCart.addProducts('Coffee, 2$');
console.log(shoppingCart.getCart())
But unfortunately, my implementation doesn't satisfy the 2nd part of test needs. And it's terminal window it communicates with:
Expected value to equal:
[{"name": "product1", "price": 1.5, "quantity": 1}]
Received:
undefined
Can you please suggest what can be done? :)
how mock allows checking the arguments sent to the mocked function in django testing
This is the method where i want to mock send_email()
def send_set_password_email(self):
self.update_hash()
url = self.user.password_set_url()
recipient = self.user.email
context_dict_map = {}
context_dict_map[recipient] = Context(dict(
partner_realtor_obj=self,
full_name=self.contact_name,
change_password_url=url,
slug=self.slug,
host = "http://%s.moveeasy.com/" % (self.slug, ),
STATIC_URL = settings.EMAIL_STATIC_URL
))
if self.brokerage_link:
subject = '%s has empowered you with MoveEasy' % (self.brokerage_link.name)
else:
subject = 'You have been empowered with MoveEasy'
send_mail(
recipients=[recipient], subject=subject,
text_content='Set your password at the following url: %s' % (url,),
template_name='emails_table/realtors/set-password.html',
context_dict_map=context_dict_map,
subdomain=self.slug, email_type='Realtor: Set password'
)
In my testcase i have mocked it like
@mock.patch('moving_concierge.utils.send_mail')
def test_send_set_password_email(self, send_mail):
image_content = open(
os.path.join(settings.BASE_DIR, 'static/images/avatar.jpg'), "rb"
).read()
logo = SimpleUploadedFile('image.jpg', image_content)
user = User.objects.create_realtor(
email='john@doe.com', password='Abc123!'
)
realtor = RealtorDetails.objects.create(
user=user, slug='john-doe',
logo=logo, hash='j12h9on8'
)
realtor.send_set_password_email()
url = realtor.user.password_set_url()
send_mail.returnvalue = context_dict_map
I need to Assert that proper context_dict_map is passed to send_mail, How can i do that ???
Please help me out guys, Thanks in advance.
Jest - expect a variable to be null or boolean
I am developing some tests with Jest for a Node.js backend and I need to check out some values that come from a third party. In some cases those values can come as a boolean
or as null
.
Right now I am checking the variables that fit that situation with:
expect(`${variable}`).toMatch(/[null|true|false]/);
Is there any better way to check them with Jest built in functions?
keep mocked apis in sync with documentation
I have a Vue js application with some mocked api for testing purposes. The library I use to handle http request is Axios and the library to mock everything is Axios-mock-adapter:
mock.onGet(/.+\/api\/annotation/).reply(() =>
[200, ResponseObject.getTopics],
);
In another file that I import I have all the response object:
const getTopics = {
topics: [
{
id: 'source',
name: 'am',
},
],
};
This approach works but is pretty limited because when some back-end guy updates the documentation I have to manually change the response object, otherwise my tests would still pass and they shouldn't.
There's a way to keep in sync the doc with my object file? The ideal set up would be that before starting the testing phase I download automatically a json containing all the response to the api based on the doc...
There's a way to achieve that?
component testing in angular5
Can anyone tell me whether is it possible to test a component as a whole in angular5? If yes then how?
Also i am aware of unit testing and that is already covered by jasmine/karma so i dont want to write unit test but test the component as a whole.
I came across this link - https://vsavkin.com/three-ways-to-test-angular-2-components-dcea8e90bd8d where they are doing isolated test/shallow test. Is this nothing but component testing?
Somebody plz advice.
Xamarin UI Test: Is it possible to interact with the OS level dialogues during UITesting
Is it possible to automate OS level dialogues during xamarin UI testing? I.E - Tap the upload button, which brings up a gallery modal which would allow you to select a photo of your choice to upload? Or tapping an overflow menu and be given the choice to open via external app, or go fullscreen?
Is it possible to automate the selection of the photo? Is it possible to trigger airplane mode so the app is offline during the test execution? I'm just trying to find out how limited i am when it comes to automating the app im responsible for as there are a few scenarios like this.
Path coverage testing: Basic logic
I am trying to understand Path coverage completely and I have a question:
Let's say I have this program:
for (int i = 0; i <array.length;i++) {
if (...) //1
{
//do sth
return false;
}
if(...) //2
{
if(...) //2A
{
//Do sth
}
else () //2B
{
if (...) //2BX
{
//Do sth
}
else //2BY
{
//Do sth
}
}
else //3
{
//Do sth
}
}
return true;
Is showing that, given an array of inputs, each code (do sths) in 1,2A,2BX,2BY,3
is executed enough to satisfy path coverage testing?
A single input array[i]
can only execute the code in only one of these (1,2A,2BX,2BY,3)
Or does the permutation of these //do somethings
matter because there is a for
loop in the program?
I am a little confused behind the logic behind it.
Thanks!
Android UI testing - custom dialog
I need help with Android UI testing. I use Expresso to testing my Login Activity class and i don't know how can i test that custom dialog was show.
This is my code: Test:
@Test
public void validation_return_success() throws InterruptedException {
/** Set up */
onView(withId(R.id.editTextUserName)).perform(typeText("username"), closeSoftKeyboard());
onView(withId(R.id.editTextPassword)).perform(typeText("password"), closeSoftKeyboard());
/** Execute */
onView(withId(R.id.loginBtn)).perform(click());
/** Validation */
onView(withId(R.id.dialog_progress)).check(matches(isDisplayed()));
This is my ProgressDialog create (Its class ProgresDialog.class and I have layout progress_dialog.xml):
ProgressDialog
.newInstance(getString(R.string.progress_authenticating))
.show(getSupportFragmentManager(), "progress");
And this is my layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/dialog_progress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:orientation="horizontal"
android:paddingBottom="24dp"
android:paddingLeft="32dp"
android:paddingRight="48dp"
android:paddingTop="24dp">
<ProgressBar
android:id="@+id/progressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/tvContent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="24dp"
android:text="wait..."
android:textSize="16sp" />
Some help how can i test it that after put username and password and click to button will be show dialog... Show the dialog is success end. I try lots of options which i found on internet but nothing work... I stack on dialog which don't hide.
Sorry for my english.
Testing Service. TypeError: done.fail is not a function
I tried this test for testing my service:
Show this error:
TypeError: done.fail is not a function
test file
it('should return reasonable json ssss', inject([ProductService, MockBackend], async((service: ProductService, mockBackend: MockBackend) => {
const mockResponse = {
data: [
{ id: 0, details: 'All cats are lions' },
{ id: 1, details: 'Video 1' },
{ id: 2, details: 'Video 2' },
{ id: 3, details: 'Video 3' },
]
};
mockBackend.connections.subscribe(connection => {
connection.mockRespond(new Response(
new ResponseOptions({
body: [
{ id: 0, details: 'All cats are lions' },
{ id: 1, details: 'Video 1' },
{ id: 2, details: 'Video 2' },
{ id: 3, details: 'Video 3' },
]
})));
});
service.productsgetall().subscribe((facts) => {
console.log(facts)
expect(facts[0].details).toEqual('ffff');
});
})));
- My service.ts
public productsgetall(): Observable<Products[]> {
...
return this.http.get(Api.getUrl(Api.URLS.productsgetall), {
headers: headers
}).map((response: Response) => {
let res = response.json();
if (res.StatusCode === 1) {
this.auth.logout();
} else {
return res.StatusDescription.map(aa => {
return new Products(aa);
});
}
});
}
Can you ask me, what is the problem in my code, how to write good testing? If this testing is'n good, please suggest something. Thnx
Testing passing parameter in C# code
Below i've pasted my code. I'm using BDD so have written code for my 'Then' step in my feature file. My code validates data within a file with data i'm expecting it to have. Within my feature file i'm also passing parameters (see below). How can i pass a third validation in my code to make sure the correct lifecyclestatus is being run?
Then measure should be generated <lifecyclestatus>
Examples:
| Lifecyclestatus |
| New |
| Current |
using System; // Other usings
using NUnit.Framework;
namespace MyTests
{
....
[TestCase("irm_xxx_tbbmf_xu.csv.ovr", "6677,6677_6677,3001,6")]
[TestCase("irm_xxx_tbbmf_xxx.csv.ovr", "6677,22,344")]
public void ValidateInventoryMeasurement(string path, string expected)
{
const string processFilePath = "/orabin/product/inputs/actuals/";
var actual = Common.LinuxCommandExecutor
.RunLinuxcommand($"cat {processFilePath}{path}");
Assert.AreEqual(expected, actual);
}
How to test file upload for REST API in Jmeter
How to test file upload for REST API in Jmeter. I have tried in attaching file in file upload in HTTP Request and providing header parameter in Http header manager.
mercredi 30 mai 2018
How do I test this using Jest + Enzyme
I have a react + typescript application and I have an async api call done with axios
. I want to test that async call using Jest + Enzyme.
This is what I have for my action
// load items callback
export function loadItemsSuccess(response) {
return {
type: LOAD_ITEMS,
items: response.data
};
}
// load items
export function loadItems() {
return function (dispatch) {
const authOptions = {
method: "GET",
url: "http://192.168.99.100:3000/items
headers: {
"Content-Type": "application/x-www-form-urlencoded"
},
json: true
};
return axios(authOptions).then(response => {
dispatch(loadItemsSuccess(response));
}).catch(error => {
console.log("Error loading items, error);
});
};
}
My reducer simple updates the store:
case LOAD_ITEMS:
console.log(action.items);
return action.items;
How to count DOM elements in Cypress assertion
I'm trying to count the number of options in a select element, and the number of elements of a certain class in the DOM.
I need to compare the two totals for a Cypress assertion.
I can select the options I need, and iterate over them with each(), and increment a counter that way. However, it's asynchronous, and it's also a clumsy solution. I'm certain that the object yielded by my cy.get() has a length property, I just can't seem to get at it.
Here is one of the things I expected to work. It logs undefined to the console.
cy.get('div[data-cy-type="group-component"]:first').as('firstGroup');
cy.get('@firstGroup').find('[name=group_id]').as('groupSelect');
console.log(cy.get('@groupSelect').children('option').length);
I know my alias is good and my cy.get() is yielding the correct select element.
If I do something like this:
cy.get('@groupSelect').children('option').each(function(){
console.log(i++);
});
then it will iterate over each option. But it's asynchronous so not very helpful in this flow.
Django : fixtures object not retrievable
Strange thing is happening. Here is a part of my fixture :
{
"model": "mezzanine_agenda.event",
"pk": 1,
"fields": {
"comments_count": 0,
"keywords_string": "",
"rating_count": 0,
"rating_sum": 0,
"rating_average": 0.0,
"site": 1,
"title": "event search",
"slug": "event-search",
"_meta_title": "",
"description": "event search",
"gen_description": true,
"created": "2018-05-25T15:49:55.223Z",
"updated": "2018-05-25T15:49:55.257Z"
}
And here is my test :
class FrontTest(LiveServerTestCase):
fixtures = ['event.json']
@classmethod
def setUpClass(cls):
super().setUpClass()
print(Event.objects.all())
And the output :
[]
Do someone know why my fixture is not loaded ?
React test error
I tried to run some tests in react for the first time, BUT I received some error, and got no idea what these are.
2018-05-30 16:47 node[3217] (FSEvents.framework) FSEventStreamStart: register_with_server: ERROR: f2d_register_rpc() => (null) (-22)
2018-05-30 16:47 node[3217] (FSEvents.framework) FSEventStreamStart: register_with_server: ERROR: f2d_register_rpc() => (null) (-22)
2018-05-30 16:47 node[3217] (FSEvents.framework) FSEventStreamStart: register_with_server: ERROR: f2d_register_rpc() => (null) (-22)
events.js:183
throw er; // Unhandled 'error' event
^
Error: Error watching file for changes: EMFILE
at _errnoException (util.js:1022:11)
at FSEvent.FSWatcher._handle.onchange (fs.js:1359:9)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! isomorphic@2.6.0 test: `react-app-rewired test --env=jsdom`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the isomorphic@2.6.0 test script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! /Users/EcoSurvUser/.npm/_logs/2018-05-30T15_47_27_998Z-debug.log
Alessandros-MacBook-Pro-2:isomorphic_immutable_js EcoSurvUser$
How do I write test for homebrew formula?
I made an homebrew formula which is now accessible only on my local taps. I want to send pull request to homebrew-core. Now I am required to write test for my formula. How to write that based on example below?
test do
output = shell_output("#{bin}/balance 2>&1", 64)
assert_match "this is balance #{version}", output
end
Laravel basic test assert false.. but it's works?
I have a failure on my test suite but my code is running properly in my seeders...
When I'm running my seed once I have a failure.. But ! When I'm running twice I've not the failure on my previous dataset anymore (just on my new dataset appended). Is my function too slow to be executed ?
My feature test :
/**
* Test if User can follow an other user and send a notification
*
* @return void
*/
public function test_user_can_follow_an_other_user()
{
$follower = factory(User::class)->create();
$followed = factory(User::class)->create();
$this->actingAs($follower, 'web')
->post('/following', ['user' => $followed->id])
->assertRedirect('/following');
$this->assertTrue($follower->follows($followed));
}
My PhpUnit result :
PHPUnit 7.1.5 by Sebastian Bergmann and contributors.
.mpoo.F 3 / 3 (100%)
Time: 2.91 seconds, Memory: 50.00MB
There was 1 failure:
1) Tests\Feature\UserTest::test_user_can_follow_an_other_user
Failed asserting that false is true.
/Users/gtr/Code/La-dechetterie-du-web/lddw-api/tests/Feature/UserTest.php:69
FAILURES!
Tests: 3, Assertions: 9, Failures: 1.
My seeder :
public function run()
{
$follower = User::first();
$following = User::all();
$followingArrayIds = [];
foreach ($following as $u) {
$follower->follow($u);
array_push($followingArrayIds, [
'follower' => $follower->id,
'pretend_to_follow' => $u->id,
'is '. $follower->id .' following '. $u->id .' ?' => $follower->follows($u) // should be true !!!!!
]);
}
print_r($followingArrayIds);
}
My Model's function :
/**
* User's following relation
*
* @return Relation User
*/
public function following(){
return $this->belongsToMany('App\User', 'followers', 'follower_id', 'following_id');
}
/**
* User's followers relation
*
* @return Relation User
*/
public function followers(){
return $this->belongsToMany('App\User', 'followers', 'following_id', 'follower_id');
}
/**
* Follow an other user
*
* @param User $user
* @return void
*/
public function follow(User $user){
if($this->follows($user))
return;
$this->following()->attach($user);
}
/**
* Check if the current user follows the user he wanted to
*
* @param User $user
* @return boolean
*/
public function follows(User $user){
return $this->following->contains($user);
}
Thx :)
TestNG Factory Freezing
I have a TestNG factory that should create about 25 tests and run them all. It completes about 20 of them fully, and then freezes part of the way into the last test.
The basic structure looks like this:
myType[] array1 = { create x many myType objects here }
myType[] array2 = { create x many myType objects here }
myType[] array3 = { create x many myType objects here }
myType[] array1 = { create x many myType objects here }
@Factory
public TestClassName[] testFactory(){
return new TestClassName[]{
new TestClassName(Array1),
new TestClassName(Array2),
new TestClassName(Array3),
new TestClassName(Array4),
}
}
public class TestClassName extends TestCase{
private myType[] myArray;
TestClassName(myType[] array){this.myArray = array;}
@DataProvider(parallel = true)
private Iterator<myType[]> thingProvider(){return Arrays.stream(myArray).map(ArrayUtils::toArray).iterator();}
@Test(dataProvider = "thingProvider()")
private void doWork(MyType thing){
//do some work on the thing here
}
}
Any idea why a factory would just freeze like this? Could it have to do with using the dataProvider with parallel set to true?
Fake BigQuery server for tests
I am writing a simple Java server application that works against BigQuery
using BigQuery
Java API. Now I need a simple "end-to-end" test for that application. I'd like to use a "fake" BigQuery
server for that test instead working against "real" BigQuery
at Google.
My application does not use all BigQuery
APIs. I can start with a "fake" BigQuery
server that implements only one API for now.
I found a few "fake" BigQuery
servers on the internet but they are written in Python/Go. I would prefer a JVM-based "fake" server. How would you suggest implement such a "fake" BigQuery
server ?
Same id for 2 dropdown unable to perform actions om 2 one
Hi everyone In my code there are 2 dropdowns on 2 different pages and they both have same id "birth-nation". I am able to perform the actions by using this id but when it goes to second it gives me an error that element is not visible.
Here is code:
Select dropdown1111111 = new Select(driver.findElement(By.id("birth-nation"))); dropdown1111111.selectByVisibleText("UNITED STATES");
Select dropdown1111111 = new Select(driver.findElement(By.id("birth-nation"))); dropdown1111111.selectByVisibleText("UNITED STATES");
the id for both are same and i am not able to perform actions on 2 dropdown.
Please help.
My testing.spec.ts doesn't work
I tried this test for testing my service:
Result for this is successful, but I think that this must be unsuccessful, because I have only 5 products.
it('testing getall products', () => {
const proservice = TestBed.get(ProductService);
proservice.productsgetall().subscribe(products => {
expect(product.length).toEqual('10') // This is unsuccessful, because I have only 5 products.
});
})
My service.ts
public productsgetall(): Observable<Products[]> {
...
return this.http.get(Api.getUrl(Api.URLS.productsgetall), {
headers: headers
})
.map((response: Response) => {
let res = response.json();
if (res.StatusCode === 1) {
this.auth.logout();
} else {
return res.StatusDescription.map(aa => {
return new Products(aa);
});
}
});
}
Can you ask me, what is the problem in my code, how to write good testing?
Testing processFilePath NUnit C#
I've written a test using NUnit Testcase. I've defined the file name 'irm_xxx_tbbmf_xu.csv.ovr' and what data i expect that file to output.
I've defined my processFilePath of the location of where that file will be and the file name within [NUnit.Framework.TestCase("irm_xxx_tbbmf_xu.csv.ovr".
My question is the way i've written the processFilePath will it find the file name from the [NUnit.Framework.TestCase as i expect it to. And will the Assert.AreEqual work the way i've written it.
[NUnit.Framework.TestCase("irm_xxx_tbbmf_xu.csv.ovr", "6677,6677_6677,3001,6")]
[NUnit.Framework.TestCase("irm_xxx_tbbmf_xxx.csv.ovr", "6677,22,344")]
public void ValidateInventoryMeasurement(string path, string expected)
{
var processFilePath = "/orabin/product//inputs//actuals/";
var actual = Common.LinuxCommandExecutor.
RunLinuxcommand("cat " + path);
Assert.AreEqual(expected, actual);
}
How add test folders in android studio
I am working on a project to which the test folders were removed and I want to do a unit test. Is there a way to create the test folders again for that project?
how i can test my web site on MS Edge web browser, if i do not have it installed
I have windows 7 and i got these 3 browsers installed:-
- Firefox Quantum version 60
- IE 11.
- chrome 66.
now i want to test how my web site will looks like on MS Edge. but i am not sure what i need to do. so i have these 3 questions:-
- can i install MS Edge and keep IE 11 ? so i will have 2 browsers types?.
- is there any MS Edge simulators, i can use for testing ?
- inside IE 11 F12 tools, i can find MS edge under simulators, as follow:- so will choosing this option mimic MS Edge?
How to mock a FileWriter in spark structured streaming unit tests?
I'm trying to write unit tests for a spark structured streaming app. I'm reading some data from a stream and storing it in RDS. To do this I'm using the ForeachWriter
:
ds.writeStream
.queryName("query")
.foreach(writer)
.option("checkpointLocation", CHECKPOINT)
.outputMode("append")
.start()
Is there a way to mock it in order to not write the data in the database?
appium webdriver remoteserver UnreachableBrowserException
package basic_scenario;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.remote.UnreachableBrowserException;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
public class Login_TG {
WebDriver driver;
@BeforeTest
public void setup() throws MalformedURLException
{
String apkpath="C:\\Users\\rgi-40\\android-sdks\\platform-tools\\GG.apk";
File app=new File(apkpath);
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability("browserName", "");
capabilities.setCapability("deviceName", "emulator-5554");
capabilities.setCapability("PlatformVersion", "6.0");
capabilities.setCapability("app", app.getAbsolutePath());
capabilities.setCapability("platformName", "Android");
capabilities.setCapability("noReset", true);
capabilities.setCapability("appActivity", "com.globalgarner.BaseClasses.Navigation.Activity.SplashScreenActivity");
capabilities.setCapability("appPackage", "com.globalgarner");
capabilities.setCapability("autoGrantPermissions",true);
capabilities.setCapability("newCommandTimeout", "60");
capabilities.setCapability("automationName", "Appium");
//capabilities.setCapability("--session-override",true);
try{
driver = new RemoteWebDriver(new URL("http://127.0.0.1:5038/wd/hub"), capabilities);
}catch(UnreachableBrowserException e){
System.out.println("cant find driver");
}
}
@Test
public void testLogin() throws Exception {
WebElement login_element = driver.findElement(By.id("com.globalgarner:id/act_tutorial_btn_login"));
login_element.click();
WebElement uname_element = driver.findElement(By.className("android.widget.EditText"));
uname_element.sendKeys("test");
WebElement pwd_element = driver.findElement(By.id("com.globalgarner:id/fragment_login_edt_password"));
pwd_element.sendKeys("test");
WebElement submit_element = driver.findElement(By.id("com.globalgarner:id/fragment_login_btn_login"));
submit_element.click();
}
@AfterTest
public void teardown() {
driver.quit();
}
}
windows 10 osenter image description here Appium version = 1.6.1 Eclipse : neon 3.
First whole code is run perfect but after running multiple time test it shows "unreachablebrowserexception"
i am not able to handle unreachable browser exception, if i am using androiddriver and appiumdriver , i am not able to getting the element inside testLogin() method.
Strategy for dictionary with optional keys
Currently I am using hypothesis fixed_dictionaries strategy to generate a dictionary with specific keys and data types that are considered valid for my application. I need a strategy which produces this fixed dictionary as well as others with specific keys removed. Or a dictionary with a certain minimal set of keys with optional additional ones, preferably in a way that produces the various combinations of these optional keys.
This is an example of the json schema that needs to be validated, with the 2 optional fields. I'd like to generate all possible valid data for this schema.
'user_stub': {
'_id': {'type': 'string'},
'username': {'type': 'string'},
'social': {'type': 'string'},
'api_name': {'type': 'string',
'required': False},
'profile_id': {'type': 'integer',
'required': False},
}
This is what I came up with but it is incorrect because it retains the keys but uses None as the value, and I want instead that the keys are removed.
return st.fixed_dictionaries({
'_id': st.text(),
'username': st.text(),
'social': st.text(),
'api_name': st.one_of(st.none(),
st.text()),
'profile_id': st.one_of(st.none(),
st.integers()),
})
Testing validations C#
Below i've pasted my code. I'm validating a measure. I've written code that will read a linux file. But if i wanted to pass multiple file names here would this be possible? so for example instead of my test just validating one file could i do a loop so it could ready multiple files in one go.
Once the file is being read and proceeded i return actualItemData. In my next method i want to make a call to this actualItemData so the data is published in my 'var actual'
public string validateMeasurement
{
var processFilePath = **"/orabin/app/oracle/inputs/ff/ff/actuals/xx_ss_x.csv.ovr";**
var actualItemData = Common.LinuxCommandExecutor.
RunLinuxcommand("cat " + processFilePath);
**return actualItemData;**
}
public void validateInventoryMeasurementValue(string Data, string itemStatus)
{
var expected = '6677,6677_6677,3001,6';
**var actual = actualItemData);**
Assert.AreEqual(expected, actual);
}
Arquillian test againt full war not working, NullPointerException
I am running integration test on a Java ee application.
the code works perfectly this way
Dependencies
repositories {
mavenLocal()
maven { url "http://repo.maven.apache.org/maven2" }
jcenter()
}
dependencies {
providedCompile "javax:javaee-api:7.0"
testCompile 'org.jboss.arquillian:arquillian-bom:1.4.0.Final'
testCompile 'org.jboss.arquillian.junit:arquillian-junit-container:1.4.0.Final'
testCompile group: 'org.arquillian.container', name: 'arquillian-container-chameleon', version: '1.0.0.CR2'
compile group: 'org.jboss.shrinkwrap.resolver', name: 'shrinkwrap-resolver-gradle-depchain', version: '2.2.0'
testCompile 'junit:junit:4.12'
}
and the test
@RunWith(Arquillian.class)
public class GreeterTest {
@Deployment
public static JavaArchive createDeployment() {
return ShrinkWrap.create(JavaArchive.class)
.addClass(Greeter.class)
.addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml");
}
@Inject
Greeter greeter;
@Test
public void should_create_greeting() {
assertEquals("Hello, toumi!", greeter.createGreeting("toumi"));
}
the needed setup
I do not want to import my classes manually like done in this example, but I want to test against a full ready war.
So I change the deployment block this way
@Deployment
public static WebArchive createTestArchive() {
return ShrinkWrap.create(EmbeddedGradleImporter.class)
.forThisProjectDirectory()
.importBuildOutput(<Full path to my war>)
.as(WebArchive.class);
}
Questions
- how to test arquillian against full war
- I am also unable to run this test from github examples
Is there something wrong with the plugin, or missed step in the setup.
Django : Connection refused to live_server_url
I'm using docker, selenium, and Django. I just realised i was doing my tests on my production database ; while i wanted to test on StaticLiveServerTestCase
self-generated database.
I tried to follow that tutorial
@override_settings(ALLOWED_HOSTS=['*'])
class BaseTestCase(StaticLiveServerTestCase):
host = '0.0.0.0'
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.host = socket.gethostbyname(socket.gethostname())
cls.selenium = webdriver.Remote(
command_executor='http://selenium:4444/wd/hub',
desired_capabilities=DesiredCapabilities.CHROME,
)
cls.selenium.implicitly_wait(5)
@classmethod
def tearDownClass(cls):
cls.selenium.quit()
super().tearDownClass()
class MyTest(BaseTestCase):
def test_simple(self):
self.selenium.get(self.live_server_url)
I've no error trying to connect to the chrome-hub, but when i try to print my page_source, i'm not on my django app but on a chrome error message. Here is a part :
<div class="error-code" jscontent="errorCode" jstcache="7">ERR_CONNECTION_REFUSED</div>
I'm using docker-compose 1. Selenium.yml:
chrome:
image: selenium/node-chrome:3.11.0-dysprosium
volumes:
- /dev/shm:/dev/shm
links:
- hub
environment:
HUB_HOST: hub
HUB_PORT: '4444'
hub:
image: selenium/hub:3.11.0-dysprosium
ports:
- "4444:4444"
expose:
- "4444"
app:
links:
- hub
I guess i did something wrong in my docker-compose file, but i don't manage to figure out what.
Thanks in advance !
Property based testing in java
I have an assignment where I have to pass the following test. Problem is I dont understand what the test does. Can someone explain it to me step by step?
public Property remove_if() {
return property(isKVList, arbF(cogenInteger, arbBoolean), (kvs, predicate) -> {
SortedTreeMap<Integer, String> tm = new SortedTreeMap<>(intOrd.toComparator());
kvs.foreachDoEffect(kv -> tm.add(kv._1(), kv._2()));
tm.removeIf((key, value) -> predicate.f(key));
List<Integer> keys = fromIterator(tm.keys().iterator());
List<Integer> kept_sorted = kvs.map(P2::_1).filter(key -> !predicate.f(key)).sort(intOrd);
return prop(intListEqual.eq(keys, kept_sorted));
});
}
Python cmd script hanging when trying to loop
I'm trying to make a python script to run a batch file multiple times with different configurations one after the other. The problem I'm having is that I'm trying to find a wait for it to wait for the run to finish and then run another one, but the cmd hangs and doesn't let the second argument to be written in the cmd. It does not do that when just using the cmd to run the batch file manually. So don't really understand what the problem is. I'm really new to Python so suggestions how to make this script better is welcome:
import subprocess
# open commandline
subprocess.Popen([r"cmd"])
# Run every test 5 times.
# Wait for a single run to finish before running another one
for x in xrange(5):
subprocess.Popen([r"batchfile.bat", "arg", "arg", "arg", "arg"])
subprocess.Popen.wait(timeout=None)
for x in xrange(5):
subprocess.Popen([r"batchfile.bat", "arg", "arg", "arg", "arg"])
subprocess.Popen.wait(timeout=None)
mardi 29 mai 2018
Unable to run cucumber feature file using gradle in Eclipse. I am getting "Error: Could not find or load main class cucumber.api.cli.Main" error
I am trying to run cucumber feature file on Eclipse but getting following error. "Error: Could not find or load main class cucumber.api.cli.Main"
Gradle code (build.gradle)
apply plugin: 'java'
configurations {
cucumberRuntime {
extendsFrom testRuntime
}
}
task cucumber() {
dependsOn assemble, compileTestJava
doLast {
javaexec {
main = "cucumber.api.cli.Main"
classpath = configurations.cucumberRuntime + sourceSets.main.output + sourceSets.test.output
args = ['--plugin', 'pretty', '--glue', 'gradle.cucumber', 'src/test/resources']
}
}
}
dependencies {
testCompile 'io.cucumber:cucumber-java:3.0.2'
testCompile 'io.cucumber:cucumber-junit:3.0.2'
testCompile 'junit:junit:4.12'
}
repositories {
mavenCentral()
}
Feature file (add.Feature)
@tag
Feature: Title of your feature
I want to use this template for my feature file
@tag1
Scenario: Title of your scenario
Given I have the calculator
When I enter input1 and input2
And I press add button
Then I get output
I am right clicking on feature file. Then selecting run as and pressing on cucumber feature. Thanks in advance.
How to test Sequelize migrations?
Is it necessary to cover Sequelize
migrations with unit tests, or even functional tests to check how they affect DB structure? If so, how to do it?
Write Test On Laravel
Hello i want to write test for my Api and i create file called: LessonsTest.php
<?php
use App\Lesson;
use Tests\ApiTester;
/**
* Class LessonsTest
* That Test Our Lessons
*/
class LessonsTest extends ApiTester
{
/**
* @test
* Test All Lessons pass
*
*/
public function it_fetches_lessons()
{
// Make Lesson
$this->times(5)->makeLesson();
// Get URL we want to test
$this->getJson('api/v1/lessons');
// Pass Ok Response
$this->assertResponseOk();
}
/**
* Make Lesson method
* @param array $lessonFields
*/
private function makeLesson($lessonFields = [])
{
$lesson = array_merge([
'title' => $this->fake->sentence,
'body' => $this->fake->paragraph,
'some_bool' => $this->fake->boolean
], $lessonFields);
while ($this->times--) Lesson::create($lesson);
}
}
now as you see its extend from ApiTester file:
<?php
namespace Tests;
use Faker\Factory as Faker;
class ApiTester extends TestCase
{
protected $fake;
protected $times = 1;
/**
* ApiTester constructor.
* @param $faker
*/
public function __construct()
{
$this->fake = Faker::create();
}
protected function times($count)
{
$this->times = $count;
return $this;
}
}
so its all write now problem i have when i try to test:
vendor\bin\phpunit tests\LessonsTest.php
i get this error:
1) LessonsTest::it_fetches_lessons ErrorException: array_merge(): Argument #1 is not an array
i research a lot but i could not find solution
Error while accessing Flask config while testing
While writing tests for my Flask app I came across an issue when trying to set Flask config settings.
Usually, I do it like this:
import unittest
from factory import create_app
class ConfigTests(unittest.TestCase):
def setUp(self):
app = create_app('flask_test.cfg')
app.testing = True
self.app = app.test_client()
def test_app_is_development(self):
self.assertTrue(self.app.application.config['SECRET_KEY'] is 'secret_key')
self.assertTrue(self.app.application.config['DEBUG'] is True)
This resulted in an error
AttributeError: 'FlaskClient' object has no attribute 'config'
Only from debugging I saw that there was no "config" attribute instead I had to go self.app.application.config
to get it to work.
import unittest
from factory import create_app
class ConfigTests(unittest.TestCase):
def setUp(self):
app = create_app('flask_test.cfg')
app.testing = True
self.app = app.test_client()
def test_app_is_development(self):
self.assertTrue(self.app.application.config['SECRET_KEY'] is 'secret_key')
self.assertTrue(self.app.application.config['DEBUG'] is True)
Am I doing something, did Flask change this in an update or is there a better way to do this?
C# compare expected result with actual result
I'm writing a test which will generate an output for me from a linux file.
I've got code to read a linux file which will give me an ouput. For example the output will be 1,333,44,5. I want to compare this the expected result which i have stored in a excel file.
Is there code i can use which will help me compare the output from the linux file with the expected result which i have in my excel sheet. Comparing the two will allow me to see whether the test is passing or failing.
WriteLine isn't shown the message in Output. Selenium. C#
I've already tried all options that I've found. It doesn't run. No messages in "Output", "Command Window" windows of VS. Any ideas why?
Thanks, guys!
namespace TestTrainee {
[TestFixture]
public class UnitTest1
{
public LoginPage mainPage;
[SetUp]
public void SetUpDrvier()
{
mainPage = new LoginPage(new ChromeDriver());
}
[Test, Order(0)]
public void CheckLogIn()
{
mainPage.OpenPage();
mainPage.FindElementByXpath(By.XPath("//a[@href='../articles_popup.php']")).Click();
Task.Delay(5000).Wait();
mainPage.SwitchPAge();
Debug.WriteLine("!!!");
Trace.WriteLine("!!!");
Console.WriteLine("!!!");
}
[TearDown]
public void FinishExe()
{
//mainPage.CloseBrowser();
}
}
}
How to use cucumber to test vertx applications?
I have to write cucumber scenarios and step definitions to a project which is written using vert.x(A JAVA framework)? Links will be helpful(I didn't get any google result)
Read and validate linux file c#
I have a linux file i can 'Cat' and read the output of. I want to then compare the file line by line to the data i'm validating against. I understand how this would work for a text file but not sure about a linux file. I've pasted a copy of my code i have for reading the file by doing a cat.
public string validateMeasurement(string measurementName, string domaianName)
{
var processFilePath = "/orabin/app/oracle/inputs/ff/ff/actuals/" + measurementName + ".csv.ovr";
var actualItemData = Common.LinuxCommandExecutor.
RunLinuxcommand("cat " + processFilePath);
return actualItemData;
Does pact support application/JavaScript content-type?
The third party service that my microservice interacts with returns the response with the content-type application/JavaScript;charset=UTF-8. Therefore, pact json has response body as string & matching rules have an empty body.
Using the following pact dependencies:
testIntegrationCompile('au.com.dius:pact-jvm-consumer-junit_2.12:3.5.11')
testIntegrationCompile('au.com.dius:pact-jvm-provider-junit_2.12:3.5.11')
testIntegrationCompile('au.com.dius:pact-jvm-provider-spring_2.12:3.5.11')
testIntegrationCompile('au.com.dius:pact-jvm-consumer-java8_2.12:3.5.11')
How to upload app to TestFlight for sandbox User?
I have already created sandbox tester account.
I want to upload TestFlight app for sandbox User only including developer certification not production certificate, is it possible?
if yes than how?
any reference link?
C# Way to validate test data
I'm running a test where i need to validate data from a linux file. I've defined the path of the file is located (see below). Once i cat the file to read the data contents (irm_dwge_stt_l__xxxx.csv.ovr) how can i validate the data within this file
Also where i have defined the measurementName where can i define what measurements belong within this.
public string validateMeasurement(string measurementName, string domaianName)
{
var processFilePath = "/inputs/ff/ff/actuals/" + measurementName + ".csv.ovr";
var actualItemData = Common.LinuxCommandExecutor.
RunLinuxcommand("cat " + processFilePath);
return actualItemData;
Cycle post request in postman
I need to test my Web api. I use Postman for sending requests to urls. Can I do it in Cycle ? Example : 10 times send request on url_1, if got error - stop sending, else - 10 times send request on url_2 ect. Can I do it with Postman ?
Catch2 - undefined reference to
I'm testing my project using Catch2 as library. I followed every step in the Catch doc, but when I run the tests I get the following error:
CMakeFiles/tests.dir/tests/IntegerIntervalTest.cpp.o: in function "____C_A_T_C_H____T_E_S_T____0()": /home/davide/cpp-project/tests/IntegerIntervalTest.cpp:8: undefined reference to "domain::IntegerAbstractInterval<int, int>::IntegerAbstractInterval(int, int)"
and this error repeates for every method call in the test "class".
CMakeLists:
PROJECT(cpp_project)
CMAKE_MINIMUM_REQUIRED(VERSION 3.5)
INCLUDE(CheckCXXCompilerFlag)
CHECK_CXX_COMPILER_FLAG(-std=c++14 COMPILER_SUPPORTS_CXX14)
IF (COMPILER_SUPPORTS_CXX14)
ADD_COMPILE_OPTIONS("-std=c++14")
ELSE ()
MESSAGE(FATAL_ERROR "Compiler ${CMAKE_CXX_COMPILER} has no C++14 support.")
ENDIF ()
set(BASE_SRCS src/Bound.cpp src/Bound.hpp src/Infinity.cpp src/Infinity.hpp src/AbstractInterval.cpp src/AbstractInterval.hpp
src/UndefinedOperationException.hpp src/IntegerAbstractInterval.cpp src/IntegerAbstractInterval.hpp src/FloatingPointAbstractInterval.cpp
src/FloatingPointAbstractInterval.hpp)
ADD_COMPILE_OPTIONS("-Wall" "-Wextra" "-Wpedantic" "-Werror" )
ADD_LIBRARY(cpp-project ${BASE_SRCS})
INCLUDE_DIRECTORIES(libs/variant/include)
set(EXECUTABLE_OUTPUT_PATH bin)
set(CATCH_INCLUDE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/catch)
add_library(Catch INTERFACE)
target_include_directories(Catch INTERFACE ${CATCH_INCLUDE_DIR})
set(TEST_SRCS tests/InfinityTest.cpp tests/IntegerIntervalTest.cpp)
add_executable(tests ${BASE_SRCS} ${TEST_SRCS})
target_link_libraries(tests Catch)
and this is the test file IntegerIntervalTest.cpp
:
#include "../src/IntegerAbstractInterval.hpp"
#include "../libs/catch2/catch.hpp"
using namespace domain;
TEST_CASE("Operations on IntegerInterval instances", "[IntegerAbstractInterval]") {
IntegerAbstractInterval<int, int> i(0,1);
IntegerAbstractInterval<Infinity, Infinity> ii(Infinity('-'), Infinity('+'));
IntegerAbstractInterval<Infinity, int> iii(Infinity('-'), 5);
IntegerAbstractInterval<int, Infinity> iv(0, Infinity('+'));
IntegerAbstractInterval<int, int> v(-1,1);
SECTION("Sum operations") {
auto res1 = i + v;
REQUIRE(res1.getLowerBound() == Bound(-1));
REQUIRE(res1.getUpperBound() == Bound(2));
}
}
Unable to click on a button through any object locators?
I am trying to execute below Selenium Web driver script, But I am getting org.openqa.selenium.ElementNotVisibleException: Element is not currently visible Login
@Test
public void BrowserInvocation() {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\DOGETHER\\Desktop\\Website\\chromedriver.exe");
@SuppressWarnings("unused")
ChromeDriver driver=new ChromeDriver();
driver.get("http://phasorlab-web-dev.s3-website-us-east-1.amazonaws.com/"); /*Get URL */
driver.manage().timeouts().implicitlyWait(65, TimeUnit.SECONDS);
driver.findElementByXPath("//span[@class='button-inner']").click();
// driver.findElementByClassName("button-inner").click();
//driver.findElementByTagName("[text()='Login']").click();
java.lang.InstantiationException error when executing class in Groovy Soap UI 5.4.0
trying to execute a Groovy script in SOAPUI 5.4.0
class MyClass {
// The three following fields are MANDATORY
def log
def context
def testRunner
public MyClass(log,context,testRunner){
this.log = log
this.context = context
this.testRunner = testRunner
}
def MyMethod(){log.info "Reference Groovy function file" }
}
and receiving error i.e.
groovy.lang.GroovyRuntimeException: Failed to create Script instance for class: class MyClass. Reason: java.lang.InstantiationException: MyClass
same code was working in previous soap ui version , could you please help.
why fmt.Scanf doesn't work in golang test
why fmt.Scanf
doesn't work properly in a test file?
I have some test code as below, the test itself finishes without waiting for me to type in something.
package sometests
import (
"fmt"
"testing"
)
func TestScanf(t *testing.T) {
fmt.Printf("type someting:\n")
var s string
fmt.Scanf("%s\n", &s)
// test should wait here for me to type, but it won't
fmt.Printf("you type: %q\n", s)
}
Tests Runners Cross Browsers like Karma
I would like to know what tools do you use for test your code in cross-browsers (like Karma). Is it used actually Karma or are there other more interesting tools?
Thank you for your answers.
Ben.
Running Kestrel for testing without using the TestServer included in Microsoft.AspNetCore.TestHost
I'm using SoapCore for creating a WCF-ish kind of application using asp.net core 2.
This works fine for me so for but I've somewhat hit a brickwall when it comes to integration testing my endpoints.
Since SoapCore is a middleware and has no relation to any api controllers I'm not able to use an HttpClient for testing the endpoints, hence the TestServer is of no use to me.
What I'm no wondering is how can I run kestrel and in the same time run my tests?
I don't think any code here might be of any use but what I got so far is as follows.
Startup.cs
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<IPaymentService>(service => new Services.PaymentService());
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseSoapEndpoint<IPaymentService>("/PaymentService.svc", new BasicHttpBinding());
app.UseMvc();
}
}
PaymentService
[ServiceContract]
public interface IPaymentService
{
[OperationContract]
string ReadPaymentFiles(string caller);
}
public class PaymentService : IPaymentService
{
public string ReadPaymentFiles(string caller)
{
return caller;
}
}
One of my tests:
public void Should_Get_Soap_Response_From_PaymentService()
{
var testServerFixture = new TestServerFixture();
var binding = new BasicHttpBinding();
var endpoint = new EndpointAddress(new Uri("http://localhost:5000/PaymentService.svc"));
var channelFactory = new ChannelFactory<IPaymentService>(binding, endpoint);
var serviceClient = channelFactory.CreateChannel();
var response = serviceClient.ReadPaymentFiles("Ping");
channelFactory.Close();
}
The test does'nt do anything right now since it is not calling any live endpoint, which is my problem...
Separate environment for hotfixes brach?
Currently we moved to gitflow branching model. We defined 2 environments for QA: testing, staging. Code from develop branch is deployed to testing environment, and code from /release branch goes to staging environment. Now we have to apply a hotfix. So we created a separate hotfix branch from master, fixed the bug, and... Where can we test this? Should we have a separate PreProduction env? I'm not sure I should test in on staging, cause on staging we may have a new release under test.
lundi 28 mai 2018
Webpack - how to use loader for file ending with given string?
I have some files called:
core.service.js
second.service.js
And I'm loading them like this:
rules: [
{
test: /\.service\.js$/,
use: { loader: 'service-loader' }
}
I want to rename these files to:
coreService.js
secondService.js
How should I update my "test" rule to load these? I've been trying something like:
test: /\service\.js$/,
but it's not working.
Clojure - how to instrument another protocol in implementation
I'm new in Clojure and after searching for it, I turning my problem to SO community.
I'm testing a protocol implementation (deftype
) who has a reference to another implementation, so constructor is like this :
(deftype FooImpl [^Protocol2 protocol-2]
(function bar [_] ... (.bar2 protocol-2))
)
The ...
are somes condition too meet to call the .bar2
function.
The thing that I'm not able to do, is to instrument (conjure.core/instrumenting
) the call the .bar2
to validate passed parameter (verify-called-once-with-args
).
So problem is this:
(instrumenting [ns/function ;;In normal case with `defn`
????] ;; what to write for .bar2
....)
Thanks!
Is there any automated test framework for Qt for Android besides Squish
We have developed an application using Qt for Android C++. Besides Frologic's Squish, I am wondering if there is open source automated GUI testing tool for such applications?
How do you automate Excel?
I was curious if there were other means besides macros/vba to automate tasks in excel such as the following:
- Launch the Excel and print the version number
- Switch between different tabs, and print Count of tabs.
- User must be prompted with input box (accepts text of any tab names), and then focus must be automatically switched on to the specific tab.
- Print different control types (For Example Ribbon, list…) with in the Excel
I'm currently working on an assignment where I have to do the above, and from the research that I've done it appears that macros may be the only way if not the best way of accomplishing this. I'm just trying to narrow things down and possibly find out if there aren't any other frameworks for automating these tasks that I may of missed?
Thank you in advance
neural network from [., 3] to [., 2] prediction
I have 3 incoming blue-tooth signals and try to predict my x, y coordinates based on these signal strength. I've build a network but can't resolve changing it to a 2 output network.
#my input:
[[50,35,21],[40,36,25],...[20,5,-5]]
#my labels:
[[10,2], [10,2], ...[4,0] ]
My network looks like this:
class Network:
def __init__(self, input, labels):
self.input = input
self.labels = labels
self.num_input = input.shape[1]
self.num_output = labels.shape[1]
self.X = tf.placeholder("float", [None, self.num_input])
self.Y = tf.placeholder("float", [None, self.num_output])
self.layer_1 = tf.add(tf.matmul(self.X, w1 = [self.num_input, 256], b1 = [256])
...
self.lastLayer = tf.matmul(self.layer_5, wLast = [128, self.num_output], bLast = [num_output])
self.loss_op = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits=self.network, labels=self.Y))
self.optimizer = tf.train.AdamOptimizer(learning_rate=self.learning_rate)
self.train_op = self.optimizer.minimize(self.loss_op)
def train(self):
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for step in range(1, 500):
batch_x, batch_y = self.random_batch(self.numpy_input, self.numpy_labels, self.batch_size)
sess.run(self.train_op, feed_dict={self.X: batch_x, self.Y: batch_y})
def predict(self, test_input, test_labels):
#how do I write this
prediction = XXX
for i in range(test_labels):
print("Label: ", test_labels[i], " was predicted as: ", prediction[i]
How to test the upload of .csv file in protractor
I'm trying to test an upload of a csv file in protractor. For wich i have the following code:
const absolutePath = path.resolve(__dirname, 'csvFile.csv');
const fileInput = element(by.css('input[type=file]'));
browser.wait(until.presenceOf(fileInput), 5000, 'File input not found');
fileInput.sendKeys(absolutePath);
browser.wait(until.presenceOf(mockPage.uploadBtn));
mockPage.uploadBtn.click();
But it always throws jasmine timeout. My input field is found, so that's not the problem. And the value of absolutePath it's correct!
./home/user/project/src/test/javascript/e2e/entities/csvFile.csv
My html input code is:
<input id="input-file" type="file" (change)="setFileData($event,'file', false)" />
What i've tried:
- Passing the path as './csvFile.csv'
- Trying to upload a .png file to see if the extension was the problem.
- Searching my input by id to see if there was an error finding the input.
For all these cases the same thing happened, jasmine timeout when writing the path into the input.
Anyone has an idea of what could be the problem? Thanks in advance!
React Jest --coverage ignore
My folder/ project structure for reusable components (i.e. field types) looks like this:
- /fields
- /fields/text
- /fields/radio
- /fields/checkbox
- /fields/...
- /fields/index.jsx (which only reexports each of above for simpler importing purposes)
now when i run jet --coverage i get index.jsx which is just a import/export proxy included into coverage report, is there a way to configure jest runner to ignore "such" files ?
Thanks
Neo4j procedure testing and test server
I'm creating a Neo4J procedure to import RDF data. The RDF data has a few complex structure information and I write the tests to cover every case (some triples creates labels, some properties, some relations...etc..).
The procedures are written in Kotlin.
It works fine, and actually each test when executed individually succeeds. but when I run the whole test case at one, I get one success then all other tests fails with the exception:
org.neo4j.kernel.impl.core.ThreadToStatementContextBridge$BridgeDatabaseShutdownException: This database is shutdown.
I'm new to Neo4J and I struggle to find good examples, here is the structure of a test case:
package mypackage
import org.junit.Assert
import org.junit.Rule
import org.junit.Test
import org.neo4j.driver.internal.value.NullValue
import org.neo4j.driver.v1.Config
import org.neo4j.driver.v1.GraphDatabase
import org.neo4j.harness.junit.Neo4jRule
import java.io.File
import java.net.URI
class PropertyParserTest {
// this rule starts a Neo4j instance
@Rule
@JvmField
var neo4j: Neo4jRule = Neo4jRule()
// This is the procedure/function to test
.withProcedure(Mypackage::class.java)
@Test
@Throws(Throwable::class)
fun shouldSetTheNameCorrectly() {
GraphDatabase.driver(neo4j.boltURI(), Config.build().withoutEncryption().toConfig()).use({ driver ->
driver.session().use({ session ->
// Given
val path: String = File("src/test/resources/test_rdf__1.ttl").getAbsolutePath()
val testFile = File(path)
val urlTestFile: URI = testFile.toURI()
session.run("CALL mypackage.import('${urlTestFile}')")
// When
val result = session.run("MATCH (n) WHERE n:Person RETURN n.name as name")
// Then
var rec = result.next()
Assert.assertEquals("Manuel, Niklaus (Niclaus)", rec.get("name").asString())
rec = result?.next()
Assert.assertEquals("Fischli / Weiss", rec.get("name").asString())
rec = result?.next()
Assert.assertEquals("Hodler, Ferdinand", rec.get("name").asString())
})
})
}
@Test
@Throws(Throwable::class)
fun shouldSetTheAlternateNameCorrectly() {
GraphDatabase.driver(neo4j?.boltURI(), Config.build().withoutEncryption().toConfig()).use({ driver ->
driver.session().use({ session ->
// Given
val path: String = File("src/test/resources/test_rdf_2.ttl").absolutePath
val testFile = File(path)
val urlTestFile: URI = testFile.toURI()
session.run("CALL mypackage.import('${urlTestFile}')")
// When
val result = session.run("MATCH (n) WHERE n:Person RETURN n.name as name, n.alternate_names as alternate_names")
// Then
var rec = result.next()
Assert.assertEquals("Holbein, Hans", rec.get("name").asString())
var alternateNames = rec.get("alternate_names").asList()
Assert.assertEquals(9, alternateNames.size)
Assert.assertEquals("Holpenius, Joannes", alternateNames[0])
Assert.assertEquals("Olpenius, Hans", alternateNames[8])
rec = result.next()
Assert.assertEquals("Manuel, Niklaus (Niclaus)", rec.get("name").asString())
alternateNames = rec.get("alternate_names").asList()
Assert.assertEquals(8, alternateNames.size)
rec = result.next()
Assert.assertEquals("Fischli / Weiss", rec.get("name").asString())
Assert.assertTrue(rec.get("alternate_names") is NullValue)
rec = result.next()
Assert.assertEquals("Hodler, Ferdinand", rec.get("name").asString())
Assert.assertTrue(rec.get("alternate_names") is NullValue)
rec = result.next()
Assert.assertEquals("Holbein", rec.get("name").asString())
alternateNames = rec.get("alternate_names").asList()
Assert.assertEquals(3, alternateNames.size)
})
})
}
}
Any idea ? I'm using this code base as starting point : https://github.com/jbarrasa/neosemantics/blob/3.3/src/test/java/semantics/RDFImportTest.java
I want to get specific string from a text file
Following is the log from which i just wanted to get the string at its end which is "Total conversion time (11766 element(s))|36565 millisecs" and it's number will be change in the new run . like may be second time if i run the software i get "Total conversion time (12366 element(s))|36465 millisecs"
++ LOG> INFO DgnV8Converter.Performance - Convert Spatial Elements> Model 'Office Building' (2 element(s))|64 millisecs [ ] Converting Elements: Model: Architecture :6/3 +++ LOG> INFO DgnV8Converter.Performance - Convert Spatial Elements> Model 'Architecture' (8257 element(s))|5640 millisecs [ ] Converting Elements: Model: Civil :6/2 +++ LOG> INFO DgnV8Converter.Performance - Convert Spatial Elements> Model 'Civil' (164 element(s))|183 millisecs [ ] Converting Elements: Model: MEP :6/1 +++ LOG> INFO DgnV8Converter.Performance - Convert Spatial Elements> Model 'MEP' (2916 element(s))|3593 millisecs [ ] Converting Elements: Model: Structural :6/0 +++ LOG> INFO DgnV8Converter.Performance - Convert Spatial Elements> Model 'Structural' (427 element(s))|493 millisecs +++ LOG> INFO DgnV8Converter.Performance - Convert Spatial Elements (total)|10047 millisecs [ ] Converting Drawings: :5/0 +++ LOG> INFO DgnV8Converter.Performance - Convert Drawings (total)|3 millisecs [ ] Converting Sheets: :4/0 +++ LOG> INFO DgnV8Converter.Performance - Convert Sheets (total)|3 millisecs [ ] Converting Sheets: Model: Office Building :4/4 +++ LOG> INFO DgnV8Converter.Performance - Convert NamedGroups in dictionary (0 element(s))|4 millisecs [ ] Converting Sheets: Converting Relationships :4/0 +++ LOG> INFO DgnV8Converter.Performance - Convert Elements> ECRelationships: Dropped indices for bulk insertion into BisCore:ElementRefersToElements class hierarchy.|1 millisecs +++ LOG> INFO DgnV8Converter.Performance - Convert Elements> NamedGroups|247 millisecs +++ LOG> INFO DgnV8Converter.Performance - Convert Elements> ECRelationships (total)|2 millisecs +++ LOG> INFO DgnV8Converter.Performance - Convert Elements> ECRelationships: Recreated indices for BisCore:ElementRefersToElements class hierarchy.|11 millisecs [ ] Embedding Files: :3/0 [ ] Embedding Fonts: :2/0 [ ] Creating Thumbnails: :1/0 [ ] Creating Thumbnails: View: Model - View 1 :1/8 [ ] Creating Thumbnails: View: Kitchen :1/7 [ ] Creating Thumbnails: View: First Floor Office Space :1/6 [ ] Creating Thumbnails: View: Second Floor Open Space :1/5 [ ] Creating Thumbnails: View: Third Floor Unfinished Space :1/4 [ ] Creating Thumbnails: View: Aerial North Face :1/3 [ ] Creating Thumbnails: View: Aerial West Face :1/2 [ ] Creating Thumbnails: View: Aerial South Face :1/1 [ ] Creating Thumbnails: View: Front Entrance :1/0 +++ LOG> INFO DgnV8Converter.Performance - Finish conversion|26396 millisecs +++ LOG> INFO DgnV8Converter.Performance - Total conversion time (11766 element(s))|36565 millisecs
function ReadFileLines()
{
var str,AFileName="D:\\ConverterElements\\bingo.log";
var F, s;
var s = aqFile.ReadWholeTextFile(AFileName, aqFile.ctANSI);
Log.Message("File entire contents:");
Log.Message(s);
let aSubString="11766 element"
let Res = aqString.Find(s, aSubString)
if ( Res != -1)
Log.Checkpoint("Element Count is same");
else
Log.Error("Element Count is Different");
}
strong text
Python test for missing static file
I have the following MWE (the actual code is bigger, but this is the part I want to test):
def processFile():
try:
with open("localFile.txt", "rb") as f:
# Process file here
except EnvironmentError:
# Handle Exception
My question is: How can I test the function above, to test whether the exception is thrown or not. My understanding of testing (which is very limited) is, that one is calling the function in a test and causing the "failure" to happen, while asserting.
But how can I invalidate the presence of the file, without actually deleting it? Thanks!
TestNG version number differs in pom.xml and in execution log
I added TestNG
dependency in pom.xml
file.
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.14.3</version>
<scope>compile</scope>
</dependency>
I see following during execution of test:
... ... TestNG 6.8.9beta by Cédric Beust (cedric@beust.com) ...
I just wondering, why isn't version 6.14.3 in use?
My espresso tests fail because of interstitial ads
I am new to Firebase / Test-Lab. I was trying to use Firebase Robo and Instrumentation test. During robo tests, interstitial ads are not problem because Firebase Robo test takes back action in this situation but during Espresso test, my test fails because of interstitial ads. Is there any way to prevent interstitial ads during espresso test or pressing back when test codes realize interstitial is came?
Thanks.
Expected true to equal false
I want to test something in angular that really is not in teh Anguar tutorial.
I am trying to test that when the value of this input is invalid teh error message is outputted, so the hidden atributte is false in the case of putting a wor with more than 20 haracters.
<input #cardInput type="text" class="form-control" name="tarjetaSanitaria" id="field_tarjetaSanitaria"
[(ngModel)]="paciente.tarjetaSanitaria" maxlength="20"/>
<div [hidden]="!(editForm.controls.tarjetaSanitaria?.dirty && editForm.controls.tarjetaSanitaria?.invalid)">
<small class="form-text text-danger" id="ref"
[hidden]="!editForm.controls.tarjetaSanitaria?.errors?.maxlength" translateValues="{ max: 20 }">
This field cannot be longer than 20 characters.
</small>
My component has this:
paciente: Paciente = {tarjetaSanitaria: 'ddd'} as Paciente;
And my test:
fit ('Blank input is not valid', async(() => {
comp.paciente.tarjetaSanitaria = 'ddddddddddddddddddddddddddddddddddddddddddd' ;
spyOn(comp, 'save');
var1 = comp.submitButton.nativeElement;
var1.click();
fixture.detectChanges();
expect(comp.save).toHaveBeenCalledTimes(1);
expect(fixture.debugElement.query(By.css('#ref')).nativeElement.hasAttribute('hidden')).toEqual(false);
}));
It always fails saying Expected true to qual false.IF I remove fixture.detectChanges it aways passes. Have I done something wrong?
Automatically run complete code base in IE11 and check for syntax problems
Our JavaScript web application has a rather big code base. It is required to work in Internet Explorer 11. One of our biggest problems is that far too often, programmers (both our own and 3rd party) use JavaScript functions like contains
or startsWith
which are not implemented in IE11. Of course, unit tests would detect problems like that. However, writing of those lag behind and the code coverage is embarrassing small.
So, I'm wondering: Is there a fast and easy way to run a complete web application/JavaScript file in IE11 without any expectations
and just checking for syntax problems?
E.g. assume you have a code snippet like this:
if(myVar == 12) {
var someString = 'foohoo';
var doesMyStringStartWithSomething = someString.startsWith('f');
return 24 + 3;
}
In "normal" unit tests, you would have to mock myVar
and expect some return value. What I have in mind is: Run the code, entering each line, regardless if it is in a conditional block or in a function which is never called or whatever: Simply try to execute it. If there is a syntax problem (like in this case something like: "Object foohoo has no method 'startsWith'"), then stop with an error. And don't care about the results: E.g. if the browser miscalculates 24 + 3
and returns 666 instead of 27, we wouldn't care at this point.
End-to-end tests with something like Protractor are not a solution here, because you have to write test cases here, too, in order to trigger the execution of all bits and pieces of JavaScript.
dimanche 27 mai 2018
Referencing elements in unit and selenium tests when "class" is not available
I'm developing projects using javascript (React). I'm using modular css which randomizes class
name so I cannot have a hold on it using css selectors later in tests.
What are my options if I want to make referencing UI elements easier in tests (be it unit or selenium)?
How can I get webpacker's compilation to immediately be reflected in rspec/capybara runs?
I'm running Rails 5.1.4 (with spring), @rails/webpacker 3.4, poltergeist 1.18.1, phantomjs 2.1.1, rspec 3.7.0, capybara 2.17.0.
When I run capybara specs locally, I do not precompile assets, but rather allow webpacker to compile assets automatically in memory. When I have modified assets, I can see in the logs that webpacker is compiling, but when the specs run, the assets are not picked up--in that the javascript does not run causing tests to fail.
When I re-run the same rspec command, there is no compilation, and assets are loaded correctly.
Program won't print out a string unless another string is printed before it
I have a java program that simulates an interpreter.
When I loop through following commands given to it:
x = 4
y = 10
print x * y
x = x + 1
print x
It should return/print
40
5
But it gives nothing.
Now if I do
System.out.println("whatever here");
Before the actual print command is given, it returns:
whatever here
40
whatever here
5
Has anybody ever had this problem and how should I deal with it?
I can't really post the code because it's in my native language but I can give answers about it if it helps.
Need web applications tailored to practice performance
I am looking for sample web application which are specifically designed for experimenting performance and fault tolerance testing. I need it to test different performance testing strategies against know performance flows in the application. Thanks in advance.
samedi 26 mai 2018
Override Go Method in Tests
So I have this Client
struct that has a method UserByID
that makes a HTTP request to an endpoint for a User
. I want to unit test this function but also not make an actual HTTP request in the function c.Request
. I want to stub that function with a response and error I can control.
func (c Client) UserByID(id string) (u User, err error) {
v := url.Values{}
v.Set("id", id)
opts := Request{
HTTP: http.Request{
Method: http.MethodGet,
Form: v,
},
URL: 'some/endpoint/users',
}
resp, err := c.Request(opts)
err = json.Unmarshal(resp, &u)
return
}
Here's what the stub looks like:
type mockClient struct {
Client
fakeUser User
fakeError error
}
func (mc mockClient) Request(opts Request) (resp []byte, err error) {
resp, err = json.Marshal(mc.fakeUser)
err = mc.fakeError
return
}
In a single test I have something like:
client := mockClient{
fakeUser: User{},
fakeError: nil,
}
user, err := client.UserByID(c.id)
Then I can assert the return values from client.UserByID
. In this example I'm trying to override the client.Request
function but I understand Go is not an inheritance-type of language. In my tests, my mockClient.Request
function is not being called. The original client.Request
is still being called.
I then assume that my approach is not right then. How can I test client.UserByID
without actually calling the real client.Request
function within it? Should the design of my methods be different?
spring boot test like unitils
is there any test framework like unitils for coding spring boot test case ?.for spring project ,it specify configuration like applicationContext.xml, and unitils is base on this xml ,it can prepare dataset before running test by xml or excel and after test completed ,it delete the record in the database ,so it works well anytime ,but now spring boot dot not provide this function . enter image description here
vendredi 25 mai 2018
How to run an entire test suite with Selenium & JUnit 5 on different URLs
I have a test class that currently uses parameterized tests to run each test on different URLs. However I want the output to be in the form
Url
- Failed Test 1
- Failed Test 2
instead of
Test
- Failed URL 1
- Failed URL 2
I can accomplish this by having a seperate class for each URL but there are over 300 URLs so that's not really an option. The classes would be the same except for paremters though so:
- Is there a way to do this in JUnit (essentially I want to parameterize the whole class) if not:
- Would log4j be able to accomplish this if not:
- Is there a way to make the classes at runtime automatically if not:
- What testing framework can accomplish this, I am open to any software that can do this
How to write good test unit/functional test for such case?
This thread is more about idea not giving ready code.
I'am currently making Dusk (Selenium implemented in Laravel) tests for application. I have functionality which is returning : search users which like color blue. It's ofc bit more complicated (relations, many models etc. etc.). I wrote 2 tests right now.
-
searching for users who likes color abc. Only my test users like it so I know what result I should get. I am doing comparison between db query and int.
-
searching for users who likes color (random from available colors) in db. It's same logic as previous with real color name.
I think that it's not good, beacause I never know what result I should get from db. Checking manually in db is hard with large amount of users.
I am asking for some ideas how and what I should test to be shure that functionality returns correct result.
Bug when simulating click event
I am trying to test input fields in form. However when using Enzyme.js
to simulate
change in input field the state
is incorrectly updated, since the log reveal that simulate
function has created new record in state named undefined
.I'd be really glad for help.
Regards
Initial component state looks like this:
this.state = {
submission: {
firstName: '',
lastName: '',
email: '',
date: new Date(),
validation: {
email : {isInvalid: false, message: ""},
firstName : {isInvalid: false, message: ""},
isValid : true,
lastName : {isInvalid: false, message: ""}
}
}
}
This is the testing function:
it('should respond to change event and change the state of the Component', () =>{
const wrapper = shallow(<ApplicationForm/>);
console.log(wrapper.find('#firstName').debug());
wrapper.find('#firstName').simulate(
'change', {
target: {
name: 'firstName',
value: 'John'
}
}
)
expect(wrapper.state().submission.firstName).to.equal('John');
})
This is what I expect to get in state:
submission: {
firstName: 'John',
...
}
And this is what I get when I inspect result with wrapper.debug
submission: {
firstName: '',
lastName: '',
email: '',
date: new Date(),
validation: {
email : {isInvalid: false, message: ""},
firstName : {isInvalid: false, message: ""},
isValid : true,
lastName : {isInvalid: false, message: ""}
},
undefined: 'John'
}
Below you can see the code of the rendered form:
<input type="text"
id="firstName"
className="form-control form-control-sm"
placeholder="First name"
onChange={this.updateSubmission.bind(this)}
/>
updateSubmission function looks as follows:
updateSubmission(event) {
let updatedSubmission = Object.assign({}, this.state.submission);
updatedSubmission[event.target.id] = event.target.value;
this.setState({
submission: updatedSubmission
});
}
Selenium table count
I am testing a Java 7 web application developed with Vaadin 7 and I used to calculate the total number of rows in a table with the following code:
WebElement table= driver.findElement(By.xpath("//* [@id='grdEvRequestSearchView']/div[3]/table"));
List <WebElement> gridrow = table.findElements(By.tagName("tr"));
int rowNumber= gridrow.size();
Now the new version of the application put in a page a Vaadin grid component instead of table, now what I obtain from the count is the number of elements that currently visible: if I have a grid of 50 elements and only 10 are visible I obtain 10 and not 50 as I got in the past when table component. Is there any way to get the effective count of rows and not the visible ones?
Andres
Working with cypress redirect
Situation: I am writing test automation for a website. There comes a point where there is a link button on my website. Clicking this I am redirected to an external website. There I have to log in and as soon as I do that I am redirected to my original web-page which contains some 'connections' that I need.
Problem: As soon as cypress clicks on the redirection button it does into a blank page.
Ideal solution: I would want to automate the entire scenario. If not then at-least a work around.
Can I uncommented a line of commented code in a javascript function after it is loaded in the DOM?
I'm testing a webpage with javascript commented out - I'd like to test the commented functionality and do not have the option to push a new version of the page with the comment notation removed.
Is there a way (using firefox console perhaps?) to remove the comment notation and re-enable a portion of a script already loaded on a page?
Testing Methodologies Using Python
I need to understand testing methodologies both in terms of an overview and specific examples using Python. I need to cover the following types of testing: dry run, walkthrough, white-box, black-box, integration.
I'm having some conceptual difficulties and would appreciate some clarification for a few specific issues, preferably with code examples if appropriate.
-
Does using a trace table come under white-box testing, or dry-run, or both?
-
Is using
doctest
in Python for testing specific values an example of black-box or white-box testing? -
What about the kinds of tests found on sites like Codewars and Hacker Rank - test cases with things like
assert_equals(my_function(args), expected)
? Is this black or white box, or something else? -
Would an example of integration testing be importing a new module and then testing if the program still works as expected?
The context here is very small projects with perhaps just 2 or 3 files written for the purposes of learning.
Having very short examples of code which implements black-box testing and code which implements white-box testing would be very helpful indeed.
How to ignore code during a PHPUnit Test
I am creating unit tests in php.
There is one line in the code under test which generates a random number and assigns it to property of an object. This object is then compared as an assertion.
Because of this, I cannot get the test to pass, so I'm wondering; is there a way to ignore this line with any compiler variable or similar?
Any help is greatly appreciated.
Expected spy on log to equal 'Authentificated failed'
I need to test compare to value. I tried this exapmle:
I have this component.ts
export class AppComponent implements OnInit {
title= 'Angular'
constructor() { }
ngOnInit() {
}
}
And in component.spec.ts
it(`should have as title 'Angular'`, async(() => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.debugElement.componentInstance;
expect(app.title).toEqual('Angular');
}));
it(`should have as title 'Angular'`, async(() => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.debugElement.componentInstance;
expect(app.title).toEqual('Angular1');
}));
I follow this example that is simple. But now I need to compare my response value with some value
Step1. Html Component
<div id="container">
<div id="login_card_container">
<div id="login_card" class="card col s12">
<form [formGroup]="loginForm" (ngSubmit)="onLogin()" class="col s12">
<h1 id="form_title">Login</h1>
<div class="row">
<div class="input-field col s12">
<input formControlName="username" id="username" type="text" class="validate" [ngClass]="{invalid: invalidCredentials}">
<label for="username">Username</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<input formControlName="password" id="password" type="password" class="validate" [ngClass]="{invalid: invalidCredentials}">
<label for="password" data-error="Your username/password combination is invalid">Password</label>
</div>
</div>
<div id="login_button_container" class="row">
<button id="login_button" type="submit" class="btn waves-effect waves-light" [disabled]="!loginForm.valid">
<i class="fa fa-sign-in left"></i>
Login
</button>
</div>
</form>
</div>
</div>
</div>
Step 2: TS Component
onLogin() {
this.loading = true;
this.ws.login(
this.loginForm.controls['username'].value,
this.loginForm.controls['password'].value)
.subscribe(
result => {
if (result === true) {
} else {
this.loading = false;
this.invalidCredentials = true;
}
});
}
This is my first attempt,and show this error
Expected spy on log to equal 'Authentificated failed'.
In fact this is successful because response from service is this message Authentificated failed
it('should notify in console on form submit', () => {
spyOn(console, 'log');
component.loginForm.controls['username'].setValue('admin');
component.loginForm.controls['password'].setValue('11');
fixture.debugElement.query(By.css('form')).triggerEventHandler('ngSubmit', null);
fixture.detectChanges()
expect(console.log).toEqual('Authentificated failed');
});
In this code, I want toEqual
service response with ('Authentificated failed')
like in first example
Can you suggest my how to compare result
form service, with some text?
I do not understand how I can test the success of sending mailgun with jest
I have app.js on express and mailgun, i need to test the success of sending mailgun with jest.
////////////app.js///////
var express = require('express');
var bodyParser = require('body-parser')
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
// Adding headers to support CORS
app.use('*', function (req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET, PUT, POST, DELETE, OPTIONS');
res.header('Access-Control-Allow-Headers', 'Accept, Origin, Content-Type, access_token');
res.header('Access-Control-Allow-Credentials', 'true');
next();
});
console.log("Preparing server!")
// Handling request
app.post('/get-client-data', function (req, res) {
// console.log("Got a request: ", req.body);
var postQuery = req.body.query;
var name = postQuery.name;
var email = postQuery.email;
var message = postQuery.message;
var mailgun = require("mailgun-js");
var api_key = 'some key';
var DOMAIN = 'some Domain';
var mailgun = require('mailgun-js')({ apiKey: api_key, domain: DOMAIN });
var data = {
from: 'Mailgun <postmaster@' + DOMAIN + '>',
to: 'Sales team <some@sales.io>',
subject: 'Name of client: ' + name + ', email: ' + email,
text: message,
};
mailgun.messages().send(data, function (error, body) {
console.log(body);
});
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify({ 'response': 'email has been sent' }));
});
app.listen(3000, function () {
console.log('backend is listening on port 3000!');
});
module.exports = app;
I do post from frontend to beckend and then mailgun sending.
MB i shoult to mock mailgun sending or response to mailgun api.
How do you reliably wait for page idle in cypress.io test
When using cypress.io to test an angular web page, whats the best / most reliable way to detect when the page is fully loaded and idle. Not just the onload event. Needs to include all xhr requests, angular digest cycles complete and all rendering complete.
The reason is that at this point I want to test that the page does NOT contain an element and cant test that until all the above is fully complete.
Android test app/service/something for testing PLAYBACK and record?
I am new to Android app development and testing. I wanna implement apk or some background service or something else ( I don't know what suites better to my situation).
Goal: A piece of code to test the playback. The code should take a wave file and play it through all the layers of android.
Can anyone suggest me the best ways of doing? I don't want any UI for this. I wanna run it using the am or something else.
Can anyone please help me in this.
Automation testing desktop application tool
Im trying to find a tool to automate testing of our desktop application. I can find all kind of tools for web application but nothing that is useful for windows application. We will have both integretiong and system testing. What we need is that it works on windows program, you can send Soap Request maybe database plugin. The code is c#
Someone of experice can give us a hint of a good tool to start with.
thank you
How to test mobile apps on different devices
I want to test my IOS,Android and hybrid apps on various virtual devices. Please suggest me a good tool that can perform these functions.
jeudi 24 mai 2018
Enzyme: How to test interactions on shallow component
Basically I want to test, that a 'select all' checkbox works, using Enzyme+Jest with a shallow root object.
I want to test some basic UI interaction with my list component.
1) Verifying, that no checkbox at all is selected beforehand, does work:
const allBox = list.find('Checkbox.select-all')
expect(allBox.prop('checked')).toBe(false)
mainRows.find('Checkbox').forEach( (node) => {
expect(node.prop('checked')).toBe(false)
})
But I can't trigger a click i.e.
allBox.simulate('click')`
because Checkbox is of course still a shallow <Checkbox>
not an actual html-ish <input type='checkbox'…>
.
What can I do?
Mounting (actually rendering) the entire list component will become to vast. Can I somehow just mount the tiny https://ift.tt/2scp76Z)
Anything else before expect()
ing that all is selected now?
Do I need to list.instance().forceUpdate()
? There is some discussion on the Enzyme tracker, on wether/how .update() works…
Anyway, no luck for me:
Expected value to be: true
Received: false
180 | allBox.simulate('change')
181 | list.instance().forceUpdate()
182 |
> 183 | expect(allBox.prop('checked')).toBe(true)
184 | // verify, that did the job:
185 | mainRows.find('Checkbox').forEach( (node) => {
186 | expect(node.prop('checked')).toBe(true)