Defensive coding and unit test rules (2)

Source: Internet
Author: User
Tags printable characters

Enhanced security (en garde )!

Remember that your customers have different ideas about your products. They will install it in an environment that your group probably never imagined-or at least never tested. They will use it in methods you have never imagined and configure it in unexpected ways. The following list helps you ensure that they are not angry:

  • Verify the integrity of all received parameters (if you expect an arraynullBut you didn't check the possibility before indexing the array ).

  • Consider all possible error cases and add code to handle each case (you want the code to handle the error conditions appropriately rather than blocking it ).

  • For Unexpected error conditions, add a general "catch all" error handler.

  • Use constants when and where appropriate.

  • Add tracking and logs throughout the Code.

  • If your product is translated into another language, make sure that your code "supports" it. Even if there is a small chance of such a situation, it is always better to plan ahead. Modifying code to support it is the easiest way to produce defects. The following are some questions about support:

    • Do you have any hard-coded strings?

    • Do you correctly process different dates/times?

    • What about different currencies?

  • Also, a large number of assertions are used in the code.

  • AddAdequateAnnotations. In short, do you still remember the idea when writing that method six months ago? What will happen to someone who wants to modify your code one year later? Of all our suggestions, this one may be the most important.

    Unit testing (defensive Testing Technology)

    In this article, unit testing is all testing and analysis performed by developers after their code is correctly compiled and handed over to the functional testing team. As we mentioned in this test, we take the initiative to conduct unit tests and think like a tester (that is, we must think about the downside, be keen on destruction, and be fond of prank) is very important. The following are several things to remember during unit testing.

    Static code analysis tools

    The first and easiest way to analyze code is to let someone else do it for you-or let other tools do it for you like here. There are some different static code analysis tools available, from comprehensive tools-some development agencies are actually in their "Compiling" Environment (this is what needs to be purchased) to other tools that can be downloaded from the Internet for free.

    Defects discovered

    When you are preparing to run the code and check for defects, remember to think about the disadvantages. These defects are generated by the code you have created or ignored. The following are some tips to help you find defects in the Code:

    • Try to forcibly create all the error conditions you think of and check all the error messages that can appear.

    • Try to use the code path that interacts with other components or programs. If other programs or components do not exist, write some scaffolding code so that you can try APIs or fill in shared memory, shared queue, and so on. And allow your function testing team to use this scaffolding code so that they can add it to their weapons library.

    • For each input field in the GUI, experiment with different combinations below (considerAutomation):

      • Unacceptable characters (control characters, non-printable characters, etc ).

      • Too many characters.

      • Too few characters.

      • Negative number (especially when you only want a positive number ).

      • A large value or a small value.

      • Cut and paste data and text into the input field, especially when the code you write limits that users can enter the content of this field.

      • A combination of text and numbers.

      • All uppercase letters and all lowercase letters.
    • Create "stress conditions" for the Code, such as a large number of activities, a slow connection network, and all the things you think of that can push the code to the limit.

    • Repeat the same steps and then:

      • Check for unanticipated memory loss conditions.

      • Check what happens when the memory is used up.

      • Try to create cache overflow, full queue, unavailable cache, and other situations where "cannot work correctly.
    • For array and cache, try to add to array (or cache)nData items, and then try to deleten+1

      Items.

    About time?

    What happens if "B" is performed before "A" is operated? Even if you don't think it will happen-can you make it happen? If yes, you can bet that your customer will make it happen. It is better to find out now, instead of doing it after the repair cost is higher and the customer complains that your software quality is poor.

    Scaffolding code

    We discussed the scaffolding code in the previous defects. If it is created for your own use needs, it must be handed over to the verification engineer. The scaffolding code you provide may allow them to quickly start testing your code, or at least give them a better understanding of what can be expected when other components exist.

    If your product has protective security functions, you must test them. It is important to provide scaffolding code that can create situations that you want to prevent: You must be able to create situations that the system is trying to prevent.

    Another simple example of scaffolding Code is to provide code for manipulating queues. If your product uses a queue, you can add or delete items from the queue at runtime, or destroy data in the queue (to ensure proper error handling) and so on.

    Source code-level debugging program

    Using source code-level debugging programs is a key method for thorough and successful unit tests. Developers should end up with their debugging programs. Unfortunately, the full understanding and use of source code-level debugging programs is a dying practice, although the benefits of these debugging programs far exceed any learning curve. In short, we strongly encourage you to fully learn a debugging program. The following are several methods to perform unit tests on the code using the source code-level debugging program. You can:

    • Manipulate data during running-for example, set a breakpoint when entering the code, and then re-set the passed parameter value to check whether the code can properly process (currently) invalid parameters. When using the debugging program in this way, you do not need to make the error conditions happen.

    • Set the breakpoint, and then "Step" through the Code, so that you can see what each line of code does.

    • Set "watch" for the variable )".

    • Forcibly use the error code path.

    • Observe the call stack to check which routine calls your code.

    • "Capture" them when an error occurs.

    • Run the boundary check.

    Know your verification Engineer

    Verification engineers are a good source of test knowledge. They can show you what to test and help you understand what to add to the Code to help them test (such as code hooks ). In addition, you can show them how to use your scaffolding code. They will also be very interested in understanding what you think should be automated in testing-if you have done something more than once, they will.

    Start quiz!

    Now is the time to perform a small test. Let's see if you are working hard.

    Problem

    You want to check whether the value of an integer is 5. Generally, you need to write code like this:

          
           if ( i == 5 ) then  {    //    // do something...    //  }
          

    However, if you perform a "Finger check" on the Code and write the code as follows, what will happen?

          
           if ( i = 5 ) then  {    //    // do something...    //  }
          

    This mistake is a defect, but it can only be captured at runtime-it may take considerable debugging efforts to find it. The compiler will easily let go of your code. How can this error be prevented?

    Answer

    In fact, there are two answers: You can use a static code analysis tool described above and expect it to be robust enough to capture such errors, you can also switch the number of operations to make the constant on the left:

          
           if ( 5 == i ) then  {    //    // do something...    //  }
          

    This method ensures that you can capture problems immediately during code compilation, so it is the preferred technology. Although it looks stupid, the code can be compiled and run well. However, when you "Finger check" the code, you can immediately see the benefits:

          
           if ( 5 = i ) then  {    //    // do something...    //  }
          

    However, the compiler does not like this because 5 cannot be assigned to another value. This is what we said before that you should regard the compiler as your friend.

    You can also use this technique when checking the NULL pointer. See the following code:

          
           if ( returnString == null )  {    //    // do something...    //  }
          

    What happens if you accidentally write it as follows?

          
           if ( returnString = null )  {    //    // do something...    //  }
          

    You may not get the expected results. Using the following method, you will get the same "compiler protection" as we just described ":

          
           if ( null == returnString )  {    //    // do something...    //  }
          

    Conclusion

    To keep it concise, we have made a very concise induction: either do it now, or do it at a much higher cost in the future. In other words, the more time you spend in testing and Preventing code defects early in the development cycle, the more time and money you save in the future. This is the meaning of defensive encoding. It is so simple.

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.