w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
django-webtest with multiple test client
I haven't tried setting up another instance of DjangoTestApp as you suggest, but I have written complex tests where, after making requests as user A I have then switched to making requests as user B with no issue, in each case passing the user or username in when making the request, e.g. self.app.get('/', user'A') as you have already written. The only part which did not work as expected was when making unauthenticated requests, e.g. self.app.get('/', user=None). This did not work as expected and instead continued to use the user from the request immediately prior to this one. To reset the app state (which should allow you to emulate most workflows with several users in a sequential manner) you can run self.renew_app() which will refresh your app state, effectively logging the current use

Categories : Django

Django Testing MySQLdb in UnitTest / WebTest
As alecxe points out in comments, you can't use MySQLdb connections and cursors with a sqlite3 database. Here was my quick and dirty workaround, which probably isn't suitable for any code you're going to have in production. I replaced my connection string with the sqlite3 equivalent: import sqlite3 db = sqlite3.connect("settings.DATABASES['default']['HOST']") cursor = db.cursor() # No direct equivalent to MySQLdb.cursors.DictCursor cursor.execute("SELECT something FROM sometable WHERE somecondition = 'somevariable';") ...

Categories : Python

How do you skip a unit test in Django?
Python's unittest module has a few decorators: There is plain old @skip: from unittest import skip @skip("Don't want to test") def test_something(): ... If you can't use @skip for some reason, @skipIf should work. Just trick it to always skip with the argument True: @skipIf(True, "I don't want to run this test yet") def test_something(): ... unittest docs Docs on skipping tests If you are looking to simply not run certain test files, the best way is probably to use fab or other tool and run particular tests.

Categories : Django

Create a visual studio WebTest/OrderedTest that runs the same test against different XML data sources
You can create a seniors.webtest that uses seniors.xml and so on, much like you describe. However, the only action in each of these tests is a call of the one main test (use context menu Add call of web test). Effectively the main webtest would be called a subroutine of the others. Expand the Data source part of the calling webtests (for example seniors.webtest) and view the properties of the data source file. The Select columns property should be set to Select all columns and that should make all the columns in the data source available as context parameters in the called web test.

Categories : C#

Django: issue with unit-test ListView and assertContains
The "No polls are available" message is from the template. From part 3 of the tutorial: {% if latest_poll_list %} <ul> {% for poll in latest_poll_list %} <li><a href="/polls/{{ poll.id }}/">{{ poll.question }}</a></li> {% endfor %} </ul> {% else %} <p>No polls are available.</p> {% endif %} You need to update your template rsvp_list.html to include "No persons are available." in a similar way.

Categories : Django

Django test DoesNotExist: Contact matching query does not exist
You shall use setUp method, not setup. This method is called before running every test. class BatchTestCase(TestCase): def setUp(self): # create test objects here # ...

Categories : Python

Python/Django: how to assert that unit test result contains a certain string?
Build a JSON object using json.dumps(). Then compare them using assertEqual(result, your_json_dict) import json expected_dict = {"car":["toyota", "honda"]} expected_dict_json = json.dumps(expected_dict) self.assertEqual(result, expected_dict_json)

Categories : Python

Can't read unit test success rate, can read unit test coverage generated by jacoco
Thanks for Jeanne's answer. I solved it now. As Jeanne said, sonar doesn't support TestNG, it supports JUnit. So I use ReportNG to generated test report in xml format. The report file will be named as com.abc.classTest1.xml. In order to show the Unit Test Success in sonar successfully, we should change it's name to TEST-com.abc.classTest1.xml. Below is my final version of build.xml. <!-- ========= Define the main properties of this project ========= --> <property name="src.dir" value="${basedir}/src" /> <property name="test.dir" value="${basedir}/test" /> <property name="lib.dir" value="${basedir}/lib" /> <property name="build.dir" value="${basedir}/build" /> <property name="classes.dir" value="${build.dir}/classes" /> <property name="dist.dir" va

Categories : Java

Django - Unit Tests on localhost creating objects in main database, but not finding them in the test database later in the method
You should use LiveServerTestCase, so that django can run it's own test server and therefore use it's own test db. https://docs.djangoproject.com/en/1.4/topics/testing/#live-test-server

Categories : Python

SonarQube "Could not find source for unit test: Chrome_280150095_Windows.ButtonTest in any of test directories"
Properties such as "sonar.sources" and "sonar.tests" are not taken into account while triggering the analysis with Maven. See http://docs.codehaus.org/display/SONAR/Analysis+Parameters. Hence your issue regarding source code of tests that is not found. This behavior will eventually changed when the following ticket is implemented: http://jira.codehaus.org/browse/SONAR-4536. Meanwhile, you should use the SonarQube Runner to trigger the analysis.

Categories : Javascript

Unit test fails with NUnit Test Adapter but not with ReSharper in VS2012
I found that in VS2012 similar code would fail at run-time with the same error. If you used this method in an application, would it succeed? You're functionally iterating over a collection and removing items from it while you're still in the collection - this changes the internal indexing of the collection, invalidating the addressing of the iteration. If you'd coded it as: for(int I=0; I < Items.Count, I++) { removeItem(Items[I]); } you'd wind up with an index out of bounds error because the collection's internal indexing resets. I can't speak to ReSharper, but I'd guess that it has a more generous run-time engine than the MS nunit engine (or, for that matter, the MS runtime engine). I was doing something similar in an application where I tried to iterate through the collect

Categories : Unit Testing

Microsoft Fakes & TFS 2012 Visual Studio Test Runner - unit test fail sporadically
I think I know where the issue lies, the TypeNotFoundException was correct, at least the corresponding types were not generated (as shown by Reflector), this made me thinking. More exactly there is only one generated fake-file generated per assembly lying under [buildName]Binaries- and as both of my Assemblies faked the same Assembly (backend.dll) - this resulted most probably in a race condition - the one assembly which was built later than the other had its final shims/stubs generated; this doesn't clarify all problems though. Anyway the reason why this doesn't show up on a regular VS build is because the assemblies are generated in their respective [assembly]FakeAssemblies directory, not influencing any other unit test (the way it is supposed to be). So my idea to circumvent this prob

Categories : Visual Studio 2012

In Refinery CMS, how can I write a simple functional test using Test::Unit?
The section on functional testing from the Rails Engines guide helped me figure this out. This is the get request I needed: get :show, {use_route: :refinery, path: :about} The full test that now passes: require 'test_helper' class PagesControllerTest < ActionController::TestCase tests Refinery::PagesController include Devise::TestHelpers def setup Rails.application.load_seed end test "about us page" do assert_equal "about", Refinery::Page.find_by_slug("about").slug get :show, {use_route: :refinery, path: :about} assert @response.body.include? "About Us" assert_response :success end end

Categories : Ruby On Rails

Add unit test case to test external webservice (.asmx) .NET
As far as I can see, there 2 different functionalists: WSDL provider - i.e. class which gets a valid wsdl from somewhere WSDL parser - the class which parses the wsdl and extracts the data Here is a pseudo-code implementation of these to make them easy to mock and unit test. public interface IWSDLProvider { string GetWsdlFromService(string url); } public class MyWsdlProvider : IWSDLProvider { private readonly IWebWrapper _webCLient; public MyWsdlProvider(IwebWrapper webClient) { _webClient = webCLient; } public string GetWsdlFromService(string url) { //do here whatever is needed with the webClient to get the wsdl } } public interface IWSDLParser { MyServiceData GetServiceDataFromUrl(string url); } public class MyWsdlParser : IWSDLParser {

Categories : C#

Unit test thoroughness - test passing conditions as well as failing ones?
This is a scenario where you want to use one parametrized test which gets all 99 values as input. Using xUnit.net, this could look like this (untested, might contain small compilation errors): [Fact] public void Widget_CannotActiveWidgetIfStateIsCancelled() { // Arrange ... sut.State = State.Cancelled; Assert.False(sut.CanActivate); } [Theory, ValidStatesData] public void Widget_CanActivateWidgetIfStateIsNotCancelled(State state) { // Arrange ... sut.State = state; Assert.True(sut.CanActivate); } private class ValidStatesDataAttribute : DataAttribute { public override IEnumerable<object[]> GetData( MethodInfo methodUnderTest, Type[] parameterTypes) { return Enum.GetValues(typeof(State)) .Cast<State>()

Categories : Unit Testing

Can't seem to get tests running using rake test (Test::Unit)
try this out:- in your test Rakefile update your code to this require 'rake/testtask' Rake::TestTask.new do |t| t.libs << "test" t.test_files = FileList['test/*_test.rb'] t.verbose = true end desc "Run tests" task :default => :test i have myself implemented and tested this in my own gem https://github.com/sachin87/week-of-month/blob/master/Rakefile for adding more parameters to rake task, read it http://rake.rubyforge.org/classes/Rake/TestTask.html

Categories : Ruby

Implementation of Unit test and acceptance test in a .NET project
Many questions... public/private: Typically, you only want to test through the public interface. If you want to test a private method it's probably a sign of that you should split the class into two and let the private methods become public (or internal). SRP. To test internal method, check this answer. When writing a test you want to test the behaviour of the system. With behaviour, think of how the system behaves as seen from the end user (although there could be other interesting stakeholders as well). If you do this, you seldom encounter the problem with wanting to test private methods. The difference between a unit test and an integration test is debated and, in my opinion, not a very important debate. What's more important is to ask yourself, what's the purpose of the test? If yo

Categories : Dotnet

NIO load file in an unit test from src/test/resources
Well, it's a matter of obtaining the correct Path for you test resource in the classpath in your test. EDIT: this is more concise: Paths.get(getClass().getResource("/"+filename).toURI()).toString()

Categories : Java

Whether I am writing the correct test method in Unit Test?
You can use NUnit in several ways. It depends on your code and what your test is all about. In your case yes, comparing totals you would use the AreEqual method. Another common example is if you would like to see if a code generates exceptions or not - maybe to check library updates etc. Something similar to the following might be useful : [TestCase] public void TestCase() { try { // Write you code here that might generate an exception Assert.AreEqual(true, true); } catch (Exception e) { Assert.Fail(e.Message, e.GetType().Name); } } As you can see if the executes successfully I use AreEqual, and comparing true with true so it will exe

Categories : Asp Net Mvc

C++ unit test testing, using template test class
I do not know if there is a way to do this with CppUnitTestFramework, with which I am unfamiliar, but something you can certainly do in googletest is specify an arbitrary list of classes and have the framework generate (template-wise) the same test(s) for all of them. I think that would fit your bill. You can download googletest as source here. The idiom you will want is: typedef ::testing::Types</* List of types to test */> MyTypes; ... TYPED_TEST_CASE(FooTest, MyTypes); ... TYPED_TEST(FooTest, DoesBlah) { /* Here TypeParam is instantiated for each of the types in MyTypes. If there are N types you get N tests. */ // ...test code } TYPED_TEST(FooTest, DoesSomethingElse) { // ...test code } Study the primer and the samples. Then go to the AdvancedGuide f

Categories : C++

Can a unit test perform double-duty by accepting a boolean value as a switch, or should I write two separate tests that duplicate the test code?
I don't like this. Here's why: your test method names should reflect the method under test, what the preconditions of the test are, and what you expect the result of the test to be: public bool AddCustomer_CustomerIsValid_ShouldReturnTrue() public bool AddCustomer_CustomerIsInvalid_ShouldReturnFalse() Now if you want to, you can refactor the core testing logic into its own method to eliminate the code duplication, and then call that method from the two above methods. But the refactored method is not a test case; it's just a helper method for the actual test cases. Example: [Test] public void AddCustomer_CustomerIsValid_ShouldReturnTrue() { var result = AddCustomerTest(true); Assert.IsTrue(result); } [Test] public void AddCustomer_CustomerIsInvalid_ShouldReturnFalse() {

Categories : C#

Subclassing django-registration 1.0 forms for django 1.5 custom user models
Some parts are most definitely not Django 1.5 compatible yet: https://bitbucket.org/ubernostrum/django-registration/src/8f242e35ef7c004e035e54b4bb093c32bf77c29f/registration/forms.py?at=default#cl-48 class RegistrationForm(forms.Form): # ... def clean_username(self): # ... # The line below needs fixing existing = User.objects.filter(username__iexact=self.cleaned_data['username']) if existing.exists(): raise forms.ValidationError(_("A user with that username already exists.")) else: return self.cleaned_data['username'] So unless those methods are changed and/or you subclass them, it won't work yet. For your specific case this registration form should do the trick: from registration import forms as registration_for

Categories : Django

HTML5 form attributes with Django forms and django-bootstrap-toolkit
You can set the value of the widget.attrs to pass certain other HTML attributes to the form. >>> from django import forms >>> name = forms.TextInput(attrs={'size': 10, 'title': 'Your name',}) >>> name.render('name', 'A name') u'<input title="Your name" type="text" name="name" value="A name" size="10" />' -Django Docs

Categories : Django

django make available few of the django admin forms to the users at a different url
When you create a User, you can give different access to any part of your app in the user permission tab. This mechanism should do what you want. If you want to go further and play with the display of your app while keeping something similar to the django admin, you can use the templates of django admin in a view in order to give access to only a part of your model and add more design and custom functions. In this case, I'll suggest you to make a copy of the templates located in djangocontribadmin emplatesadmin and then you can modifiy them as you want.

Categories : Django

Django: How to use django.forms.ModelChoiceField with a Raw SQL query?
Are you sure you actually need a raw query there? Just looking at that query, I can't see any reason you can't just do it with filter(location__city=city_id, available_reserves__gte=0, datetime_from__gt=datetime.datetime.now()). Raw query sets are missing a number of methods that are defined on conventional query sets, so just dropping them in place isn't likely to work without writing your own definitions for all those methods.

Categories : Django

Django django.test.client jquery ready
The Django test client tests the responses generated by the Django server. It doesn't test the JavaScript, as that is run on the client, not the server. You can use Selenium to test the behaviour of the browser. Django has a LiveServerTestCase, which allows you to use the Selenium client. See the docs on LiveServerTestCase for more information.

Categories : Jquery

Is it still possible to use test-unit in rails 4?
Are you subclassing: Test::Unit::TestCase and not ActiveSupport::TestCase? Maybe try adding minitest_tu_shim to your test group: https://github.com/seattlerb/minitest_tu_shim or make sure to subclass ActiveSupport::TestCase

Categories : Ruby On Rails

Unit Testing - What to/not to Test?
The point of unit testing is to test the code that you write. Given that ArgumentNullException is part of an API that you use, testing whether that behaves according to your expectation is testing the API and not your code and would only muddy waters. The unit test you have tests for all behaviors of the method you wrote for the code you wrote and is hence sufficient.

Categories : Unit Testing

Unit Test SQL Procedure
To perform an automated, repeatable unit test would require an environment where you have total control of the data - e.g. a local install of the database on your own PC, or a dedicated database or schema on the server that only you can access. Only then can you do what you would need to do i.e. Run a pre-test script to set up the initial condition for the test, i.e. the exact data it will work on. Run your procedure. Run a script to inspect the data after running the procedure and check that it matches your expectations. Even in a controlled environment you are going to have complications if your data involves dates, since the value of SYSDATE is probably not under your control! There is a mechanism for Unit Tests along these lines built into SQL Developer. Also there is a tool ca

Categories : SQL

C# Unit Test Mocking using Moq.dll
Use It.IsAny<Employee> to setup Save method parameter a.Setup(s => s.Save(It.IsAny<Employee>())).Returns(true).Verifiable(); The reason why your test not working is because you have two different employee instances - one for mock setup, and one which is passed to SaveEmployeeData method call. By default those instances will be compared by reference. Moq waits for Save method call with employee instance, which have reference 13 (e.g). But you are passing another employee with reference 42. Thus setup is never invoked. You have two more options override Equals and GetHashCode methods of Employee class. Thus Moq will compare employees not by reference, but by business data. use exactly same instance of employee both for mock setup and SaveEmployeeData method call (prefera

Categories : C#

How can i unit test an EntitySetController
Came here looking for a solution aswell. This seems to work however not sure if there is a better way. The controller needs a minimum of CreateEntity and GetKey overrides: public class MyController : EntitySetController<MyEntity, int> { protected override MyEntity CreateEntity(MyEntity entity) { return entity; } protected override int GetKey(MyEntity entity) { return entity.Id; } } Where MyEntity is really simple: public class MyEntity { public int Id { get; set; } public string Name { get; set; } } Looks like you need at least: + Request with a URI + 3 keys in the request header, MS_HttpConfiguration, MS_ODataPath and MS_ODataRouteName + A HTTP configuration with a route [TestMethod] public void CanPostToODataController()

Categories : Asp Net

How can I unit test JS that uses a REST API?
First you should put the function passing into the read function into a named function, so you can call it like this $(document).ready(myFunction) Now you call myFunction into your test without the need to mock the $.ready function. The test will look like this: test( sets the iFrameUrl", function() { var server = sinon.fakeServer.create(); server.respondWith('responseUrl'); server.autoRespond = true; $('body').append('iframe') myFunction(); equal($('iframe').attr('src'), 'responseUrl', 'iframe url') })

Categories : Jquery

When to perform my unit test and why use Moq
Let me take a shot. A1: When you refactor existing code, you should execute the corresponding unit tests (not all) and see if anything is broken by your changes. For new functionality you should implement new unit tests in parallel using TDD. You should never execute all the unit tests by your own but should use or rely on continuous integration. A2: I had a same opinion like you. But now, I am convinced that unit testing for service layer is required. Whatever that can be covered using unit testing should be covered. At this point, the core of your services might just be a delegation to repositories but services evolves. The services takes up the responsibility of parameter validation, authorization, logging, transactions, batch-support API etc. Then, it is not only data-access but many

Categories : Unit Testing

How to unit test webrtc app?
i was just about to tell you that it's impossible but then I realized nothing is impossible... https://code.google.com/p/mongoose/ download mongoose web server. serve up your pages locally. use chrome and firefox.. start communication and have fun.. requires one computer, no internet=)

Categories : Unit Testing

Proper use of MOQ in a Unit Test
The way I understand it is that this mock is providing a known result, so when I test this service using it, the service reacts properly? This statement is correct - the unit test should be verifying that the class you're testing (in this case, CustomerService) is exhibiting the behavior you desire. It's not intended to verify that its dependencies are behaving as expected (in this case, IRepository<Customer>). Your test is good* - you're setting up your mock for the IRepository and injecting into your SystemUnderTest, and verifying that the CustomerService.CreateCustomer() function is exhibiting the behavior that you expect. *The overall setup of the test is fine, but I'm not familiar with xUnit, so the final two line's syntax is foreign to me, but it looks like it's corre

Categories : C#

How do I set sys.argv so I can unit test it?
It doesn't work because you're not actually calling get_setup_file. Your code should read: import argparse def test_parse_args(): sys.argv = ["prog", "-f", "/home/fenton/project/setup.py"] setup = get_setup_file() # << You need the parentheses assert setup == "/home/fenton/project/setup.py"

Categories : Python

GWT unit test case
If getModuleName returns null then your test runs just like any other JUnit test, i.e. not in a GWT context. Make getModuleName return the name of your module (the one you pass to the GWT Compiler, or the one you'll <inherit> in another GWT module) to switch to running as GWT.

Categories : Gwt

What should be the expected value in the unit test
When you're unit testing, you're trying to validate that, for a given set of inputs, you have the correct outputs. In this case, you have two inputs: language and name. Presumably, given a certain combination of the two, there's an expected output. You, as the developer, should have the toolset necessary to determine that and validate whether it's correct. Then, once you have a test written, you'll never have to manually validate that behavior again! For example, if you were unit testing a calculator, you might test the Add method by asserting that given 1+1, the output is 2.

Categories : Unit Testing

Unit test RedirectToRouteResult
(Know the question is old but for anyone coming here) Hi, There is a more efficent way since you don't need to test these two lines Assert.IsTrue(result.RouteValues.ContainsKey("action")); Assert.IsTrue(result.RouteValues.ContainsKey("controller")); Those are assertions for code that you have not written. You have to trust that those who writes that code have there own unit tests. If against all odds the first two lines would be faulty, your two final assertions would fail.

Categories : Asp Net Mvc

Can a unit test not be automated?
You can have unit tests which are not automated. For example, I have done unit testing on a method that parses text in a file, where the file was dropped into a directory that was monitored for these files. Before the test was run, I needed to manually make sure that the file was available in the monitored directory. Since there was manual work to be done, the test was not an automated one. However, the test could be considered a unit test because it tested a small part (unit) of my code. This test was useful for me, because although it would not have worked by itself, I could still repeat it every time I made a change to make sure the parsing was happening the way I wanted to. Automating a test makes it a little easier for developers to test their code and keep it working.

Categories : Unit Testing



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.