Search Results

Search found 10010 results on 401 pages for 'a b testing'.

Page 25/401 | < Previous Page | 21 22 23 24 25 26 27 28 29 30 31 32  | Next Page >

  • Unit Testing Refcounted Critical Section Class

    - by BillyONeal
    Hello all :) I'm looking at a simple class I have to manage critical sections and locks, and I'd like to cover this with test cases. Does this make sense, and how would one go about doing it? It's difficult because the only way to verify the class works is to setup very complicated threading scenarios, and even then there's not a good way to test for a leak of a Critical Section in Win32. Is there a more direct way to make sure it's working correctly? Here's the code: CriticalSection.hpp: #pragma once #include <windows.h> namespace WindowsAPI { namespace Threading { class CriticalSection; class CriticalLock { std::size_t *instanceCount; CRITICAL_SECTION * criticalStructure; bool lockValid; friend class CriticalSection; CriticalLock(std::size_t *, CRITICAL_SECTION *, bool); public: bool IsValid() { return lockValid; }; void Unlock(); ~CriticalLock() { Unlock(); }; }; class CriticalSection { std::size_t *instanceCount; CRITICAL_SECTION * criticalStructure; public: CriticalSection(); CriticalSection(const CriticalSection&); CriticalSection& operator=(const CriticalSection&); CriticalSection& swap(CriticalSection&); ~CriticalSection(); CriticalLock Enter(); CriticalLock TryEnter(); }; }} CriticalSection.cpp: #include "CriticalSection.hpp" namespace WindowsAPI { namespace Threading { CriticalSection::CriticalSection() { criticalStructure = new CRITICAL_SECTION; instanceCount = new std::size_t; *instanceCount = 1; InitializeCriticalSection(criticalStructure); } CriticalSection::CriticalSection(const CriticalSection& other) { criticalStructure = other.criticalStructure; instanceCount = other.instanceCount; instanceCount++; } CriticalSection& CriticalSection::operator=(const CriticalSection& other) { CriticalSection copyOfOther(other); swap(copyOfOther); return *this; } CriticalSection& CriticalSection::swap(CriticalSection& other) { std::swap(other.instanceCount, instanceCount); std::swap(other.criticalStructure, other.criticalStructure); return *this; } CriticalSection::~CriticalSection() { if (!--(*instanceCount)) { DeleteCriticalSection(criticalStructure); delete criticalStructure; delete instanceCount; } } CriticalLock CriticalSection::Enter() { EnterCriticalSection(criticalStructure); (*instanceCount)++; return CriticalLock(instanceCount, criticalStructure, true); } CriticalLock CriticalSection::TryEnter() { bool lockAquired; if (TryEnterCriticalSection(criticalStructure)) { (*instanceCount)++; lockAquired = true; } else lockAquired = false; return CriticalLock(instanceCount, criticalStructure, lockAquired); } void CriticalLock::Unlock() { if (!lockValid) return; LeaveCriticalSection(criticalStructure); lockValid = false; if (!--(*instanceCount)) { DeleteCriticalSection(criticalStructure); delete criticalStructure; delete instanceCount; } } }}

    Read the article

  • Unit Testing in QTestLib - running single test / tests in class / all tests

    - by Dave
    I'm just starting to use QTestLib. I have gone through the manual and tutorial. Although I understand how to create tests, I'm just not getting how to make those tests convenient to run. My unit test background is NUnit and MSTest. In those environments, it was trivial (using a GUI, at least) to alternate between running a single test, or all tests in a single test class, or all tests in the entire project, just by clicking the right button. All I'm seeing in QTestLib is either you use the QTEST_MAIN macro to run the tests in a single class, then compile and test each file separately; or use QTest::qExec() in main() to define which objects to test, and then manually change that and recompile when you want to add/remove test classes. I'm sure I'm missing something. I'd like to be able to easily: Run a single test method Run the tests in an entire class Run all tests Any of those would call the appropriate setup / teardown functions.

    Read the article

  • Unit Testing a Django Form with a FileField

    - by Jason Christa
    I have a form like: #forms.py from django import forms class MyForm(forms.Form): title = forms.CharField() file = forms.FileField() #tests.py from django.test import TestCase from forms import MyForm class FormTestCase(TestCase) def test_form(self): upload_file = open('path/to/file', 'r') post_dict = {'title': 'Test Title'} file_dict = {} #?????? form = MyForm(post_dict, file_dict) self.assertTrue(form.is_valid()) How do I construct the *file_dict* to pass *upload_file* to the form?

    Read the article

  • Python Pre-testing for exceptions when coverage fails

    - by Tal Weiss
    I recently came across a simple but nasty bug. I had a list and I wanted to find the smallest member in it. I used Python's built-in min(). Everything worked great until in some strange scenario the list was empty (due to strange user input I could not have anticipated). My application crashed with a ValueError (BTW - not documented in the official docs). I have very extensive unit tests and I regularly check coverage to avoid surprises like this. I also use Pylint (everything is integrated in PyDev) and I never ignore warnings, yet I failed to catch this bug before my users did. Is there anything I can change in my methodology to avoid these kind of runtime errors? (which would have been caught at compile time in Java / C#?). I'm looking for something more than wrapping my code with a big try-except. What else can I do? How many other build in Python functions are hiding nasty surprises like this???

    Read the article

  • testing dao with hibernate genericdao pattern with spring.Headache

    - by black sensei
    Hello good fellas! in my journey of learning hibernate i came across an article on hibernate site. i' learning spring too and wanted to do certain things to discover the flexibility of spring by letting you implement you own session.yes i don't want to use the hibernateTemplate(for experiment). and i'm now having a problem and even the test class.I followed the article on the hibernate site especially the section an "implementation with hibernate" so we have the generic dao interface : public interface GenericDAO<T, ID extends Serializable> { T findById(ID id, boolean lock); List<T> findAll(); List<T> findByExample(T exampleInstance); T makePersistent(T entity); void makeTransient(T entity); } it's implementation in an abstract class that is the same as the one on the web site.Please refer to it from the link i provide.i'll like to save this post to be too long now come my dao's messagedao interface package com.project.core.dao; import com.project.core.model.MessageDetails; import java.util.List; public interface MessageDAO extends GenericDAO<MessageDetails, Long>{ //Message class is on of my pojo public List<Message> GetAllByStatus(String status); } its implementation is messagedaoimpl: public class MessageDAOImpl extends GenericDAOImpl <Message, Long> implements MessageDAO { // mySContainer is an interface which my HibernateUtils implement mySContainer sessionManager; /** * */ public MessageDAOImpl(){} /** * * @param sessionManager */ public MessageDAOImpl(HibernateUtils sessionManager){ this.sessionManager = sessionManager; } //........ plus other methods } here is my HibernatUtils public class HibernateUtils implements SessionContainer { private final SessionFactory sessionFactory; private Session session; public HibernateUtils() { this.sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory(); } public HibernateUtils(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } /** * * this is the function that return a session.So i'm free to implements any type of session in here. */ public Session requestSession() { // if (session != null || session.isOpen()) { // return session; // } else { session = sessionFactory.openSession(); // } return session; } } So in my understanding while using spring(will provide the conf), i'ld wire sessionFactory to my HiberbernateUtils and then wire its method RequestSession to the Session Property of the GenericDAOImpl (the one from the link provided). here is my spring config core.xml <bean id="sessionManager" class="com.project.core.dao.hibernate.HibernateUtils"> <constructor-arg ref="sessionFactory" /> </bean> <bean id="messageDao" class="com.project.core.dao.hibernate.MessageDAOImpl"> <constructor-arg ref="sessionManager"/> </bean> <bean id="genericDAOimpl" class="com.project.core.dao.GenericDAO"> <property name="session" ref="mySession"/> </bean> <bean id="mySession" factory-bean="com.project.core.dao.SessionContainer" factory-method="requestSession"/> now my test is this public class MessageDetailsDAOImplTest extends AbstractDependencyInjectionSpringContextTests{ HibernateUtils sessionManager = (HibernateUtils) applicationContext.getBean("sessionManager"); MessageDAO messagedao =(MessageDAO) applicationContext.getBean("messageDao"); static Message[] message = new Message[] { new Message("text",1,"test for dummies 1","1234567890","Pending",new Date()), new Message("text",2,"test for dummies 2","334455669990","Delivered",new Date()) }; public MessageDAOImplTest() { } @Override protected String[] getConfigLocations(){ return new String[]{"file:src/main/resources/core.xml"}; } @Test public void testMakePersistent() { System.out.println("MakePersistent"); messagedao.makePersistent(message[0]); Session session = sessionManager.RequestSession(); session.beginTransaction(); MessageDetails fromdb = ( Message) session.load(Message.class, message[0].getMessageId()); assertEquals(fromdb.getMessageId(), message[0].getMessageId()); assertEquals(fromdb.getDateSent(),message.getDateSent()); assertEquals(fromdb.getGlobalStatus(),message.getGlobalStatus()); assertEquals(fromdb.getNumberOfPages(),message.getNumberOfPages()); } i'm having this error exception in constructor testMakePersistent(java.lang.NullPointerException at com.project.core.dao.hibernate.MessageDAOImplTest) with this stack : at com.project.core.dao.hibernate.MessageDAOImplTest.(MessageDAOImplTest.java:28) at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27) at java.lang.reflect.Constructor.newInstance(Constructor.java:513) at junit.framework.TestSuite.createTest(TestSuite.java:61) at junit.framework.TestSuite.addTestMethod(TestSuite.java:283) at junit.framework.TestSuite.(TestSuite.java:146) at org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner.run(JUnitTestRunner.java:481) at org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner.launch(JUnitTestRunner.java:1031) at org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner.main(JUnitTestRunner.java:888) )) How to actually make this one work.I know this is a lot to stuffs and i'm thanking you for reading it.Please give me a solution.How would you do this? thanks

    Read the article

  • Unit Testing in ASP.NET MVC: Minimising the number of asserts per test

    - by Neil Barnwell
    I'm trying out TDD on a greenfield hobby app in ASP.NET MVC, and have started to get test methods such as the following: [Test] public void Index_GetRequest_ShouldReturnPopulatedIndexViewModel() { var controller = new EmployeeController(); controller.EmployeeService = GetPrePopulatedEmployeeService(); var actionResult = (ViewResult)controller.Index(); var employeeIndexViewModel = (EmployeeIndexViewModel)actionResult.ViewData.Model; EmployeeDetailsViewModel employeeViewModel = employeeIndexViewModel.Items[0]; Assert.AreEqual(1, employeeViewModel.ID); Assert.AreEqual("Neil Barnwell", employeeViewModel.Name); Assert.AreEqual("ABC123", employeeViewModel.PayrollNumber); } Now I'm aware that ideally tests will only have one Assert.xxx() call, but does that mean I should refactor the above to separate tests with names such as: Index_GetRequest_ShouldReturnPopulatedIndexViewModelWithCorrectID Index_GetRequest_ShouldReturnPopulatedIndexViewModelWithCorrectName Index_GetRequest_ShouldReturnPopulatedIndexViewModelWithCorrectPayrollNumber ...where the majority of the test is duplicated code (which therefore is being tested more than once and violates the "keep tests fast" advice)? That seems to be taking it to the extreme to me, so if I'm right as I am, what is the real-world meaning of the "one assert per test" advice?

    Read the article

  • Django TestCase testing order

    - by ziang
    If there are several methods in the test class, I found that the order to execute is alphabetical. But I want to customize the order of execution. How to define the execution order? For example: testTestA will be loaded first than testTestB. class Test(TestCase): def setUp(self): ... def testTestB(self): #test code def testTestA(self): #test code

    Read the article

  • Integration testing - Hibernate & DbUnit

    - by Marco
    Hi, I'm writing some integrations tests in JUnit. What happens here is that when i run all the tests together in a row (and not separately), the data persisted in the database always changes and the tests find unexpected data (inserted by the previous test) during their execution. I was thinking to use DbUnit, but i wonder if it resets the auto-increment index between each execution or not (because the tests also check the IDs of the persisted entities). Thanks M.

    Read the article

  • Testing bash scripts

    - by nimcap
    We have a system that has some bash scripts running besides Java code. Since we are trying to "Test Everything That Could Possibly Break" and those bash scripts may break, we want to test them. The problem is it is hard to test the scripts. Is there a way or a best practice to test bash scripts? Or should we quit using bash scripts and look for alternative solutions that are testable?

    Read the article

  • Unit Testing Hibernate's Optimistic Locking (within Spring)

    - by Michal Bachman
    I'd like to write a unit test to verify that optimistic locking is properly set up (using Spring and Hibernate). I'd like to have the test class extend Spring's AbstractTransactionalJUnit4SpringContextTests. What I want to end up with is a method like this: @Test (expected = StaleObjectStateException.class) public void testOptimisticLocking() { A a = getCurrentSession().load(A.class, 1); a.setVersion(a.getVersion()-1); getCurrentSession().saveOrUpdate(a); getCurrentSession().flush(); fail("Optimistic locking does not work"); } This test fails. What do you recommend as a best practice? The reason I am trying to do this is that I want to transfer the version to the client (using a DTO). I want to prove that when the DTO is sent back to the server and merged with a freshly loaded entity, saving that entity will fail if it's been updated by somebody else in the meantime.

    Read the article

  • Unit Testing: DateTime.Now

    - by Pedro
    I have some unit tests that expects the 'current time' to be different than DateTime.Now and I don't want to change the computer's time, obviously. What's the best strategy to achieve this? Thanks

    Read the article

  • Robotium Uniting Testing on an application having multiple processes

    - by warenix
    I have written an application running activities in multiple processes. I tried Robotium by creating a new test project set target package to my application. When I executed it, the test stopped with the following error message: Error in testDisplayBlackBox: java.lang.RuntimeException: Intent in process com.abc.def resolved to different process com.abc.def:mail: Intent { act=android.intent.action.MAIN flg=0x10000000 cmp=com.abc.def/com.abc.def.email.activity.Welcome } at android.app.Instrumentation.startActivitySync(Instrumentation.java:377) at android.test.InstrumentationTestCase.launchActivityWithIntent(InstrumentationTestCase.java:119) at android.test.InstrumentationTestCase.launchActivity(InstrumentationTestCase.java:97) at android.test.ActivityInstrumentationTestCase2.getActivity(ActivityInstrumentationTestCase2.java:104) at com.abc.def.test.TestApk.setUp(TestApk.java:31) at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:190) at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:175) at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:555) at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1584) Test results for InstrumentationTestRunner=.E Time: 0.027 FAILURES!!! Tests run: 1, Failures: 0, Errors: 1 Is it possible to have any workaround provided that I have source code in hand?

    Read the article

  • dummy IVR for testing vxml

    - by Nippysaurus
    Voxeo provide a free IVR for development purposes, but I was wondering if there is a much simpler form of test IVR, perhaps which runs on the local machine and uses your microphone and speakers instead of the telephony network?

    Read the article

  • Unit testing with Mocks when SUT is leveraging Task Parallel Libaray

    - by StevenH
    I am trying to unit test / verify that a method is being called on a dependency, by the system under test. The depenedency is IFoo. The dependent class is IBar. IBar is implemented as Bar. Bar will call Start() on IFoo in a new (System.Threading.Tasks.)Task, when Start() is called on Bar instance. Unit Test (Moq): [Test] public void StartBar_ShouldCallStartOnAllFoo_WhenFoosExist() { //ARRANGE //Create a foo, and setup expectation var mockFoo0 = new Mock<IFoo>(); mockFoo0.Setup(foo => foo.Start()); var mockFoo1 = new Mock<IFoo>(); mockFoo1.Setup(foo => foo.Start()); //Add mockobjects to a collection var foos = new List<IFoo> { mockFoo0.Object, mockFoo1.Object }; IBar sutBar = new Bar(foos); //ACT sutBar.Start(); //Should call mockFoo.Start() //ASSERT mockFoo0.VerifyAll(); mockFoo1.VerifyAll(); } Implementation of IBar as Bar: class Bar : IBar { private IEnumerable<IFoo> Foos { get; set; } public Bar(IEnumerable<IFoo> foos) { Foos = foos; } public void Start() { foreach(var foo in Foos) { Task.Factory.StartNew( () => { foo.Start(); }); } } } I appears that the issue is obviously due to the fact that the call to "foo.Start()" is taking place on another thread (/task), and the mock (Moq framework) can't detect it. But I could be wrong. Thanks

    Read the article

  • Testing fault tolerant code

    - by Robert
    I’m currently working on a server application were we have agreed to try and maintain a certain level of service. The level of service we want to guaranty is: if a request is accepted by the server and the server sends on an acknowledgement to the client we want to guaranty that the request will happen, even if the server crashes. As requests can be long running and the acknowledgement time needs be short we implement this by persisting the request, then sending an acknowledgement to the client, then carrying out the various actions to fulfill the request. As actions are carried out they too are persisted, so the server knows the state of a request on start up, and there’s also various reconciliation mechanisms with external systems to check the accuracy of our logs. This all seems to work fairly well, but we have difficult saying this with any conviction as we find it very difficult to test our fault tolerant code. So far we’ve come up with two strategies but neither is entirely satisfactory: Have an external process watch the server code and then try and kill it off at what the external process thinks is an appropriate point in the test Add code the application that will cause it to crash a certain know critical points My problem with the first strategy is the external process cannot know the exact state of the application, so we cannot be sure we’re hitting the most problematic points in the code. My problem with the second strategy, although it gives more control over were the fault takes, is I do not like have code to inject faults within my application, even with optional compilation etc. I fear it would be too easy to over look a fault injection point and have it slip into a production environment.

    Read the article

  • VS2008: File creation fails randomly in unit testing?

    - by Tim
    I'm working on implementing a reasonably simple XML serializer/deserializer (log file parser) application in C# .NET with VS 2008. I have about 50 unit tests right now for various parts of the code (mostly for the various serialization operations), and some of them seem to be failing mostly at random when they deal with file I/O. The way the tests are structured is that in the test setup method, I create a new empty file at a certain predetermined location, and close the stream I get back. Then I run some basic tests on the file (varying by what exactly is under test). In the cleanup method, I delete the file again. A large portion (usually 30 or more, though the number varies run to run) of my unit tests will fail at the initialize method, claiming they can't access the file I'm trying to create. I can't pin down the exact reason, since a test that will work one run fails the next; they all succeed when run individually. What's the problem here? Why can't I access this file across multiple unit tests? Relevant methods for a unit test that will fail some of the time: [TestInitialize()] public void LogFileTestInitialize() { this.testFolder = System.Environment.GetFolderPath( System.Environment.SpecialFolder.LocalApplicationData ); this.testPath = this.testFolder + "\\empty.lfp"; System.IO.File.Create(this.testPath); } [TestMethod()] public void LogFileConstructorTest() { string filePath = this.testPath; LogFile target = new LogFile(filePath); Assert.AreNotEqual(null, target); Assert.AreEqual(this.testPath, target.filePath); Assert.AreEqual("empty.lfp", target.fileName); Assert.AreEqual(this.testFolder + "\\empty.lfp.lfpdat", target.metaPath); } [TestCleanup()] public void LogFileTestCleanup() { System.IO.File.Delete(this.testPath); } And the LogFile() constructor: public LogFile(String filePath) { this.entries = new List<Entry>(); this.filePath = filePath; this.metaPath = filePath + ".lfpdat"; this.fileName = filePath.Substring(filePath.LastIndexOf("\\") + 1); } The precise error message: Initialization method LogFileParserTester.LogFileTest.LogFileTestInitialize threw exception. System.IO.IOException: System.IO.IOException: The process cannot access the file 'C:\Users\<user>\AppData\Local\empty.lfp' because it is being used by another process..

    Read the article

  • Rhapsody TestConductor Experiences

    - by vaiomike
    I was wondering whether anybody out there is actively using Rhapsody TestConductor? Or has tried it for a while, but then decided to turn it down for a particular reason? If so, what are your experiences, in which field do you apply it, what are the shortcomings, or why did you turn it down? At the moment we're considering TestConductor as our tool of choice for testing as it's already integrated into Rhapsody, and would like to find out how applicable it is to our project (btw, we're using Rhapsody 7.4 in C). P.S: Recommendations on good books about Model Based Testing are also appreciated.

    Read the article

  • Testing install procedure of a program requiring administrative privileges

    - by Lucas Meijer
    I'm trying to write automated test, to ensure that the installer for my program works okay. The program can be installed for all users (requires admin privs), or for current user (does not require admin privs). The program can also autoupdate itself, which in some cases requires admin privileges, and in some cases doesn't. I'm looking for a way where I can have an automated test click "Yes, Allow" on the UAC dialogs, so I can write tests for all different scenarios, on many different operating systems, so that I can be confident when I make changes to the installer that I didn't break anything. Obviously, the installer process itself cannot do this. However, I control the complete machine, and could easily start some sort of daemon process with administrative rights, that the testprogram could make a socket connection to, to request it to "please click ok on the UAC now".

    Read the article

  • Null reference to DataContext when testing an ASP.NET MVC app with NUnit

    - by user252160
    I have an ASP.NET MVC application with a separate project added for tests. I know the plusses and minuses of using the connection to the database when running unit tests, and I still want to use it. Yet, every time when I run the tests with the NUnit tool, they all fail due to my Data Context being null. I heard something about having a separate config file for the tests assembly, but i am not sure whether I did it properly, or whether that works at all.

    Read the article

  • Unit testing and mocking email sender in Python with Google AppEngine

    - by CVertex
    I'm a newbie to python and the app engine. I have this code that sends an email based on request params after some auth logic. in my Unit tests (i'm using GAEUnit), how do I confirm an email with specific contents were sent? - i.e. how do I mock the emailer with a fake emailer to verify send was called? class EmailHandler(webapp.RequestHandler): def bad_input(self): self.response.set_status(400) self.response.headers['Content-Type'] = 'text/plain' self.response.out.write("<html><body>bad input </body></html>") def get(self): to_addr = self.request.get("to") subj = self.request.get("subject") msg = self.request.get("body") if not mail.is_email_valid(to_addr): # Return an error message... # self.bad_input() pass # authenticate here message = mail.EmailMessage() message.sender = "[email protected]" message.to = to_addr message.subject = subj message.body = msg message.send() self.response.headers['Content-Type'] = 'text/plain' self.response.out.write("<html><body>success!</body></html>") And the unit tests, import unittest from webtest import TestApp from google.appengine.ext import webapp from email import EmailHandler class SendingEmails(unittest.TestCase): def setUp(self): self.application = webapp.WSGIApplication([('/', EmailHandler)], debug=True) def test_success(self): app = TestApp(self.application) response = app.get('http://localhost:8080/[email protected]&body=blah_blah_blah&subject=mySubject') self.assertEqual('200 OK', response.status) self.assertTrue('success' in response) # somehow, assert email was sent

    Read the article

  • Testing chess game

    - by mousey
    There is a software for chess game and we need to test the following method: boolean canMoveTo(int x, int y) x and y are the coordinates of the chess board and it returns true/false whether the piece can move to that position or not. We need to test this method for a pawn piece and you can set up the board any way you like prior to running a test case. Source code is not provided

    Read the article

  • Unit testing a controller method?

    - by Stefan Kendall
    I have a controller method like such: def search = { def query = params.query ... render results as JSON } How do I unit test this? Specifically, how do I call search to set params.query, and how do I test the results of the method render? Is there a way to mock the render method, perhaps?

    Read the article

< Previous Page | 21 22 23 24 25 26 27 28 29 30 31 32  | Next Page >