I want to generate a bug report from Bugzilla, which should be consist of following status
Confirmed In progress Verified and Closed So how I can generate the report with the mentioned status?
I am testing a webhook that Stripe uses to communicate with my Laravel application. I am using PHP Stripe Webhooks Tester for this and I'm following their official tutorial.
Here's my Test Case:
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use TeamTNT\Stripe;
class WebhooksControllerTest extends TestCase
{
/**
* A basic test example.
*
* @return void
*/
public function testWhenCustomerSubscriptionDeleted()
{
$tester = new TeamTNT\Stripe\WebhookTester('http:/localhost/stripe/webhook');
$response = $tester->triggerEvent('customer.subscription.deleted');
$this->assertEquals(200,$response->getStatusCode());
//$this->assertTrue(true);
}
}
When I run phpunit
I get the following error:
PHPUnit 5.7.5 by Sebastian Bergmann and contributors.
E 1 / 1 (100%)
Time: 4.57 seconds, Memory: 10.00MB
There was 1 error:
1) WebhooksControllerTest::testWhenCustomerSubscriptionDeleted
GuzzleHttp\Exception\ConnectException: cURL error 6: Could not resolve host: http (see http://ift.tt/1mgwZgQ)
/home/levi/SIGadmin/vendor/guzzlehttp/guzzle/src/Handler/CurlFactory.php:186
/home/levi/SIGadmin/vendor/guzzlehttp/guzzle/src/Handler/CurlFactory.php:150
/home/levi/SIGadmin/vendor/guzzlehttp/guzzle/src/Handler/CurlFactory.php:103
/home/levi/SIGadmin/vendor/guzzlehttp/guzzle/src/Handler/CurlHandler.php:43
/home/levi/SIGadmin/vendor/guzzlehttp/guzzle/src/Handler/Proxy.php:28
/home/levi/SIGadmin/vendor/guzzlehttp/guzzle/src/Handler/Proxy.php:51
/home/levi/SIGadmin/vendor/guzzlehttp/guzzle/src/PrepareBodyMiddleware.php:72
/home/levi/SIGadmin/vendor/guzzlehttp/guzzle/src/Middleware.php:30
/home/levi/SIGadmin/vendor/guzzlehttp/guzzle/src/RedirectMiddleware.php:68
/home/levi/SIGadmin/vendor/guzzlehttp/guzzle/src/Middleware.php:59
/home/levi/SIGadmin/vendor/guzzlehttp/guzzle/src/HandlerStack.php:67
/home/levi/SIGadmin/vendor/guzzlehttp/guzzle/src/Client.php:275
/home/levi/SIGadmin/vendor/guzzlehttp/guzzle/src/Client.php:123
/home/levi/SIGadmin/vendor/guzzlehttp/guzzle/src/Client.php:129
/home/levi/SIGadmin/vendor/guzzlehttp/guzzle/src/Client.php:87
/home/levi/SIGadmin/vendor/teamtnt/php-stripe-webhook-tester/src/Stripe/WebhookTester.php:85
/home/levi/SIGadmin/tests/WebhooksControllerTest.php:18
/usr/share/php/PHPUnit/TextUI/Command.php:155
/usr/share/php/PHPUnit/TextUI/Command.php:106
FAILURES!
Tests: 1, Assertions: 0, Errors: 1.
I looked up the error code, I found this (source):
Couldn't resolve host. The given remote host was not resolved.
Here's my route for this webhook:
Route::post('stripe/webhook', 'WebhooksController@handle');
And here's my actual webhook:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
class WebhooksController extends Controller
{
public function handle()
{
$payload = request()->all();
$method = $this->eventToMethod($payload['type']);
if(method_exists($this, $method))
{
$this->$method($payload);
}
return response('Webhook Received');
//return redirect('myaccount')->with('success', 'Account deactivated');
}
public function whenCustomerSubscriptionDeleted($payload)
{
User::byStripeId(
$payload['data']['object']['customer']
)->deactivate();
}
public function whenCustomerSubscriptionCreated($payload)
{
User::byStripeId(
$payload['data']['object']['customer']
)->addSubscriptionId($payload['data']['object']['id']);
}
public function eventToMethod($event)
{
return 'when' . studly_case(str_replace('.', '_', $event));
}
}
I'm trying to test my React application and I can successfully test reducers and component states with Simulate
on a onClick
handler, but I can't seem to test setting a component state when the change in state is based on an async request. Would love some help :) Thanks!
My test.utils file
import jsdom from 'jsdom';
import _$ from 'jquery'; // _$ instead of $ because '$', will try and reach out to browser which is not avail.
import TestUtils from 'react-addons-test-utils';
import ReactDOM from 'react-dom';
import chai, { expect } from 'chai';
import React from 'react';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import reducers from '../../src/reducers/index.js';
import chaiJquery from 'chai-jquery';
// 1. Set up testing environment to run like a browser in the command line
// window (browser global env)--> global (in terminal)
global.document = jsdom.jsdom("<!doctype html><html><body></body></html>");
global.window = global.document.defaultView;
// hooking jQuery to our version of window
// don't go out to the DOM, just be responsible for the window created above
const $ = _$(global.window);
// 2. Build 'renderComponent' helper that should render a given react class
/**
* [renderComponent description]
* @param Class ComponentClass React Class or Functional Component to render
* @param Object props Props for the Component to render
* @param Object state Setting a temporary state for test purposes
* @return jQueryWrapped DOM selection
*/
function renderComponent(ComponentClass, state, props) {
// componentInstance --> rendered instance of our component
// <Provider> element is required because redux expects components to be
// rendered within a <Provider> element
const componentInstance = TestUtils.renderIntoDocument(
<Provider store={createStore(reducers, state)}>
<ComponentClass {...props}/>
</Provider>
);
// ReactDOM.findDOMNode --> gets reference to our componentInstance HTML
return $(ReactDOM.findDOMNode(componentInstance)); // produces HTML
}
// 3. Build helper for simulating events
// Adding simulate to jQuery library
$.fn.simulate = function(eventName, value) {
// "this" refers to the jQuery element form $('element') e.g. $('div');
// jQuery selectors return an array
if (value) {
this.val(value);
}
TestUtils.Simulate[eventName](this[0]);
}
// 4. Setup chai-jQuery
chaiJquery(chai, chai.util, $);
export { renderComponent, expect };
My Verify test
// Test Helpers
import {renderComponent, expect} from '../../../helpers/test_helper.js';
import TestUtils from 'react-addons-test-utils';
// Component to Test
import Verify from '../../../../src/modules/App/components/Authentication/Verify';
import authReducer from '../../../../src/reducers';
import {
USER_VERIFIED,
USER_NOT_VERIFIED,
USER_VERIFIED_UNDEFINED
} from '../../../../src/actions/types.js';
describe('Components - Authentication/Verify', () => {
let component;
it('Shows verified notice when verified', () => {
const action = { type: USER_VERIFIED };
component = renderComponent(Verify, { authReducer: { userVerified: true} });
console.log('component: ', component)
// if (authReducer({}, action).authReducer.userVerified) {
// console.log('verified: ', component)
expect(component.find('.verified-content').length).to.eql(1);
// }
});
});
My Verify component
// Other Libraries
import React, { Component } from 'react';
import { connect } from 'react-redux';
// Our Code
import { verify } from '../../../../actions/auth.js';
import { BUSINESS_TEAM_NAME } from '../../../../../utils/constants.js';
class Verify extends Component {
constructor(props) {
super(props)
this.state = { validURL: false }
}
componentWillMount() {
let params = window.location.href,
token = null;
// Check if URL contains token required by server
if (params.includes('?') && params.includes('=') && params[1].split('=')) {
if (params.indexOf('token')) {
let index;
params = params[1].split('=');
index = params.indexOf('token');
token = params[index + 1];
this.setState({ validURL: true });
} else { this.setState({ validURL: false }) }
}
// If valid token exists, verify the user
token != null ? this.props.verify(token) : '';
}
// Once user is successfully verified, render this content.
renderVerifiedContent() {
return (
<div className="container container-center-content verified-content">
<h2>Welcome to {BUSINESS_TEAM_NAME}</h2>
<p>Your account has now been verified.</p>
</div>
)
}
// Render verification error
renderLoading() {
return (
<div>Attempting to verify your account...</div>
)
}
renderUnableToVerify() {
return (
<div className="container container-center-content">
<h2>Verification Error:</h2>
<p>We are unable to verify your account right now. Please check that you clicked on the link in your email. If that doesn't work, try right-click and copy the link. Otherwise, try again later. We apologise for this inconvenience.</p>
<p>Hope you have a great day!</p>
<p>{BUSINESS_TEAM_NAME} Team</p>
</div>
)
}
render() {
return this.state.validURL
? this.props.userVerified != undefined && this.props.userVerified
? this.renderVerifiedContent()
// Only render loading if request is still in progress,
// otherwise user might still think its being verified
: this.props.userVerified == undefined ? this.renderLoading() : this.renderUnableToVerify()
: this.renderUnableToVerify()
}
}
function mapStateToProps(state) {
return {
userVerified: state.authReducer.userVerified
}
}
export default connect(mapStateToProps, { verify })(Verify);
In a multiproject build, some projects depend on others, and the latter provide not only compile/runtime libraries, but also useful test libs (such as, for instance, "mock" implementations of the components they provide).
I know of a couple of ways to make the test sources of one project available to another. They are discussed, for instance as answers to this question.
What I am looking for is some magical way to make this happen automatically, so that if a subproject adds a dependency on another subproject, it automatically gets that projects test sources added to the testCompile
config.
I tried the naive approach:
configure(rootProject.subprojects.findAll {
it.configurations.getByName("compile")
.dependencies.any {
it.name == project.name
}
}) {
dependencies {
testCompile project.sourceSets.test.output
}
}
But this does not work ... presumably, because this code is evaluated "at the wrong stage" (or whatever the correct lingo is), and the other projects don't "know" yet that they depend on this one.
I also tried putting (an equivalent of) this at the end of root build file (hoping, that everything else would already be configured by then), but that did not work either.
Is there a way to do what I am looking for here?
I am testing a React component.
My React component has a ref - http://ift.tt/2ePLKpP - that is necessary for some functionality.
My testing code has a line like
const document = ReactTestUtils.renderIntoDocument(<MyReactComponent></MyReactComponent>);
in a beforeEach function.
Normally, the tests fail with
addComponentAsRefTo(...): Only a ReactOwner can have refs. You might be adding a ref to a component that was not created inside a component's `render` method, or you have multiple copies of React loaded .
If I comment out that line from the beforeEach, the tests will fail because document is null - which suggests that it was that line that created the addComponentAsRefTo
problem.
If I remove the ref from the element, then the specs will run and most will pass. The failing specs are related to functionality that depends on the ref. This suggests that the problem is related to refs.
Together, I am fairly confident that ReactTestUtils.renderIntoDocument
does not work properly with elements that have refs in them.
This was mentioned in http://ift.tt/2hzIUsM
I've got a:
TypeError: page.fillForm is not a function
every time I try to run my tests. Before I started to use PageObject everything was ok.
Here is my spec file: contactBook_spec.js
describe("Contact book", function(){
beforeEach(function(){
browser.ignoreSynchronization = true;
browser.get("http://ift.tt/2ilh821");
});
xit("Should be able to save new contact details", function(){
expect(browser.getCurrentUrl()).toContain("contactbook");
element(by.css("#nameInput")).sendKeys("Vladimir");
element(by.css("#surnameInput")).sendKeys("Putin");
element(by.css("#emailInput")).sendKeys("vlad@hack.ru");
element(by.css("#phoneInput")).sendKeys("+01 123456");
element(by.css("#saveBTN")).click();
});
xit("Should find saved contact", function(){
element(by.css("#nameInput")).sendKeys("Vladimir");
element(by.css("#surnameInput")).sendKeys("Putin");
element(by.css("#emailInput")).sendKeys("vlad@hack.ru");
element(by.css("#phoneInput")).sendKeys("+01 123456");
element(by.css("#searchBTN")).click();
expect(element(by.css('tr td')).getText()).toContain("Vladimir");
expect(element(by.css('tr td')).getText()).toContain("Vladimir");
});
var page = require('./page/home_page.js');
it("Should be able to test by page objects", function(){
page.fillForm('Adam', 'Eva', 'c@c.o', '1230');
page.clickSave();
});
});
And here is page object file: home_page.js
var home_page = function(){
this.fillForm = function(name, surname, email, phone){
element(by.css("#nameInput")).sendKeys(name);
element(by.css("#surnameInput")).sendKeys(surname);
element(by.css("#emailInput")).sendKeys(email);
element(by.css("#phoneInput")).sendKeys(phone);
};
this.clickSave = function(){
element(by.css("#saveBTN")).click();
};
};
module.exports = home_page;
I can't figure out what's wrong. I'm running test on Protractor v. 4.0.14 and Node v. 6.9.2
I was testing my Rails 5.0 application with the following code:
test "destroy should require logged-in user" do
assert_no_difference 'AtpSelection.count' do
delete :destroy, params: { id: atp_selections(:selection_1) }
end
assert_redirected_to login_url
end
but the test kept failing:
ERROR["test_destroy_should_require_logged-in_user", AtpSelectionsControllerTest, 1.9559332270000596]
test_destroy_should_require_logged-in_user#AtpSelectionsControllerTest (1.96s)
URI::InvalidURIError: URI::InvalidURIError: bad URI(is not URI?): http://www.example.com:80destroy
So, in order for the test to pass, I had to change my code using instead the following code:
test "destroy should require logged-in user" do
assert_no_difference 'AtpSelection.count' do
delete atp_selection_path(atp_selections(:selection_1))
end
assert_redirected_to login_url
end
I have no idea why I could not make the test pass calling delete
directly on the controller action :destroy
. I made this same choice in other tests I created before for other controllers and they succeed without raising errors.
I'm trying to write test cases for my web api methods.
[Fact]
public async Task Get_Message_By_Id()
{
var messages = new Messages()
{
MessageId = 1,
Recipient = "1;2;3",
Subject = "Test Subject",
MessageText = "test subject"
};
var mesBL = new Mock<IMessagesBusinessLogic>();
mesBL
.Setup(repo => repo.GetRecivedMessageById(It.IsAny<IWebToken>() ,messages.MessageId))
.Returns(Task.FromResult(messages));
var messageController = new MessagesController(mesBL.Object);
var contentResult = await messageController.GetRecivedMessageById(messages.MessageId) as OkObjectResult;
Assert.NotNull(contentResult);
}
I get an error of null reference
while GetRecivedMessageById
method call.
Controller method;
[HttpGet]
[Route("{id:int}")]
public async Task<IActionResult> GetRecivedMessageById(int id)
{
return Ok(await _messagesBusinessLogic.GetRecivedMessageById(User.GetWebToken(), id));
}
Here, issue is because, user identity passing NULL.
GetWebToken()
:
public static IWebToken GetWebToken(this ClaimsPrincipal principal)
{
var identity = principal.Identity as UserIdentity;
if (identity == null)
throw new InvalidOperationException(" ");
return identity.WebToken;
}
How can we pass it from Test?
I'm trying to run a simple test with mochajs
:
var assert = require('assert'),
ActionCreators = require('../src/components/Dashboard/ActionCreators.js');
describe('', function () {
it('', function () {
assert.equal(1, 1);
});
});
But it throws errors that the ActionCreators
file contain import
keywords. It does, becuase I run my code with webpack, and it goes through babel.
I've been trying to run this test with mocha-webpack
, but it's the same. How should I do this?
I have a gradle project with 2 Test tasks, test and test2.
When running gradle test test2
2 times both test
and test2
ran again even though they should be UP-TO-DATE
(when running gradle test
It stays UP-TO-DATE
no matter how many times I ran it).
Why is this happening?
void start() {
bar.foo()
.filter(i -> i % 2 == 0)
.subscribeOn(computation())
.observeOn(io())
.subscribe(new FooSubscriber());
}
In this function I see 3 points to test:
bar.foo()
.filter
is correctly implemented.bar.foo()
.The first point is easy to test with Mockito.verify()
. But I have no idea about how to test the other points.
How can I test this code? Must I refactor it? How?
Please, think that filter
is just an example, I have a big chain with different operators.
I tried the command go test -cpuprofile cpu.out on a GO test file and it resulted in a file cpu.out which is full of many 64 bit numbers. It doesn't make any sense to me. What did the command do and what information can get I extract from cpu.out file?
Similarly go test -memprofile mem.out generated a mem.out file which also seems to make no sense to me. Help me out.
I have attached both the files.
I unable to click Open button and getting an exception as "No such element exception". I tried all XPath and id but same exception I am getting. I have tried getContextHandles() and it returns size as one. it means control cannot switch. Kindly help me to click the "Open" button.
I want to know the best practice for placing test files in express application. I am using mocha and chai. Should I place all tests in one test folder or should I place them with my SRC files with .test.js extension?
Which is favorable for automating tests with npm scripts?
I want to add all the language it should only count the English words but the my program counting everything so please check on it and help me out
I have a problem and a don't know how to solve it. I saw some tools for automation testing for android apps, like appium and others. They connect to the android device, emulator, from outside the device and open the application to be tested. I want to know how can i build a native android app that can to the same thing. Open another application and start executing different operations on the UI of that app. For a simple example, let's say i have a social app that i want to test. I want another that runs on the phone that opens my social app and starts running some operations like searching inside the app, clicking on different posts, liking post, s.o. Is there a way to do this? Are there any frameworks or methods for doing this?
Regards.
Can you guys please suggest some good books?
Topics I want to read about:
Thank you!
I am doing testing on software used in clinical trials.
There are components that are repeated throughout the forms. For example, there is a date component that appears repeatedly across a number of forms. It has some peculiarities such as accepting UNK in the month and day fields.
Does this field need to be tested new each time it appears? I am told that from a regulatory standpoint each instance must be tested for all possible cases individually, even if the code is replicated across the forms.
Does anyone have any insight on best practices here? I am overwhelmed by the amount of work it will take to confirm the proper functioning of each field individually.
Thanks for any advice!
I have a C# unit test project where I'd like to test some encryption extensions that I've written. I would like to use a dummy cert for testing, but I have the following restrictions:
.pfx
file) as part of the git repository or build, as doing so would violate security protocols. Thus, I cannot read the cert from a file included in the project.Since I'll be doing encryption and decryption, I need to have the private key information. How can I create this cert programmatically within these restraints?
I am a developer that never understood testing properly. I am reading up on unit testing, TDD, and other relevant topics that come up together since I am primarily trying to understand the concepts behind Continuous Integration.
What is particularly tested on a CI server? Is it just the unit tests written by the developers? Are testers in less demand since the CI is doing a lot of the heavy lifting here and are they still relevant?
I currently have a failing test for one of my mailers and can't figure out what's causing it. I've tried some other solutions on stack like, adding Rails.application.routes.default_url_options[:host] = '???'
to the config environment files but to no avail. Here is the error output form the terminal
Error:
OrderMailerTest#test_shipped:
ActionView::Template::Error: undefined method `protect_against_forgery?' for #<#<Class:0x007f97fe5f0080>:0x007f97ff82b790>
app/views/line_items/_line_item.html.erb:9:in `_app_views_line_items__line_item_html_erb__1698223746397690403_70145401700580'
app/views/order_mailer/shipped.html.erb:7:in `_app_views_order_mailer_shipped_html_erb__790900287724335052_70145401782860'
app/mailers/order_mailer.rb:23:in `shipped'
test/mailers/order_mailer_test.rb:14:in `block in <class:OrderMailerTest>'
bin/rails test test/mailers/order_mailer_test.rb:12
order_mailer_test.rb
require 'test_helper'
class OrderMailerTest < ActionMailer::TestCase
test "received" do
mail = OrderMailer.received(orders(:one))
assert_equal "Pragmatic Store Order Confirmation", mail.subject
assert_equal ["dave@example.org"], mail.to
assert_equal ["depot@example.com"], mail.from
assert_match /1 x Programming Ruby 1.9/, mail.body.encoded
end
test "shipped" do
mail = OrderMailer.shipped(orders(:one))
assert_equal "Pragmatic Store Order Shipped", mail.subject
assert_equal ["dave@example.org"], mail.to
assert_equal ["depot@example.com"], mail.from
assert_match /<td>1×<\/td>\s*<td>Programming Ruby 1.9<\/td>/, mail.body.encoded
end
end
and my config files.
development.rb
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
# Do not eager load code on boot.
config.eager_load = false
# Show full error reports.
config.consider_all_requests_local = true
# Enable/disable caching. By default caching is disabled.
if Rails.root.join('tmp/caching-dev.txt').exist?
config.action_controller.perform_caching = true
config.cache_store = :memory_store
config.public_file_server.headers = {
'Cache-Control' => 'public, max-age=172800'
}
else
config.action_controller.perform_caching = false
config.cache_store = :null_store
end
# Don't care if the mailer can't send.
config.action_mailer.raise_delivery_errors = false
config.action_mailer.perform_caching = false
# Print deprecation notices to the Rails logger.
config.active_support.deprecation = :log
# Raise an error on page load if there are pending migrations.
config.active_record.migration_error = :page_load
# Debug mode disables concatenation and preprocessing of assets.
# This option may cause significant delays in view rendering with a large
# number of complex assets.
config.assets.debug = true
# Suppress logger output for asset requests.
config.assets.quiet = true
# Raises error for missing translations
# config.action_view.raise_on_missing_translations = true
# Use an evented file watcher to asynchronously detect changes in source code,
# routes, locales, etc. This feature depends on the listen gem.
config.file_watcher = ActiveSupport::EventedFileUpdateChecker
# Don't actually send emails
config.action_mailer.delivery_method = :test
# Alternate configuration example using gmail
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
address: "smtp.gmail.com",
port: 587,
domain: "domain.of.sender.net",
authentication: "plain",
user_name: "dave",
password: "secret",
enable_starttls_auto: true
}
end
production.rb
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both threaded web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present?
# Compress JavaScripts and CSS.
config.assets.js_compressor = :uglifier
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = 'http://ift.tt/rzONfP'
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX
# Mount Action Cable outside main process or domain
# config.action_cable.mount_path = nil
# config.action_cable.url = 'wss://example.com/cable'
# config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ]
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# Use the lowest log level to ensure availability of diagnostic information
# when problems arise.
config.log_level = :debug
# Prepend all log lines with the following tags.
config.log_tags = [ :request_id ]
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Use a real queuing backend for Active Job (and separate queues per environment)
# config.active_job.queue_adapter = :resque
# config.active_job.queue_name_prefix = "depot_#{Rails.env}"
config.action_mailer.perform_caching = false
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation cannot be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
# Use a different logger for distributed setups.
# require 'syslog/logger'
# config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name')
if ENV["RAILS_LOG_TO_STDOUT"].present?
logger = ActiveSupport::Logger.new(STDOUT)
logger.formatter = config.log_formatter
config.logger = ActiveSupport::TaggedLogging.new(logger)
end
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
end
test.rb
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# The test environment is used exclusively to run your application's
# test suite. You never need to work with it otherwise. Remember that
# your test database is "scratch space" for the test suite and is wiped
# and recreated between test runs. Don't rely on the data there!
config.cache_classes = true
# Do not eager load code on boot. This avoids loading your whole application
# just for the purpose of running a single test. If you are using a tool that
# preloads Rails for running tests, you may have to set it to true.
config.eager_load = false
# Configure public file server for tests with Cache-Control for performance.
config.public_file_server.enabled = true
config.public_file_server.headers = {
'Cache-Control' => 'public, max-age=3600'
}
# Show full error reports and disable caching.
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Raise exceptions instead of rendering exception templates.
config.action_dispatch.show_exceptions = false
# Disable request forgery protection in test environment.
config.action_controller.allow_forgery_protection = false
config.action_mailer.perform_caching = false
# Tell Action Mailer not to deliver emails to the real world.
# The :test delivery method accumulates sent emails in the
# ActionMailer::Base.deliveries array.
config.action_mailer.delivery_method = :test
# Print deprecation notices to the stderr.
config.active_support.deprecation = :stderr
# Raises error for missing translations
# config.action_view.raise_on_missing_translations = true
end
Any advice would be appreciated!!
We have a large website with express and the whole application is written in Node.JS.
When the mongo db is down our app starts hanging when you refresh the browser on home page and also in other page. This is caused because of the behaviour of the mongoose library when the mongo database goes down. the app is served from ubuntu 14.04 machines.
My question is how to test application "hangs".
What kind of tests should I perform to know that i don't have any more web app hangs. The problem is that a hang can be caused by multiple reasons and not just by the mongoose issue which i have fixed.
How can I test that? What kind of tools and techniques are recommended?
I am working in a integration test, seems to work fine until it has to render the freemarker view.
Freemarker cannot find the taglibs and other defined stuff throwing this error:
FreeMarker template error:
No mapping defined for http://ift.tt/2hwDoah
The failing instruction (FTL stack trace):
----------
==> #assign ui = JspTaglibs
And the same with other JspTagLibs...
Also, there are some rewrites (made in a xml loaded at the web.xml) that I need to be loaded (now I hit those urls that it rewrites and I get a 404 status)
I checked that I can load the xml by adding this tag
@ContextConfiguration("file:src/main/webapp/WEB-INF/web.xml")
But when I try to do it cannot recognise come tags (like ) and stuff like this
Configuration problem: Unable to locate Spring NamespaceHandler for XML schema namespace [http://ift.tt/nSRXKP]
Is there any way I can load the whole context for a real integration test and use mockMvc? or any idea how to enable the tagLib loading?
Thanks.
This is a web-based application created by IBM that visualizes the performance of your code.
https://www.youtube.com/watch?v=1eLMurepPPg
Would you find this useful? If so, why? If no, why not?
What would make this product more useful? Please specify if you are a developer or tester.
I am trying to test the thrown of an error inside a generator function as follow, using Jest and Chai:
// function
function * gen () {
yield put({ type: TIME_OUT_LOGOUT })
throw new Error('User has logged out')
}
//test
let genFunc = gen()
expect(genFunc().next).to.deep.equal(put({ type: TIME_OUT_LOGOUT }))
expect(genFunc().next).to.throw(Error('User has logged out'));
But it isn't working. Which would be the correct way to test this?
I'm using Fitnesses for tests i have the same configuration on server but my test passed locally but when i run on server it failed I use java 1.7 + version of fitnesses 20160506 can anyone help me thank you
Is there a way in mochajs to list all tests collected by test runner without executing them?
E.g. if the are specs that look like:
describe('First', function() {
it('should test something', function() {
...
})
});
describe('Second', function() {
it('should test something else', function() {
...
})
});
then I want to get console output similar to an output produced by test reporters, but without executing actual tests, like this:
First
should test something
Second
should test something else
Using webpack, is a more streamlined development testing workflow possible?
I've been using webpack for a little while now, but I've never used any front end testing frameworks, so would like to start integrating them into my development. From what I understand from the tutorials I've seen so far, there needs to be two separate processes:
Each of these appear to run in their own process (eg localhost:3000/localhost:8080), which means manually firing them both separately - the former which is required for the developer to work and the latter (the testing process) which the developer should do to run the tests.
Is there a way to integrate the testing process into the development workflow more? What I'd like is for tests to be run in the same process that the dev HMR build process runs in. It will run the tests that have been affected by the code that has been changed only and output any failing items to the browser (in the same way ESLint does).
Is this possible?
I am looking for seperate tool for testdata generator if any.. For example in TOSCA automation tool, we have Testcase design module, where we can create set of testdata and having an option to create linear expansion for all combination of data for the testcase
Recorded an UI Test in Xcode 8.1, it runs perfectly for the first time but when I run multiple times it do not detect UI element. Reason showed is either
"Multiple Matches found" or "No Matches Found"
I tried using "debug description" and "Accessibility Inspector" for checking hierarchy but it is of no use.
Logs are saying "Using Cached Hierarchy", does that causing error?
As I am new to UI Testing, Please Help..
Thank You!
I'm trying to test my angular 1 (using typescript) modules, and I'm having issues with the dependencies:
These are my modules:
app.module.ts
export const appModule: IModule = angular.module('app', [
'ui.router',
'ngMaterial',
'ngMessages',
'ngAnimate',
'angularMoment',
'ngMap',
sharedModule.name,
componentsModule.name
]);
shared.module.ts
export const sharedModule: IModule = angular.module('app.shared', [
'ui.router',
'ngMaterial',
'ngMessages',
'ngAnimate',
'angularMoment',
'ngMap'
]);
but when testing I get the error on all my tests, however my project runs just fine in the browser. So only the tests can't find the dependency throw erros like this:
Uncaught Error: [$injector:modulerr] Failed to instantiate module app.shared due to:
Error: [$injector:modulerr] Failed to instantiate module ui.router due to:
Error: [$injector:nomod] Module 'ui.router' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.
but when i set my shared module to:
export const sharedModule: IModule = angular.module('app.shared', []);
then it errors only on the tests that use external services, e.g.:
Error: [$injector:unpr] Unknown provider: $stateProvider <- $state
the test is as follows:
describe('component: bookmark', () => {
let parentScope: any;
let element: any;
beforeEach(angular.mock.module(sharedModule.name));
beforeEach(inject(($compile: ng.ICompileService, $rootScope: ng.IRootScopeService) => {
parentScope = $rootScope.$new();
element = angular.element(`<bookmark></bookmark>`);
$compile(element)(parentScope);
parentScope.$digest();
}));
it('should display a star', () => {
const someAttrValue: string = findIn(element, 'md-icon').text();
console.debug('found ', someAttrValue);
expect(someAttrValue).toEqual('star');
});
});
and my bookmark
requires $state
any clue what I might be doing wrong?
I have two piece of codes which both using pika , one for doing a task as a worker (I call it worker code) and one for creating a message in queue containing a task( I call it run_async code) and I want to make my codes testable .
this is my run_async code :
def run_async(function, args=None, kwargs=None):
import json
import pika
from django.conf import settings
from poseidon_async import default_settings
from poseidon_async._utils import _getattr_multiple # NOQA
body = json.dumps(
{
"function": function,
"parameters": {
"args": args or tuple(),
"kwargs": kwargs or {}
}
}
)
settings_modules = (settings, default_settings)
queue_name = _getattr_multiple("POSEIDON_ASYNC_QUEUE_NAME", settings_modules)
rmq_parameters = _getattr_multiple("POSEIDON_RABBITMQ_CONNECTION_PARAMETERS", settings_modules)
with pika.BlockingConnection(pika.ConnectionParameters(**rmq_parameters)) as connection:
channel = connection.channel()
channel.queue_declare(queue=queue_name, durable=True)
channel.basic_publish(exchange='',
routing_key=queue_name,
body=body,
properties=pika.BasicProperties(
delivery_mode=2,
))
return None
and this is my worker code :
def worker(queue_to_read, logger_name=None, result_log_level=None, connection_parameters=None):
import pika
import json
from django.utils.module_loading import import_string
from logging import getLogger
import logging
import traceback
if connection_parameters is None:
raise ValueError("connection_parameters must contains a dictionary of rabbitmq connection parameters")
connection = pika.BlockingConnection(pika.ConnectionParameters(**connection_parameters))
channel = connection.channel()
channel.queue_declare(queue=queue_to_read, durable=True)
def log_error(exception, body):
if logger_name is not None:
log_message = "{}: {} happened during running task\nBody is :\n{}\ntracback :\n{}".format(
type(exception),
str(exception),
body,
traceback.format_exc()
)
getLogger(logger_name).error(log_message)
def log_result(function, result):
if logger_name is not None:
log_message = "{} -> {} ".format(
function,
result
)
_result_log_level = result_log_level or logging.DEBUG
getLogger(logger_name).log(_result_log_level, log_message)
pass
def callback(ch, method, properties, body):
try:
body = json.loads(body.decode('utf8'))
function_dot_path, parameters = body['function'], body['parameters']
args, kwargs = parameters['args'], parameters['kwargs']
function = import_string(function_dot_path)
if callable(function):
result = function(*args, **kwargs)
log_result(function_dot_path, result)
else:
raise ValueError("{} is not callable".format(function_dot_path))
except Exception as exp:
log_error(exp, body)
ch.basic_ack(delivery_tag=method.delivery_tag)
channel.basic_qos(prefetch_count=1)
channel.basic_consume(callback, queue=queue_to_read)
channel.start_consuming()
I know I should mock my pika connection but how ?
Android version: 4.1 .
I want to test my apk without pc, so i write android apk to do it.
Process proc = Runtime.getRuntime().exec(command);
try {
if (proc.waitFor() != 0) {
System.err.println("exit value = " + proc.exitValue());
// proc.waitFor();
}
BufferedReader in = new BufferedReader(new InputStreamReader(
proc.getInputStream()));
StringBuffer stringBuffer = new StringBuffer();
String line = null;
while ((line = in.readLine()) != null) {
stringBuffer.append(line+"\n");
}
// proc.waitFor();
System.out.println(stringBuffer.toString());
Log.i("info",stringBuffer.toString());
return stringBuffer.toString();
} catch (InterruptedException e) {
System.err.println(e);
}
and the command is
am instrument -w -e deleteCase no http://ift.tt/2iHryfo
but it's not worked.
Laura Yeiser Bloom "Thank you! You're right about not being overwhelmed!
Just following your smoothie prep advice has helped my morning routine.
Ifs so easy to prep seven bags at a time and freeze." 2016-06-29T04:21:26+00:00 "Thank you! You're right about not being overwhelmed! Just following your smoothie prep advice has helped my morning routine. Ifs so easy to prep seven bags at a time and freeze." http://ift.tt/2hrcCgj
Google Structured Data Testing Tool error
hreview 1 ERROR 0 WARNINGS
@type hreview
dtreviewed 2016-06-29T04:21:26+00:00
permalink http://ift.tt/2hrcCgj
reviewer
@type hcard The review has no reviewed item specified.
I have a basic knowledge in Schema but I can't seem to figure out this GSDTT error. Ive been finding the solution but Im still stuck. I need help with this "The review has no reviewed item specified." error. thanks
I have an object and some variables that are currently being declared in each individual test that I write (not DRY at all). What I would like to do is create this object and variables in the module's setup method so that all the tests can have access to the object and variables.
This is how I have currently attempted this:
QUnit.module("Main Function Test", {
setup: function() {
this.controls = {
validCharacters : /^[0-9a-zA-Z]+$/
,
searchResultTable : {
setVisible : setVisible
},
commentBoxContainer: {
setVisible : setVisible
}
};
var getValue = sinon.stub().returns(false);
var setEnabled = sinon.spy();
},
});
QUnit.test("someTest that should have access to the above 'controls' object and variables" ...
When I run my tests they fail because the controls object is undefined or it can't find the variables (getValue or setEnabled).
Can someone please share what I'm doing wrong? Or the correct way to make objects and variables available to all tests within a respective module?
I am using devise_auth_token to authenticate users for an API. I would like to authenticate users before each test is run, but keep getting a 401 error. When I use postman to the endpoint with the correct headers, it works, but fails to work during tests.
before(:each) do
@user = FactoryGirl.create(:user)
end
def get_auth
headers = @user.create_new_auth_token
auth = Hash.new
auth["client"] = headers["client"]
auth["access-token"] = headers["access-token"]
auth["uid"] = headers["uid"]
auth["expiry"] = headers["expiry"]
return auth
end
it "auth user should return success" do
get 'get_tasks_for_user', params: {uid: @user.uid}, headers: get_auth
expect(response).to have_http_status(200)
end
RSpec
TasksController auth user should return success
Failure/Error: expect(response).to have_http_status 200
expected the response to have status code 200 but it was 401
Using Visual Studio 2015 Community. I have a unit test project with all these methods named "Step01_AddUser", "Step02_AddHomework", etc. However I'd like to give them descriptive names which will appear in the Test Explorer window. Basically I want to accomplish 2 things:
Is there a way to do this?
I recently found out that JUnit > 4.10 allows the usage of @Rule
and ExpectedException
. Since I'm not big on duplicating code I tried the following. For a better understanding I scaled it down from several tests to just these two. The MockitoJUnitRunner
is intentional although it's not used in the small scaled example.
pom.xml
<dependencies>
<!-- Test dependencies -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>1.10.19</version>
<scope>test</scope>
</dependency>
</dependencies>
TestBase
@RunWith(MockitoJUnitRunner.class)
public class TestBase {
/** JUnit > 4.10 allows expected exception handling like this */
@Rule
public ExpectedException exception = ExpectedException.none();
@Before
public void setup() {
this.expectBadParam();
}
protected void expectBadParam() {
this.exception.expect(NullPointerException.class);
}
}
The problem is that the following test is not working as I would expect it to. What I'm trying is by default expect an exception type and in some cases run a normal JUnit test. I can't reset the expected exception once it's set.
public class ExpectedExceptionTest extends TestBase {
@Test
public void error() {
throw new NullPointerException();
}
@Test
public void success() {
this.exception = ExpectedException.none();
// this should be a success
}
}
I already found a different solution by duplicating the expectBadParam method in each method I expect an exception. However I'm hoping someone can help me understand why this is not working?
I want to validate that an url returns 404 Not found. How can I do that? This doesn't work:
it "404" do
get "/some_url_404"
expect(response.status).to eq 404
end
The test itself fails with:
ActionController::RoutingError: No route matches [GET] "/some_url_404"
Suppose we have a module that defines an abstract type T:
module AbstractType (T, lexer) where
data T = T String deriving Show
lexer = (fmap T) . words
(Note that we do not export any type constructors for T, so the user would not be able to draft an instance by hand.)
How does one unit test lexer
function?
Sure we may use the Show property of T, like this:
module Main where
import AbstractType
main = test
(show $ lexer "summer is miles and miles away")
"[T \"summer\",T \"is\",T \"miles\",T \"and\",T \"miles\",T \"away\"]"
test :: (Eq a) => a -> a -> IO ()
test expression expectation
| expression == expectation = putStrLn "Test passed."
| otherwise = error "Test failed."
— But this is both not beautiful and unfit for cases when our abstract type is not an instance of a class that permits casting to another, constructable type.
Is there a remedy?
What is the best approach under linux to compile natively and unit test a device driver that for example writes to arbitrary memory locations when it talks to the hardware?
The approach I have tried so far is to just mmap the memory (even address 0x0 works) and just monitor it using a separate thread for changes. This works as far as building the driver natively and having it write to what it thinks is io memory. However I'm not quite sure how to go about doing synchronization between my hardware simulator thread that responds to the memory changes and the device driver. My approach so far is kindof nondeterministic.
I would prefer a solution that runs natively and enables me to test how the driver interacts with hardware by using another thread that can simulate various hardware faults.
What other options do I have?
I want to execute java class from J Meter in my maven project. There are several maven project in my application. I have also tried with simple demo to execute it using J meter its working fine, however when I tried to execute my maven project class using J meter I am enable to execute it properly. Can anyone please suggest me how to call / execute any maven project class using the J meter. Thanks in advance for your reply.
I am trying to create a basic test file using gtest but I am getting the error : testvs\debug\testvs.exe is not recognized as an internal or external command, operable program or batch file.
test.cpp
#include <gtest\gtest.h>
#include <iostream>
using namespace std;
TEST(test_case,simple_case)
{
int i=0;
int b=1;
int result= i*b;
int expected=0;
EXPECT_EQ(result,expected);
}
main.cpp
#include <gtest\gtest.h>
#include <iostream>
using namespace std;
void main(int argc, char* argv[])
{
::testing::InitGoogleTest(&argc,argv);
RUN_ALL_TESTS();
}
when I comment out the lines
TEST(test_case,simple_case)
{
int i=0;
int b=1;
int result= i*b;
int expected=0;
EXPECT_EQ(result,expected);
}
and
::testing::InitGoogleTest(&argc,argv);
RUN_ALL_TESTS();
it does not give any error. Please help
have a problem testing yeoman generator.
This is my app,js file for testing. When i just pass 'package.json' in assert.file() it works and pass the test
var path = require('path');
var assert = require('yeoman-assert');
var helpers = require('yeoman-test');
describe('generator:app', function(){
before(function(){
helpers.run(path.join(__dirname, '../generators/app/src'))
.toPromise();
});
it('creates files', function(){
assert.file([
'package.json'
])
})
})
The coverage is:
------------|----------|----------|----------|----------|----------------|
File | % Stmts | % Branch | % Funcs | % Lines |Uncovered Lines |
------------|----------|----------|----------|----------|----------------|
app\ | 0 | 100 | 0 | 0 | |
index.js | 0 | 100 | 0 | 0 |... 18,22,26,30 |
------------|----------|----------|----------|----------|----------------|
All files | 0 | 100 | 0 | 0 | |
------------|----------|----------|----------|----------|----------------|
But the problem comes when i pass a second file. When i pass 'index.html' or another path (whatever path) it brokes.
AssertionError: index.html, no such file or directory
+ expected - actual
-false
+true
at node_modules\yeoman-assert\index.js:46:12
at Array.forEach (native)
at Function.assert.file (node_modules\yeoman-assert\index.js:44:8)
at Context.<anonymous> (test\app.js:13:12)
And here is something that i don't understant. What is the right file path that i have to pass to assert.file([]).
My writing method for my app generator looks like:
writing(){
this.fs.copyTpl(
this.templatePath('_package.json'),
this.destinationPath('package.json'), {
appName: this.appName,
appDescription: this.appDescription,
authorName: this.authorName
}
);
this.fs.copy(
this.templatePath('config/'),
this.destinationRoot()
);
this.fs.copy(
this.templatePath('src/'),
this.destinationPath('src/')
);
that.fs.copyTpl(
that.templatePath('_index.html'),
that.destinationPath('src/index.html'),
{
appName: _.startCase(that.appName),
}
);
this.fs.copy(
this.templatePath('app/'),
this.destinationPath('src/app')
);
}
I wish somebody can help me. Thank you in advance!
Hi guys I am trying to write a test for my meteor method. So I created a file accountsMethods.js in the server folder
import { Meteor } from 'meteor/meteor'
Meteor.methods({
'createUser': function (email, password) {
var userObject = {
email,
password
}
Accounts.createUser(userObject)
}
})
And accountsMethods.tests.js
import { Meteor } from 'meteor/meteor'
import { resetDatabase } from 'meteor/xolvio:cleaner'
import { Random } from 'meteor/random'
import should from 'should'
describe('accountsMethods', function () {
beforeEach(function () {
resetDatabase()
})
it('Creates User', function () {
const createUser = Meteor.server.method_handlers['createUser']
const email = 'test@example.com'
const password = '12345'
const userId = Random.id()
createUser.apply({ userId }, [email, password])
should(Meteor.users.find({}).count()).be.exactly(1)
})
})
In the tests I have the following error but I am not sure what this is about.
Error: Match error: Expected object, got string
at exports.check (packages/check.js:57:15)
at packages/accounts-password/password_server.js:1033:7
at tryLoginMethod (packages/accounts-base/accounts_server.js:248:14)
at AccountsServer.Ap._loginMethod (packages/accounts-base/accounts_server.js:381:5)
at Object.createUser (packages/accounts-password/password_server.js:1026:19)
at Test.<anonymous> (server/accountsMethods.tests.js:15:16)
at run (packages/practicalmeteor:mocha-core/server.js:34:29)
at Context.wrappedFunction (packages/practicalmeteor:mocha-core/server.js:63:33)
// 11
var createUser = Meteor.server.method_handlers['createUser']; // 12
var email = 'test@example.com'; // 13
var password = '12345'; // 14
var userId = Random.id(); // 15
createUser.apply({ userId: userId }, [email, password]); // 16
should(Meteor.users.find({}).count()).be.exactly(1); // 17
I'm working now on my first bot with Microsoft Bot Framework, with asp.net.
After manually testing with the bot emulator, I'm looking for the best method to create automatic testing for the bot.
Considering two problems:
Does someone have experience in such tests?
Can someone advise testing tool which emulates touch screen laptops fully? Something like BrowserStack or CrossBrowserTesting. I know about chrome toggle device toolbar but it's not covering all areas.
Thanks in advance!
I want to do some reading tests on my system for a project, because I want to know if it is better to read() or subscribe() to several variables. These tests I will do with python. I am measuring the time it takes to read different amounts of variables and I would also like to measure memory consumption. I currently measure start time, end time and subtract. How could you measure cpu and memory consumption?
def ReadTest(cantidad=100, repeticiones=10, tiempo=0):
"""
@param cantidad; integer: numero de marcas que vamos inicio leer
@oaram repeticiones; integer: numero de repeticiones que queremos que haga nuestro programa.
@param tiempo; float: tiempo que pasara hasta que se repita la lectura de datos.
"""
info= "numero de variables %d, numero de repeticiones %d, tiempo de espera %d" %(cantidad, repeticiones, tiempo)
print info
tiempos=[]
media=0
tiempos.append(info)
aux=0
while(repeticiones > aux):
inicio=time.time()
for i in xrange(cantidad):
val=jh.Get("\\PLC\\memory\\m\\" + str(i)).values()[0]
final=time.time()
time.sleep(tiempo)
aux+=1
t=final-inicio
tupla=(t,cantidad)
tiempos.append(tupla)
media+=t
tupla=(media/repeticiones,"media")
tiempos.append(tupla)
return tiempos
tiempos=ReadTest()
write_file(tiempos)
tiempos=ReadTest(cantidad=500,repeticiones=10,tiempo=2)
write_file(tiempos)
tiempos=ReadTest(cantidad=1000,repeticiones=10,tiempo=2)
write_file(tiempos)
tiempos=ReadTest(cantidad=2000,repeticiones=10,tiempo=2)
write_file(tiempos)
I'm really stuck here. I have a Language
model, that gets updated in this method:
def update
@language = Language.find(params[:id])
if @language.update_attributes(language_params)
flash[:success] = 'Language information updated.'
redirect_to @language
else
@skill_errors = @language.errors
render 'edit'
end
end
The intended behaviour for a successful update reproduces when I run it on my local server, object gets updated, flash appears and redirect to @language
happens.
In the test, however, I only get the 200: Success
response, and the object doesn't get updated. Here's the test code:
test 'should allow update when logged in as admin user' do
sign_in(@admin)
patch language_path(@ruby_language), params: { language: { name: 'Test'} }
assert_not flash.empty?
assert_redirected_to @ruby_language
@ruby_language.reload
assert_equal 'Test', @ruby_language.name
end
@admin_user
and @ruby_language
are defined in fixtures. All the asserts in this test fail, including the last one, with reload
. My guess is that there might be some routing glitch caused by my usage of Devise
and/or Kaminari
gems? On the other hand, my Language
routes are very simple: resources :languages, concerns: :paginatable
(the concern is here for human-readable URL formatting). Please, keep in mind that everything works as intended, only tests fail for some reason... Thanks in advance!
Can someone advise site testing tool which includes touch screen laptops ? Something like BrowserStack or CrossBrowserTesting. I know about chrome toggle device toolbar but it's not covering all areas.
Thanks in advance!
I have a problem that seems to have no solution that I can find.
I have a react component that uses jquery to change the classes of some DOM nodes based on a click event, like so (simplified version):
hide() {
if ($('.hidecontrols').hasClass('fa-arrow-left')) {
//hide UI
$('.hidecontrols').removeClass('fa-arrow-left');
$('.hidecontrols').addClass('fa-arrow-right');
} else {
//show UI
$('.hidecontrols').removeClass('fa-arrow-right');
$('.hidecontrols').addClass('fa-arrow-left');
}
}
render() {
return (
<div>
<i onClick={this.hide} className="hidecontrols fa fa-2x fa-arrow-left" aria-hidden="true"/>
</div>
);
}
The code works fine when I test it in a browser. When I run Karma with this test:
it('should HIDE when the hide-arrow is clicked', () => {
var store = configure({});
var provider = ReactTestUtils.renderIntoDocument(
<Provider store={store}><Controls/></Provider>
);
var controls = ReactTestUtils.scryRenderedComponentsWithType(provider, Controls)[0];
var hideArrow = ReactTestUtils.scryRenderedDOMComponentsWithClass(controls, 'fa-arrow-left')[0];
ReactTestUtils
.Simulate
.click(hideArrow);
var unHideArrow = ReactTestUtils.scryRenderedDOMComponentsWithClass(controls, 'fa-arrow-right')[0];
expect(unHideArrow).toExist();
});
the test fails. this.hide() IS called on the simulated click, but the
if($('.hidecontrols').hasClass('fa-arrow-left'))
failed because jquery cannot see any of the elements rendered by renderIntoDocument.
Long story short, jquery is being called on the global context of Karma's browser (I'm using chrome, not that it matters) and not in whatver context my React component has been rendered.
Any ideas how to get jquery to be called in the correct context so it can actually see the nodes it's supposed to select? Nothing I've found from searching seems to deal with this problem.
In my Elixir/Phoenix app, when I run
mix test
I get output like:
$ mix test
....
Finished in 0.09 seconds
4 tests, 0 failures
with dots for each test that succeeded.
How do I output the names of the tests that succeed instead?
In Rails with rspec I used to do this with a .rspec file in the directory that looked like:
$ cat .rspec
--color
-fd
--tty
Is there an equivalent in Elixir?
This is purely a test. This is purely a test. This is purely a test. This is purely a test. This is purely a test. This is purely a test. This is purely a test. This is purely a test. This is purely a test. This is purely a test. This is purely a test. This is purely a test. This is purely a test. This is purely a test. This is purely a test. This is purely a test. This is purely a test. This is purely a test. This is purely a test.
I have build a WebAPI and apart from my tests running on Postman I would like to implement some Integration/Unit tests.
Now my business logic is very thin, most of the time its more of CRUD actions, therefore I wanted to start with testing my Controllers.
I have a basic setup. Repository pattern (interfaces), Services (business logic) and Controllers. The flow goes Controller (DI Service) -> Service (DI Repo) -> Repo Action!
So what I did was override my Startup file to change into a in memory database and the rest should be fine (I would assume) Services are added, repos are added and now I am pointing into a in memory DB which is fine for my basic testing.
namespace API.UnitTests
{
public class TestStartup : Startup
{
public TestStartup(IHostingEnvironment env)
: base(env)
{
}
public void ConfigureTestServices(IServiceCollection services)
{
base.ConfigureServices(services);
//services.Replace<IService, IMockedService>();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
base.Configure(app, env, loggerFactory);
}
public override void SetUpDataBase(IServiceCollection services)
{
var connectionStringBuilder = new SqliteConnectionStringBuilder { DataSource = ":memory:" };
var connectionString = connectionStringBuilder.ToString();
var connection = new SqliteConnection(connectionString);
services
.AddEntityFrameworkSqlite()
.AddDbContext<ApplicationDbContext>(
options => options.UseSqlite(connection)
);
}
}
}
I wrote my first test, but the DatasourceService is not there:
The following constructor parameters did not have matching fixture data: DatasourceService datasourceService
namespace API.UnitTests
{
public class DatasourceControllerTest
{
private readonly DatasourceService _datasourceService;
public DatasourceControllerTest(DatasourceService datasourceService)
{
_datasourceService = datasourceService;
}
[Xunit.Theory,
InlineData(1)]
public void GetAll(int companyFk) {
Assert.NotEmpty(_datasourceService.GetAll(companyFk));
}
}
}
What am I missing?
I am looking for a software that can provide creating maps with nodes (representing components of the system), but also provide calculations between nodes.
Reason for this is that I am making a map of components of my system and I want to assign coverage to each one of them. E.g. when I change coverage on one of them, coverage on the rest of the components are updated automatically.
Example: AverageScoreCalculation
Thank you.
I've multiple packages with absolutely independent pieces of java code. Some packages contain tests that run 5-6 second to complete. Right now, my tests execute sequentially which takes a lot of time to complete all tests in the whole project. However, I quite sure that it's possible to execute tests in package#1/package#2/package#3/.../package#10 simultaneously.
What should I do in order that all my tests from different packages execute at the same time ( without waiting for completion of each other )?
I'm very new to tests. I have a webapp that stores books and informations about books.
If i call my route /store/
it trigger my store
methods and creating a new book into my database. This are the simplified methods:
Book.php
class file:
public function __construct() {
$this->bookService = new BookService();
}
public function store() {
$input = /* get post input values */
$this->createDatabaseEntry($input);
}
private function createDatabaseEntry($input) {
// Creating database entry
$book = /* bla bla */
$languages = $this->bookService->fetchLanguages($book->goodreads_id);
// And here i loop over the $languages and store them all in a extra table.
}
And here i have an other Service class BookService.php
:
public function fetchLanguages($goodreads_id) {
// Here i make an guzzle http call to a other service from goodreads.com
}
How do i test this without making a http request to goodreads? I need to verify the languages are in the database. I can work with fixtures for fetchLanguages()
. But how can i stub/mock (i don't know the correct term) this function?
I using Laravel and PHPUnit.
I want to test the functionality of logistic base project. My expectation is to automatically execute test when some commit code in SVN. Some one can help me to suggest that which one is best Jenkins or JMeter.
I need some Test cases on Rating Engine Module in Business Support System(BSS) in Telecom Domain.
I am testing a feature in which an OTP/Text message should be received on the phone number I enter in the api request.
I would like to test it with different phone numbers- preferably Scandinavian countries.
From where I can get dummy phone numbers, where I can check the received message as well.
I found one site: http://ift.tt/2hJqbbQ (my message shows delivered but i cant see it in the list here)
Also If someone can share use cases/test cases/test scenarios that I can test, would be highly appreciated and helpful.
Regards
I have few devices like samsung galaxy S5, LG G4 and IPhone 6s. I am testing my website using these devices. But I want to test my website in all other devices also. But it is not possible to get all devices physically, so is any other option through online can we get this options like devices and OS to test my website. And also it have to support accessibility Testing also. in browserstack also I tried but not worked.
Please help.
I have this if else statement and i want to write a J unit test that will test each individual line to see is correct. Any ideas?
public class Testings {
public static int computeValue(int x, int y, int z)
{
int value = 0;
if ( x == y )
value = x + 1;
else if (( x > y) && ( z == 0))
value = y + 2;
else
value = z;
return value;
}
}
I have two integration tests
[TestFixture]
public class SimpleTests
{
...
}
[TestFixture]
public class HighLoadTests
{
...
}
And i use Throtle in my API. If HighLoadTests
run previously then all SimpleTests
is red. Is there anyway to allways run HighLoadTests
last?
Hello any one can you please share sample project with me. I can able write script but I can not able manage code in java. Suggest me any best way any website
I work in the financial industry and the FSM framework I'm referring to is for an Order Management System. It is written using Java, Spring and the rules / transitions are configured in the database.
The current tests are written using JUnit, run using Spring JUnit runner and they cover only the result states at the end of each transition.
For e.g. if an order is Modified / Amended, the integration flow tests only the final outcome i.e if the order status is now Modified in the database or not.
It doesn't test the data that was entered during the modification process actually got persisted in the database or not. There's no negative testing at all either.
My question is, what sort of test cases should a FSM based framework / application have if the framework also has a responsibility of persisting data, publishing data to the down streams, sending reports to customers etc.
We're using Greenkeeper with Git to help maintain our project. However, every time it pulls it states:
This version is covered by your current version range, but I could not detect automated tests for this project. Without a test suite I can not really tell whether your project still works.
Does this mean we need to implement something like Travis CI or just install something like Mocha? It's a Node project.
Trying to compile build.xml file and receive following error
1. java:3: error: package org.testng.annotations does not exist [javac] import org.testng.annotations.Test; 2. java:7: error: cannot find symbol @Test
I've attached my build.xml file in a comment.
I'm new with protractor and angular JS page.
For my end2end testing I need validated if my canvas has been received at least one image (There's a websocket.io thats populate some images in this canvas).
For now I should validate just if canvas starts received that images.
My html page:
<div class="terminal-screenshots" ng-class="{ online: isConnected() && vm.hasImage }">
<canvas ng-show="isConnected() && vm.hasImage" style="width: 100%;" id="remoteTerminalCanvas"></canvas>
<span ng-if="!isConnected() || !vm.hasImage">
</span>
</div>
This is my expect:
expect(element(by.id('remoteTerminalCanvas')).isDisplayed()).toBe(true);
But it's return true before the first image show up in the canvas.
Suppose I have this component:
import React, { Component } from 'react';
import { Text, TouchableWithoutFeedback, View } from 'react-native';
class MyComp extends Component {
onRowPress() {
this.myCoolFunction();
}
myCoolFunction() {
console.log('hi');
}
render() {
return (
<TouchableWithoutFeedback onPress={this.onRowPress.bind(this)}>
<View>
<Text>Hello World</Text>
</View>
</TouchableWithoutFeedback>
);
}
}
export default MyComp;
How do I go about simulating 1 click on the 'TouchableWithoutFeedback' and making sure that 'myCoolFunction' was called exactly 1 times?
If it's not a must, then I would prefer to not add more dependencies other than 'react-dom' and 'react-addons-test-utils'.
I saw a lot of guides claiming this and that but I fear they are outdated and I want to be sure that I'm not going through some unneeded workarounds and bloating my code.
I have jest/react/react native in their latest versions.
During tests using mocha, i'm having invocation issue with S3.getObject().
My code in Lambda is like this:
index.js:
S3.getObject(s3FileParams, function(err, data) {
if (err) {
var message = "Error while trying to get file object " + fullFileName + " from bucket " + bucketName + ". Make sure they exist and your bucket is in the same region as this function. Error: " + err;
console.error(message);
}
else {
userMetaDataJson = data.Metadata;
}
resolve();
})
And in the test file index.test.js (using mocha)
AWSMock.mock('S3', 'getObject', function (params, callback){
var metaDataParams = {
"Metadata": {
"startDate": "2016-11-11 12:34:56:000",
"endDate": "2016-11-11 12:34:56:000",
"userName": "userName",
"originalFileName": "originalFileName"
}
};
callback(false, metaDataParams);
});
When running this test with mocha, there is no call to the mocked getObject() and it's calling to the original one, is there anything that I can do ?
Is there any other approach I could use?
I want my app to play sounds via bluetooth headset from Apple Watch using WKAudioFilePlayer
. The problem is that I have no Apple Watch neither bluetooth headset :( Is there a way to test that WKAudioFilePlayer
working correctly? I can check the status
prop. of the player and if it equals to WKAudioFilePlayerStatusReadyToPlay
I can suppose that everything is ok. But I want to hear the sound playing just to be sure.
The code below is used to play a Lottery game.
let Lotto = {
_nMap: [
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50
],
_sMap: [
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12
],
/**
* @param {Array} shuffleArr
*
* @return {Array}
*/
_shuffleArr(shuffleArr) {
let rndNr, tmpValue;
for (let elmNr = shuffleArr.length - 1; elmNr > 0; elmNr--) {
rndNr = Math.floor(
Math.random() * (elmNr + 1)
);
tmpValue = shuffleArr[rndNr];
shuffleArr[rndNr] = shuffleArr[elmNr];
shuffleArr[elmNr] = tmpValue;
}
return shuffleArr;
},
/**
* @return {Object}
*/
getPick() {
return {
n: this._shuffleArr(this._nMap).slice(0, 5),
s: this._shuffleArr(this._sMap).slice(0, 2)
}
}
};
Now I want to verify whether the implementation is correct. For example: it should return a unique set of numbers. How do I test this? Run the .getPick() method once and validate the output or ...?
I have a Python based web scraping pet project that I'm trying to implement some TDD in, but I quickly run into a problem. The unit tests require an internet connection, as well as downloading of html text. While I understand that the actual parsing can be done with a local file, some methods are used to simply redefine the URL and query the website again. This seems to break some of the best practices for TDD (citation: Clean Code by Robert Martin claims that tests should be runnable in any environment). While this is a Python project, I ran into a similar issue using R for Yahoo Finance scraping, and I'm sure this kind of thing is language agnostic. At the very least, this problem seems to violate a major guideline in TDD, which is that the tests should run fast.
tldr; Are there any best practices for handling network connections in TDD?
AbstractScraper.py
from urllib.request import urlopen
from bs4 import BeautifulSoup
class AbstractScraper:
def __init__(self, url):
self.url = url
self.dataDictionary = None
def makeDataDictionary(self):
html = urlopen(self.url)
text = html.read().decode("utf-8")
soup = BeautifulSoup(text, "lxml")
self.dataDictionary = {"html": html, "text": text, "soup": soup}
def writeSoup(self, path):
with open(path, "w") as outfile:
outfile.write(self.dataDictionary["soup"].prettify())
TestAbstractScraper.py
import unittest
from http.client import HTTPResponse
from bs4 import BeautifulSoup
from CrackedScrapeProject.scrape.AbstractScraper import AbstractScraper
from io import StringIO
class TestAbstractScraperMethods(unittest.TestCase):
def setUp(self):
self.scraper = AbstractScraper("http://ift.tt/1f4Af77")
self.scraper.makeDataDictionary()
def test_dataDictionaryContents(self):
self.assertTrue(isinstance(self.scraper.dataDictionary, dict))
self.assertTrue(isinstance(self.scraper.dataDictionary["html"], HTTPResponse))
self.assertTrue(isinstance(self.scraper.dataDictionary["text"], str))
self.assertTrue(isinstance(self.scraper.dataDictionary["soup"], BeautifulSoup))
self.assertSetEqual(set(self.scraper.dataDictionary.keys()), set(["text", "soup", "html"]))
def test_writeSoup(self):
filePath = "C:/users/athompson/desktop/testFile.html"
self.scraper.writeSoup(filePath)
self.writtenData = open(filePath, "r").read()
self.assertEqual(self.writtenData, self.scraper.dataDictionary["soup"].prettify())
if __name__ == '__main__':
suite = unittest.TestLoader().loadTestsFromTestCase(TestAbstractScraperMethods)
unittest.TextTestRunner(verbosity=2).run(suite)
Im looking for some advice for a good test reporter that works with Jenkins. Trouble is my company has some frameworks in Cucumber while others in TestNG for our various applications. I'm looking for something where I can see historic results (preferably 30 days or so) to view trends but having issues finding a nice looking reporter to standardize all 4 of the frameworks. The reports are for upper management and the business so it needs to be easy to read. Any suggestions or am I asking too much?
I'm doing a GUI project. Something like typing speed test. I mean that you see a line of text and you have to rewrite it as fast as you can. I wonder if there's any option to check in real time if entered char is equal to char in displayed text. I want it to check if the letter I just typed is the same as the letter in displayed text, which I was supposed to type in that moment.
Now my code is not running well, because the for loop is not waiting for me to type anything, it is just checking if default String in edittext is equal to the line of test text displayed above it. I want it to check char by char if it is equal.
I also wanted to mark red the letter you have to type now, but I don't know how to do it.
That's part of my code:
function easy_Callback(hObject, eventdata, handles)
fileID = fopen('lol.txt');
tline = fgetl(fileID);
while ischar(tline)
set(handles.textdisp, 'String', tline);
L = length(tline);
w = waitforbuttonpress;
for i = 1 : L
if w == 0;
lineKey = get(handles.keyboard1, 'String');
if strcmp(tline(i), lineKey(i))
i = i+1;
else
disp('error');
end
end
end
tline = fgets(fileID);
end
fclose(fileID);
guidata(hObject, handles);
keyboard1 is edittext in which I rewrite the text above textdisp is a line of text which you have to rewrite
I tried with pause and waitforbuttonpress but it just doesn't work.
I have overridden the @angular/core ErrorHandler and I am trying to test it, however I am getting an error. The service works properly but the test fails somewhere.
exception-handler.service.ts
import { Injectable, ErrorHandler, forwardRef, Inject } from '@angular/core';
import { BkHttp } from './http.service';
@Injectable()
export class BkExceptionHandlerService implements ErrorHandler {
constructor( private bkHttp: BkHttp) { }
handleError(error) {
let originalError = this.controlError(error);
this.sendToConsole(originalError);
this.sendToBitacora( originalError );
throw( error );
}
controlError(error: any): any {
let originalError: Object = this.findOriginalError( error );
return originalError;
}
findOriginalError( error: any ) : any {
while ( error && error.originalError ) {
error = error.originalError;
}
return( error );
}
getPrueba():string {
return 'prueba!!!';
}
sendToConsole(error:any): void {
try {
console.group( 'START ErrorHandler' );
console.error( error );
console.error( error.message );
console.error( error.stack );
console.groupEnd();
} catch (handlingError) {
console.group( 'START ErrorHandler' );
console.warn( 'Error when trying to output error. Pure Irony' );
console.error( handlingError );
console.groupEnd();
}
}
sendToBitacora(error:any): void {
let body: Object = {
name: error.name,
message: error.message,
stack: error.stack,
location: window.location.href
};
this.bkHttp.post('http://google.es', body).subscribe(res => { });
//this.bkHttp.post('http://fgooffglffffe.es', body);
}
}
An here it is the test file
import { Component, DebugElement } from '@angular/core';
import { TestBed, ComponentFixture, async } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { Observable } from 'rxjs';
import { Response, Http } from '@angular/http';
import { BkHttp } from './http.service';
import { BkExceptionHandlerService } from './exception-handler.service';
const ERROR_MESSAGE = 'Dummy Error';
@Component({
selector: 'dummy-component',
template: `<button (click)="throwError()">Throw an error!!!</button>`
})
export class MockComponent {
public throwError(): void {
throw Error(ERROR_MESSAGE);
}
}
describe('FancyService without the TestBed', () => {
let bkExceptionHandlerService: BkExceptionHandlerService;
let bkHttp: BkHttp;
let fixture: ComponentFixture<MockComponent>;
let loggerSpy: jasmine.Spy;
let consoleSpy: jasmine.Spy;
let errorObservableSpy: jasmine.Spy;
let comp: MockComponent;
beforeEach( async(() => {
TestBed.configureTestingModule({
declarations: [ MockComponent ],
})
.compileComponents(); // compile template and css
}));
beforeEach(() => {
bkExceptionHandlerService = new BkExceptionHandlerService(bkHttp);
loggerSpy = spyOn(bkExceptionHandlerService, 'controlError').and.callThrough();
consoleSpy = spyOn(console, 'error');
errorObservableSpy = jasmine.createSpy('log event observable subscription');
fixture = TestBed.createComponent(MockComponent);
comp = fixture.componentInstance;
fixture = TestBed.createComponent(MockComponent);
});
it('should log error to the console', () => {
let elem = fixture.debugElement.query(By.css('button'));
elem.triggerEventHandler('click', null);
expect(loggerSpy).toHaveBeenCalledWith(jasmine.any(Error), ERROR_MESSAGE);
});
});
And finally the error
Error: Error in ./MockComponent class MockComponent - inline template:0:0 caused by: Dummy Error in node_modules/@bankular/development-tools/config/karma-test-shim.js (line 49231)
Could you guys help me?
I'm running swift test
from command line to run the test cases. This is the test case:
import XCTest
@testable import vnk_swift
class KeyMappingTests: XCTestCase {
static var allTests : [(String, (KeyMappingTests) -> () throws -> Void)] {
return [
// ("testExample", testExample),
]
}
func testExample() {
let keyMapping = KeyMapping()
XCTAssertNotNil(keyMapping , "PASS")
}
}
And here is the output message.
If I remove the usage of KeyMapping
, everything works fine:
func testExample() {
// let keyMapping = KeyMapping()
XCTAssertNotNil(true , "PASS")
}
Looks like there is a problem when I'm trying to use a class. How do I fix this?
(I did not use XCode for this project as I started with swift package init
, the source code for this project is here: http://ift.tt/2is4otg)
Can you help me please.
During a test, I did not understand this question :
Given the following code, write two lines of Javascript to call the print() function in a way that prints the Window global object in the Javascript console ? Your code must not use the variable window
. Feel free to comment.
Printer = function(){
this.print = function() {
console.log(this);
}
}
var printer = new Printer();
I'm trying to add tests to my Nodejs project and currently confused about should I use SinonJS?
I think with async handling Chai can does whatever Sinon does.
I usually don't use Guice in small unit tests (1 class tests), but as the unit gets bigger and includes more than a handful of classes it seamed to be a good choice.
The thing is, eventually I saw 2 problems with using it:
Run time
setting up the guice injector takes a long time therefore my tests become longer. I'm currently creating the injector in the setup method to start clean in each test.
I tried moving the injector creation to @BeforeClass and it cuts run time by 3. but now I have to take care of cleaning up after each test since there are some singletons.
Is there any other way to make my tests run faster?
Are there any guidelines for managing test with shared state?
Managing guice modules
since the intention of this test is to test a whole package, I wanted it to be wired like the production version except for some mocks & fakes that I had to inject for testing.
I tried using Modules.override() but ran into some problems. for instance, not being able to override Just-in-time bindings.
So I ended up writing a separate module for the test, which means I have to change it each time I change the wiring in the production code
Any idea how to solve this?
BTW. We are using Guice version 3.0
The Problem:
We have a rather large test codebase. From time to time, instead of executing all the tests, we execute them individually or in packs. But, sometimes, we see the unexpected test failures because of the tests being interconnected, coupled. For example, one test assumes there is some data created by a previous test - running this kind of test individually will fail.
The Question:
Is it possible to automatically detect which Protractor tests are coupled in the project?
Our current idea is to somehow randomize the test execution order or randomly pick up a pack of tests from all the available tests and check if there are no failures. Hence, the other question: is it possible to change/randomize the Protractor test discovery and change the order of test execution?
I'm having a nightmare writing unit tests for meteor. There are too many old, outdated articles and too few clear, relevant pieces of documentation for me to be able to work out what I actually need to do to get this to work.
I'm running in to problem after problem and just really hope someone can show me how they would write a test for one of my methods so I can see what they have done and reverse engineer it for the rest of my methods.
Here's a method I'd like to write a test for:
Meteor.methods({
'client.new':( clientDetails ) => {
check( clientDetails, {
name: String,
numberTeamMembers: String
});
clientDetails.teamMembers = [];
if(!Meteor.userId() || !Roles.userIsInRole(Meteor.userId(), 'administrator')) {
throw new Meteor.Error('500', 'You are not authorised to do this.');
}
if(Clients.findOne({ name: clientDetails.name})) {
throw new Meteor.Error('500', 'This client name already exists!');
};
return Clients.insert(clientDetails);
},
});
So far I've got the below:
import { Meteor } from 'meteor/meteor';
import { expect, be } from 'meteor/practicalmeteor:chai';
import { describe, it, before } from 'meteor/practicalmeteor:mocha';
import { resetDatabase } from 'meteor/xolvio:cleaner';
import { Random } from 'meteor/random';
import { Clients } from '/imports/api/clients/clients.js';
import '/imports/api/clients/server/methods.js';
describe('Client Methods in API', function() {
before(function() {
resetDatabase();
});
it('can create a Client', function(){
let clientName = "Microsoft",
numberTeamMembers = "5",
data = {
name: clientName,
numberTeamMembers: numberTeamMembers
};
let userId = Accounts.createUser({username: "admin", email: "admin@admin.com", password: "password"});
Meteor.users.update({ _id: userId }, { $set: { roles: [ 'administrator' ] }});
let method = Meteor.server.method_handlers['client.new'];
method.apply(userId, [data]);
let client = Clients.findOne();
expect(Clients.find().count()).to.equal(1);
expect(client.name).to.equal(clientName);
expect(client.numberTeamMembers).to.equal(numberTeamMembers);
});
});
The errors the above test throws are firstly it tells me that Meteor.userId can only be invoked in method calls. Use this.userId in publish functions.
which is irrelevant because this is a method I'm testing. Secondly, the method throws the error ('You are not authorised to do this') so either it doesn't recognise the Meteor.userId() or the fact that the user is in the 'administrator' role.
If someone could show me how they would test that method I'd really appreciate it!
Thanks
I have written a complex java program and I want to load test it. How can I go about doing this?
I have tried setting up JMeter but it feels like hell: hard to set up and documentation is hard to follow.
What are my available options?