Search Results

Search found 177 results on 8 pages for 'assertions'.

Page 1/8 | 1 2 3 4 5 6 7 8  | Next Page >

  • Are too many assertions code smell?

    - by Florents
    I've really fallen in love with unit testing and TDD - I am test infected. However, unit testing is used for public methods. Sometimes though I do have to test some assumptions-assertions in private methods too, because some of them are "dangerous" and refactoring can't help further. (I know, testing frameworks allo testing private methods). So, It became a habit of mine that (almost always) the first and the last line of a private method are both assertions. I guess this couldn't be bad (right ??). However, I've noticed that I also tend to use assertions in public methods too (as in the private) just "to be sure". Could this be "testing duplication" since the public method assumpotions are tested from the unit testng framework? Could someone think of too many assertions as a code smell?

    Read the article

  • use of assertions for type checking in php?

    - by user151841
    I do some checking of arguments in my classes in php using exception-throwing functions. I have functions that do a basic check ( ===, in_array etc ) and throw an exception on false. So I can do assertNumeric($argument, "\$argument is not numeric."); instead of if ( ! is_numeric($argument) ) { throw new Exception("\$argument is not numeric."); } Saves some typing I was reading in the comments of the php manual page on assert() that As noted on Wikipedia - "assertions are primarily a development tool, they are often disabled when a program is released to the public." and "Assertions should be used to document logically impossible situations and discover programming errors— if the 'impossible' occurs, then something fundamental is clearly wrong. This is distinct from error handling: most error conditions are possible, although some may be extremely unlikely to occur in practice. Using assertions as a general-purpose error handling mechanism is usually unwise: assertions do not allow for graceful recovery from errors, and an assertion failure will often halt the program's execution abruptly. Assertions also do not display a user-friendly error message." This means that the advice given by "gk at proliberty dot com" to force assertions to be enabled, even when they have been disabled manually, goes against best practices of only using them as a development tool So, am I 'doing it wrong'? What other/better ways of doing this are there?

    Read the article

  • The "is" in JUnit 4 assertions

    - by Space_C0wb0y
    Is there any semantic difference between writing assertThat(object1, is(equalTo(object2))); and writing assertThat(object1, equalTo(object2))); ? If not, I would prefer the first version, because it reads better. Are there any other considerations here?

    Read the article

  • Documentation and Test Assertions in Databases

    - by Phil Factor
    When I first worked with Sybase/SQL Server, we thought our databases were impressively large but they were, by today’s standards, pathetically small. We had one script to build the whole database. Every script I ever read was richly annotated; it was more like reading a document. Every table had a comment block, and every line would be commented too. At the end of each routine (e.g. procedure) was a quick integration test, or series of test assertions, to check that nothing in the build was broken. We simply ran the build script, stored in the Version Control System, and it pulled everything together in a logical sequence that not only created the database objects but pulled in the static data. This worked fine at the scale we had. The advantage was that one could, by reading the source code, reach a rapid understanding of how the database worked and how one could interface with it. The problem was that it was a system that meant that only one developer at the time could work on the database. It was very easy for a developer to execute accidentally the entire build script rather than the selected section on which he or she was working, thereby cleansing the database of everyone else’s work-in-progress and data. It soon became the fashion to work at the object level, so that programmers could check out individual views, tables, functions, constraints and rules and work on them independently. It was then that I noticed the trend to generate the source for the VCS retrospectively from the development server. Tables were worst affected. You can, of course, add or delete a table’s columns and constraints retrospectively, which means that the existing source no longer represents the current object. If, after your development work, you generate the source from the live table, then you get no block or line comments, and the source script is sprinkled with silly square-brackets and other confetti, thereby rendering it visually indigestible. Routines, too, were affected. In our system, every routine had a directly attached string of unit-tests. A retro-generated routine has no unit-tests or test assertions. Yes, one can still commit our test code to the VCS but it’s a separate module and teams end up running the whole suite of tests for every individual change, rather than just the tests for that routine, which doesn’t scale for database testing. With Extended properties, one can get the best of both worlds, and even use them to put blame, praise or annotations into your VCS. It requires a lot of work, though, particularly the script to generate the table. The problem is that there are no conventional names beyond ‘MS_Description’ for the special use of extended properties. This makes it difficult to do splendid things such ensuring the integrity of the build by running a suite of tests that are actually stored in extended properties within the database and therefore the VCS. We have lost the readability of database source code over the years, and largely jettisoned the use of test assertions as part of the database build. This is not unexpected in view of the increasing complexity of the structure of databases and number of programmers working on them. There must, surely, be a way of getting them back, but I sometimes wonder if I’m one of very few who miss them.

    Read the article

  • Using lookahead assertions in regular expressions

    - by Greg Jackson
    I use regular expressions on a daily basis, as my daily work is 90% in Perl (legacy codebase, but that's a different issue). Despite this, I still find lookahead and lookbehind to be terribly confusing and often unreadable. Right now, if I were to get a code review with a lookahead or lookbehind, I would immediately send it back to see if the problem can be solved by using multiple regular expressions or a different approach. The following are the main reasons I tend not to like them: They can be terribly unreadable. Lookahead assertions, for example, start from the beginning of the string no matter where they are placed. That, among other things, can cause some very "interesting" and non-obvious behaviors. It used to be the case that many languages didn't support lookahead/lookbehind (or supported them as "experimental features"). This isn't the case quite as much, but there's still always the question as to how well it's supported. Quite frankly, they feel like a dirty hack. Regexps often already are, but they can also be quite elegant, and have gained widespread acceptance. I've gotten by without any need for them at all... sometimes I think that they're extraneous. Now, I'll freely admit that especially the last two reasons aren't really good ones, but I felt that I should enumerate what goes through my mind when I see one. I'm more than willing to change my mind about them, but I feel that they violate some of my core tenets of programming, including: Code should be as readable as possible without sacrificing functionality -- this may include doing something in a less efficient, but clearer was as long as the difference is negligible or unimportant to the application as a whole. Code should be maintainable -- if another programmer comes along to fix my code, non-obvious behavior can hide bugs or make functional code appear buggy (see readability) "The right tool for the right job" -- I'm sure you can come up with contrived examples that could use lookahead, but I've never come across something that really needs them in my real-world development work. Is there anything that they're really the best tool for, as opposed to, say, multiple regexps (or, alternatively, are they the best tool for most cases they're used for today). My question is this: Is it good practice to use lookahead/lookbehind in regular expressions, or are they simply a hack that have found their way into modern production code? I'd be perfectly happy to be convinced that I'm wrong about this, and simple examples are useful for examples or illustration, but by themselves, won't be enough to convince me.

    Read the article

  • Where to put Assertions?

    - by sud03r
    Hi, Having assertions for unexpected conditions is considered to be good defensive coding practice. I happen to place assertions whenever i think something unexpected may happen, but that now seems to be an overkill to me. Additionally, sometimes mild unexpected conditions that don't necessarily lead to crash may even cause failure on customer end. Is there a hard and fast rule to put assertions? Thanks.

    Read the article

  • Is Debug.Assert obsolete if you write unit tests?

    - by Justin Pihony
    Just like the question asks, is there a need to add Debug.Assert into your code if you are writing unit tests (which has its own assertions)? I could see that this might make the code more obvious without having to go into the tests, however it just seems that you might end up with duplicated asserts. It seems to me that Debug.Assert was helpful before unit-testing became more prevalent, but is now unnecessary. Or, am I not thinking of some use case?

    Read the article

  • Shibboleth: found encrypted assertions, but no CredentialResolver was available

    - by HorusKol
    I've gotten a Shibboleth Server Provider (SP) up and running, and I'm using the TestShib Identity Provider (IdP) for testing. The configuration appears to be all correct, and when I requested my secured directory I was sent to the IdP where I logged in and then was sent back to https://example.org/Shibboleth.sso/SAML2/POST where I am getting a generic error message. Checking the logs, I am told: found encrypted assertions, but no CredentialResolver was available I have rechecked the configuration, and there I have: <CredentialResolver type="File" key="/etc/shibboleth/sp-key.pem" certificate="/etc/shibboleth/sp-cert.pem"/> Both of these files are present at those locations. I've restarted apache and retried, but still get the same error. I don't know if it makes a difference - but only a subdirectory of the site has been secured - the documentroot is publicly available.

    Read the article

  • Should I create my own Assert class based on these reasons?

    - by Mike
    The main reason I don't like Debug.Assert is the fact that these assertions are disabled in Release. I know that there's a performance reason for that, but at least in my situation I believe the gains would outweigh the cost. (By the way, I'm guessing this is the situation in most cases). And yes, I know that you can use Trace.Assert instead. But even though that would work, I find the name Trace distracting, since I don't see this as tracing. The other reason to create my own class is laziness I guess, since I could write methods for the most usual cases like Assert.IsNotNull, Assert.Equals and so forth. The second part of my question has to do with using Environment.FailFast in this class. Would that be a good idea? I do like the ideas put forth in this document. That's pretty much where I got the idea from. One last point. Does creating a design like this imply having an untestable code path, as described in this answer by Eric Lippert on a different (but related) question?

    Read the article

  • When should assertions stay in production code?

    - by Carl Seleborg
    Hi all, There's a discussion going on over at comp.lang.c++.moderated about whether or not assertions, which in C++ only exist in debug builds by default, should be kept in production code or not. Obviously, each project is unique, so my question here is not so much whether assertions should be kept, but in which cases this is recommendable/not a good idea. By assertion, I mean: A run-time check that tests a condition which, when false, reveals a bug in the software. A mechanism by which the program is halted (maybe after really minimal clean-up work). I'm not necessarily talking about C or C++. My own opinion is that if you're the programmer, but don't own the data (which is the case with most commercial desktop applications), you should keep them on, because a failing asssertion shows a bug, and you should not go on with a bug, with the risk of corrupting the user's data. This forces you to test strongly before you ship, and makes bugs more visible, thus easier to spot and fix. What's your opinion/experience? Cheers, Carl See related question here

    Read the article

  • Binding type variables that only occur in assertions

    - by Giuseppe Maggiore
    Hi! I find it extremely difficult to describe my problem, so here goes nothing: I have a bunch of assertions on the type of a function. These assertions rely on a type variable that is not used for any parameter of the function, but is only used for internal bindings. Whenever I use this function it does not compile because, of course, the compiler has no information from which to guess what type to bind my type variable. Here is the code: {-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances, UndecidableInstances, FlexibleContexts, EmptyDataDecls, ScopedTypeVariables, TypeOperators, TypeSynonymInstances #-} class C a a' where convert :: a -> a' class F a b where apply :: a -> b class S s a where select :: s -> a data CInt = CInt Int instance S (Int,String) Int where select (i,_) = i instance F Int CInt where apply = CInt f :: forall s a b . (S s a, F a b) => s -> b f s = let v = select s :: a y = apply v :: b in y x :: Int x = f (10,"Pippo") And here is the generated error: FunctorsProblems.hs:21:4: No instances for (F a Int, S (t, [Char]) a) arising from a use of `f' at FunctorsProblems.hs:21:4-17 Possible fix: add an instance declaration for (F a Int, S (t, [Char]) a) In the expression: f (10, "Pippo") In the definition of `x': x = f (10, "Pippo") Failed, modules loaded: none. Prelude>

    Read the article

  • How can I improve my error checking and handling?

    - by Google
    Lately I have been struggling to understand what the right amount of checking is and what the proper methods are. I have a few questions regarding this: What is the proper way to check for errors (bad input, bad states, etc)? Is it better to explicitly check for errors, or use functions like asserts which can be optimized out of your final code? I feel like explicitly checking clutters a program with a lot of extra code which shouldn't be executed in most situations anyway-- and not to mention most errors end up with an abort/exit failure. Why clutter a function with explicit checks just to abort? I have looked for asserts versus explicit checking of errors and found little to truly explain when to do either. Most say 'use asserts to check for logic errors and use explicit checks to check for other failures.' This doesn't seem to get us very far though. Would we say this is feasible: Malloc returning null, check explictly API user inserting odd input for functions, use asserts Would this make me any better at error checking? What else can I do? I really want to improve and write better, 'professional' code.

    Read the article

  • Why do I get this Debug Assertion Failed? Expression: list iterator not dereferenceable [migrated]

    - by Karel
    I'm trying this example in the (translated to dutch) book of Bjarne Stroustrup (C++): #include <vector> #include <list> #include "complex.h" complex ac[200]; std::vector<complex> vc; std::list<complex> l; template<class In, class Out> void Copy(In from, In too_far, Out to) { while(from != too_far) { *to = *from; ++to; ++from; } } void g(std::vector<complex>& vc , std::list<complex>& lc) { Copy(&ac[0], &ac[200], lc.begin()); // generates debug error Copy(lc.begin(), lc.end(), vc.begin()); // also generates debug error } void f() { ac[0] = complex(10,20); g(vc, l); } int main () { f(); } ** Compiling and Linking goes successful (0 errors/warnings)** But at runtime I get this error: Debug Assertion Failed! Program: path to exe file: \program files\ms vs studio 10.0\vc\include\list Line: 207 Expression: list iterator not dereferenceable For information on how your program can cause an assertion failure, see the Visual C++ documentation on asserts. (Press retry to debug the application)

    Read the article

  • Is possible to write too many asserts?

    - by Lex Fridman
    I am a big fan of writing assert checks in C++ code as a way to catch cases during development that cannot possibly happen but do happen because of logic bugs in my program. This is a good practice in general. However, I've noticed that some functions I write (which are part of a complex class) have 5+ asserts which feels like it could potentially be a bad programming practice, in terms of readability and maintainability. I think it's still great, as each one requires me to think about pre- and post-conditions of functions and they really do help catch bugs. However, I just wanted to put this out there to ask if there is a better paradigms for catching logic errors in cases when a large number of checks is necessary.

    Read the article

  • Test assertions for tuples with floats

    - by Space_C0wb0y
    I have a function that returns a tuple that, among others, contains a float value. Usually I use assertAlmostEquals to compare those, but this does not work with tuples. Also, the tuple contains other data-types as well. Currently I am asserting every element of the tuple individually, but that gets too much for a list of such tuples. Is there any good way to write assertions for such cases?

    Read the article

  • Weirdness with cabal, HTF, and HUnit assertions

    - by rampion
    So I'm trying to use HTF to run some HUnit-style assertions % cat tests/TestDemo.hs {-# OPTIONS_GHC -Wall -F -pgmF htfpp #-} module Main where import Test.Framework import Test.HUnit.Base ((@?=)) import System.Environment (getArgs) -- just run some tests main :: IO () main = getArgs >>= flip runTestWithArgs Main.allHTFTests -- all these tests should fail test_fail_int1 :: Assertion test_fail_int1 = (0::Int) @?= (1::Int) test_fail_bool1 :: Assertion test_fail_bool1 = True @?= False test_fail_string1 :: Assertion test_fail_string1 = "0" @?= "1" test_fail_int2 :: Assertion test_fail_int2 = [0::Int] @?= [1::Int] test_fail_string2 :: Assertion test_fail_string2 = "true" @?= "false" test_fail_bool2 :: Assertion test_fail_bool2 = [True] @?= [False] And when I use ghc --make, it seems to work correctly. % ghc --make tests/TestDemo.hs [1 of 1] Compiling Main ( tests/TestDemo.hs, tests/TestDemo.o ) Linking tests/TestDemo ... % tests/TestDemoA ... * Tests: 6 * Passed: 0 * Failures: 6 * Errors: 0 Failures: * Main:fail_int1 (tests/TestDemo.hs:9) * Main:fail_bool1 (tests/TestDemo.hs:12) * Main:fail_string1 (tests/TestDemo.hs:15) * Main:fail_int2 (tests/TestDemo.hs:19) * Main:fail_string2 (tests/TestDemo.hs:22) * Main:fail_bool2 (tests/TestDemo.hs:25) But when I use cabal to build it, not all the tests that should fail, fail. % cat Demo.cabal ... executable test-demo build-depends: base >= 4, HUnit, HTF main-is: TestDemo.hs hs-source-dirs: tests % cabal configure Resolving dependencies... Configuring Demo-0.0.0... % cabal build Preprocessing executables for Demo-0.0.0... Building Demo-0.0.0... [1 of 1] Compiling Main ( tests/TestDemo.hs, dist/build/test-demo/test-demo-tmp/Main.o ) Linking dist/build/test-demo/test-demo ... % dist/build/test-demo/test-demo ... * Tests: 6 * Passed: 3 * Failures: 3 * Errors: 0 Failures: * Main:fail_int2 (tests/TestDemo.hs:23) * Main:fail_string2 (tests/TestDemo.hs:26) * Main:fail_bool2 (tests/TestDemo.hs:29) What's going wrong and how can I fix it?

    Read the article

  • Where do you manually insert assertions into an automated coded ui test's code in VS2010?

    - by user1649536
    I am currently automating smoke tests and I am trying to learn how to manually insert assertions with C# into the UImap.Designer.cs file. I am trying to learn how to do this manually but I have no direction on where to put the assertions and all the literature I am finding only covers how to add assertions with the CodedUI Test Builder tool that is included with VS2010. Can anyone direct me to where I need to insert the assertions?

    Read the article

  • Creating Custom Assertions in Oracle Web service Manager (OWSM)

    - by sachin
    I am trying to create example given at this site: http://download.oracle.com/docs/cd/E12839_01/web.1111/b32511/custom_assertions.htm#CIHFGJAG but While compiling I get following errors: Error(63,64): cannot access oracle.annotation.logging.Publish Error: error: in class file D:\Installations\Oracle\Middleware_11g\oracle_common\modules\oracle.wsm.common_11.1.1\wsm-policy-core.jar/oracle/wsm/resources/enforcement/EnforcementMessageID.class: unknown enum constant oracle.annotation.logging.Publish.NO Error(69,28): cannot access oracle.annotation.logging.Category Error(70,48): cannot find variable FAULT_FAILED_CHECK Error(75,17): cannot access oracle.annotation.logging.Severity I have included: wsm-policy-core.jar, wsm-agent-core.jar findjars.com shows oracle.annotation.logging.Publish present in: logging-utils.jar I downloaded latest oc4j, but still not able to find this jar or resolve the issue. Please help!

    Read the article

  • Ruby assertions and disabled inputs

    - by brad
    Does anyone know how to assert that a checkbox or input is disabled? I can't find anything to indicated that this is supported I'm writing cucumber tests with webrat and test/unit. I'd like to have a step that is able to assert_disabled :some_checkbox || assert_disabled :some_input. Or some way that I can check a property of the checkbox.

    Read the article

  • Mock Assertions on objects inside Parallel ForEach's???

    - by jacko
    Any idea how we can assert a mock object was called when it is being accessed inside Parallel.ForEach via a closure? I assume that because each invocation is on a different thread that Rhino Mocks loses track of the object? Pseudocode: var someStub = MockRepository.GenerateStub() Parallel.Foreach(collectionOfInts, anInt => someStub.DoSomething(anInt)) someStub.AssertWasCalled(s => s.DoSomething, Repeat.Five.Times) This test will return an expectation violation, expecting the stub to be called 5 times but being actually called 0 times. Any ideas how we can tell the lambdas to keep track of the thread-local stub object?

    Read the article

  • Do invariant assertions fit into C# programming?

    - by P.Brian.Mackey
    In the book coders at work, the author asks "How do you use invariants in your code". Please explain what this question means. I saw class invariants on wiki, but the example is in Java and I am not skilled enough in Java to relate this example to C#. .NET 4.0 introduces invariance, covariance, and contravariance and is well explained here. Invariance is so broad. The authors usage of the word seems unit test related. For those that read the book, what does the author mean? Are we talking about making an assumption and simply testing the validity after the unit test?

    Read the article

  • Xunit: Perform all 'Assert'ions in one test method?

    - by Jörg Battermann
    Is it possible to tell xUnit.net to perform all e.g. Assert.True() in one test method? Basically in some of our use/testcases all assertions belong logically to one and the same 'scope' of tests and I have e.g. something like this: [Fact(DisplayName = "Tr-MissImpl")] public void MissingImplementationTest() { // parse export.xml file var exportXml = Libraries.Utilities.XML.GenericClassDeserializer.DeserializeXmlFile<Libraries.MedTrace.ExportXml>( ExportXmlFile); // compare parsed results with expected ones Assert.True(exportXml.ContainsRequirementKeyWithError("PERS_154163", "E0032A")); Assert.True(exportXml.ContainsRequirementKeyWithError("PERS_155763", "E0032A")); Assert.True(exportXml.ContainsRequirementKeyWithError("PERS_155931", "E0032A")); Assert.True(exportXml.ContainsRequirementKeyWithError("PERS_157145", "E0032A")); Assert.True(exportXml.ContainsRequirementKeyWithError("s_sw_ers_req_A", "E0032A")); Assert.True(exportXml.ContainsRequirementKeyWithError("s_sw_ers_req_C", "E0032A")); Assert.True(exportXml.ContainsRequirementKeyWithError("s_sw_ers_req_D", "E0032A")); } Now if e.g. the first Assert.True(...) fails, the other ones are not executed/checked. I'd rather not break these seven Assertions up into separate methods, since these really do belong together logically (the TC only is 'passed' entirely if all seven are passing all together).

    Read the article

  • Writing fortran robust and "modern" code

    - by Blklight
    In some scientific environments, you often cannot go without FORTRAN as most of the developers only know that idiom, and there is lot of legacy code and related experience. And frankly, there are not many other cross-platform options for high performance programming ( C++ would do the task, but the syntax, zero-starting arrays, and pointers are too much for most engineers ;-) ). I'm a C++ guy but I'm stuck with some F90 projects. So, let's assume a new project must use FORTRAN (F90), but I want to build the most modern software architecture out of it. while being compatible with most "recent" compilers (intel ifort, but also including sun/HP/IBM own compilers) So I'm thinking of imposing: global variable forbidden, no gotos, no jump labels, "implicit none", etc. "object-oriented programming" (modules with datatypes + related subroutines) modular/reusable functions, well documented, reusable libraries assertions/preconditions/invariants (implemented using preprocessor statements) unit tests for all (most) subroutines and "objects" an intense "debug mode" (#ifdef DEBUG) with more checks and all possible Intel compiler checks possible (array bounds, subroutine interfaces, etc.) uniform and enforced legible coding style, using code processing tools C stubs/wrappers for libpthread, libDL (and eventually GPU kernels, etc.) C/C++ implementation of utility functions (strings, file operations, sockets, memory alloc/dealloc reference counting for debug mode, etc.) ( This may all seem "evident" modern programming assumptions, but in a legacy fortran world, most of these are big changes in the typical programmer workflow ) The goal with all that is to have trustworthy, maintainable and modular code. Whereas, in typical fortran, modularity is often not a primary goal, and code is trustworthy only if the original developer was very clever, and the code was not changed since then ! (i'm a bit joking here, but not much) I searched around for references about object-oriented fortran, programming-by-contract (assertions/preconditions/etc.), and found only ugly and outdated documents, syntaxes and papers done by people with no large-scale project involvement, and dead projects. Any good URL, advice, reference paper/books on the subject?

    Read the article

  • Grails Unit Tests: Why does this statement fail?

    - by leeand00
    I've developed in Java in the past, and now I'm trying to learn Grails/Groovy using this slightly dated tutorial. import grails.test.* class DateTagLibTests extends TagLibUnitTestCase { def dateTagLib protected void setUp() { super.setUp() dateTagLib = new DateTagLib() } protected void tearDown() { super.tearDown() } void testThisYear() { String expected = Calendar.getInstance().get(Calendar.YEAR) // NOTE: This statement fails assertEquals("the years dont match and I dont know why.", expected, dateTagLib.thisYear()) } } DateTagLibTests.groovy (Note: this TagLibUnitTestCase is for Grails 1.2.1 and not the version used in the tutorial) For some reason the above test fails with: expected:<2010 but was:<2010 I've tried replacing the test above with the following alternate version of the test, and the test passes just fine: void testThisYear() { String expected = Calendar.getInstance().get(Calendar.YEAR) String actual = dateTagLib.thisYear() // NOTE: The following two assertions work: assertEquals("the years don\'t match", expected, actual) assertTrue("the years don\'t match", expected.equals(actual)) } These two versions of the test are basically the same thing right? Unless there's something new in Grails 1.2.1 or Groovy that I'm not understanding. They should be of the same type because the values are both the value returned by Calendar.getInstance().get(Calendar.YEAR)

    Read the article

1 2 3 4 5 6 7 8  | Next Page >