2013/03/25

The UNIT TEST unit test in Visual Studio


TDD (Test-Driven Development) test-driven development is a core agile development practices and technologies, is also a kind of design methodology. The principle of TDD is the first writing unit test cases before development function code, code, test code to determine what you need to write the product code. Unit testing is the most basic test steps. Located in the very bottom of the V-model of the entire product development process.
Approximately as in various development processes RA & PSD is complete without the underlying foundation, UAT program to complete the following steps. UT as the bottom and CODING equally important step is the basis of each CODER must master.

RA( Requirement Analysis)  &
PSD ( Productive Specification Design)              UAT( User Acceptance Testing)
                          \                                                              /
                            \                                                          /
                              \                                                      /
FSD(Functional Specification Design)             SIT(System Integration Testing)
                                \                                                 /
                                  \                                             /
                                    \                                         /
                           Construction(Coding)         UT(Unit Tesing)
                                         \                              /
                                            \                         /
                                                \                   /
                                                  \              /
                                                     \         /
                                                        \    /
                                                          \/

Create a new console project (Console Application) in the small amount of code to write, often by New Web Site Project (Web Form), in which typing test code to test. Once the amount of code and logical relations are complicated, this test will be difficult to carry out, and do not have the maintainability. And many functional code can not be completely divorced from the entire project. Such as a class library in a web project, write some MODEL layer To test the method, in order to verify the correctness of the method may have reference to the project model, interface, and library functions. Wait until the can by the compiler, but found you must be logged in to call the method or your directory (Directory) does not have the access rights, so he had to modify the Authorization configuration or add a login method. So layers down your test project involving almost every corner of the test program without a high degree of reusability.
Here we VS2012 example, look at how unit tests in Visual Studio.


1, right-click the solution (Solution) to pop up the context menu (Context). Select Add (Add) - a new project (New Project), in a given template, select Visual C # - Test-Unit Test Project As.

2. Template As.
3.The test method (here the default TestMethod1, general amended as the need to test the method name + Test) add the need to test their own code. But before this, we must first reference to the need to test the project as well as the need to use the class library. In this example, I quote Microsoft MVC4.0 framework, as well as the need to test the project Controller. I test the the Controller ProductCategories () method. The method returns a The ActionResult. 3 lines of test code, the first line to a instantiate the controller, the second line calls the controller method. If only the 2 line test is passed, then the code without problems of syntax, and other parts work together. The third row with an assertion to detect method returns the result is empty. Here I assert that it is not empty, an error if it is empty, the test will fail.
4,The test code is written, you can click on the the above menu Test-Run-AllTests, to carry out the test.。
After the test is completed. Below will produce a list of results. Red for failed TestCase. If you want to be the DEBUG Right-click the red TestCase, select Debug selected Tests. Modifications, can also right-click you want to re-test TestCase, select Run the Selected Tests.

2013/03/24

Control of the entire page cache and update dynamic pages as static pages




Static pages we all know, WEB server sends back the contents of the file comes with a Last-Modified header information, and static files last modification time stored inside, so that when the next time the browser requests the file will get Last -Modified header information exists with the If-Modified-Since sent to the server, telling the server's local cache last modification time, will first determine the end of the file when the server receives the time information of the If-Modified-Since request modify the time is later than this time, the late update, will retransmission of the contents of the file, along with the latest Last-Modified header information to the client, if the time is equal to or more than this time early, it shows no update cache fully synchronized, it will send back a 304 Not Modified status code, and to stop retransmission file content, and can save unnecessary data transmission.
Above is a static page cache and update the control mechanism, generally all this is by the WEB server directly arranged deal, all without user intervention. Dynamic pages are not so lucky, because of the dynamic page requests are forwarded by the WEB server to a specific page handler to complete their cache and update the strategic issues, and not arranged, so these controls must programmers to complete. Unfortunately, however, the dynamic page handler is unable to automatically handle cache is a whole page-level cache, we can cache a variable in the code so that at the next call, but still a lot of code to be executed, they can as static pages to the client a Last-Modified header information, determine the time and data updated when the next request, in order to decide whether to repeat the process and send data?

From the above analysis it is entirely feasible, but it needs to do special processing script, which is a logic to regulate this update detection, of course, this is not the focus on this. Because the the client to accept last modified time to completely rely on the Last-Modified header information, so dynamic scripting can be sent back to the content is also output a time as a basis to judge, then the next time the client requests the same page (accurately, should with a URL address), Last-Modified header information received will be appended to the If-Modified-Since request over. To a dynamic page here, we can get included with the request last modify time, then the first judgment point in time whether there is a new deal with the data, there is no new data, then, we are on the direct end of the current script, you can save server resources. Of course, before the end of the script, you need to play a 304 status code, because let clients sure to use the cache, must also be dependent on the status code, so just use dynamic script sends back a 304 Not Modified header information can not only saving server script execution resources, but also save the flow can be described as killing two birds with one stone, and the application form is more flexible and more controllable.


How to speed up the pages open faster?



Recently saw a question on how to quickly open the site, I briefly summarize the impact website open speed 3 reasons (the question of the physical line that is unable to avoid random problems can not be solved).

The client browser is the most direct impact label rendering speed involve speed, CSS rendering speed, scripts, and dynamic function of the amount of resource consumption. The label different rendering speed different, why people like DIV + CSS layout, form rendering in the number of nested multi slow, because the table is the basis of the framework, but rendering when he needs to first total size and the size of each cell is calculated based on the contents of the table cell, and then began to render, so the speed will be slower. Like a stage curtain, we always first curtain pulled down, and then wait for after the actor came to power to adjust the position until their positions before we pull opening, so that the actor lineup once to show to the audience, but the audience face monotonous curtain waiting long time. So to minimize the use of rendering slow the label, and as far as possible the direct definition of label size, rendering computation time savings. Then there are some very important CSS or filter function expression evaluates to try to ensure that in the case of less resource consumption, the script of this principle, and save resources.

2 network at the same time the number of concurrent to reduce, and as far as possible to reduce the amount of time transmission of data. Small icon file, can be taken in the form of merger into a larger image, once direct re-completed, then the client is displayed using CSS positioning cuts part of the need to show up, thereby reducing the number of simultaneous requests. Reduce the amount of data, such as take CSS overall definition the rendering style, try not specific to each label style set, you can save a lot of code. Such as data transmission using JSON way, will save a lot of code than XML, in a page, and try not to additional references never use JS script, some large-scale repetitive regularity label rendering try using JS code to complete, more codes can be saved, and in short, the fundamental principle is to use as little as possible the amount of data to transmit as much information as possible.

3, the server is the design of the program, to avoid logic errors caused infinite loop like resources occupied, try not handle cases promptly shut down, in order to avoid unnecessary idle resources occupied wasted This is relatively simple, here is not to expand that.


IIS hidden folder can not be applied to the default Home


Configured IIS site, in order to prevent the home directory of the user accidentally deleted ASP script, deliberately set the directory hidden attribute, access to the directory hierarchy results prompted 404 error, I thought insufficient permissions to the folder, modify the permissions improve IISaccount permissions to modify the default home once again. The result was 404, obviously Home in there why not find it? Home and assigned to a specific file name, the page is normal, normal access can not find is the default home page. Then suddenly think, is not a folder hidden attribute result, so quickly unhide property, now no problem.
It seems windows folder attributes IIS still has some influence.


Interaction type page to prevent IP spoofing techniques



Many interactive web pages, such as online voting, online answer, online surveys and online sweepstakes, in general, will be the user's IP as restrictions, limiting the number of users to participate in activities of the same IP.

        Network popular with many of the so-called take real client IP code, nothing less than the origin are by checking the agency to obtain the so-called "real IP, but the IP is really" real "? I do not think such practices seem to have some smart anti cleverness.

        As we all know, web access protocol is HTTP, the communication process in this agreement, almost no credible data. The reason I say that is because all of the HTTP protocol data are forged, and the only real request page direct client IP. This IP REMOTE_ADDR to get through the HTTP environment variable, which can be said is the only credible address data, while the other two environment variables HTTP_CLIENT_IP HTTP_X_FORWARDED_FOR indicates proxy source path IP, but unfortunately, these data are not reliable, unless you are sure that the proxy server is reliable, but this is almost impossible.

        Here, in the end how to obtain more reliable client IP before, my point is REMOTE_ADDR to the direct request of the IP source, because it is the only reliable data. If we trust In addition, two proxy server IP information using the so-called popular on the network to take a real IP? The result is very bad, we will easily be hackers forged proxy antecedents IP, then maxed out the results of our voting data.

        So, when the need to determine and limit IP, do not consider the so-called proxy IP, those are clouds, there is no reliable information to prevent IP spoofing fly can only rely on the detection of direct access to the address.




Instead of cumbersome inefficient use of PHP5's __autoload the external file containing the way

Generally written PHP code comrades, may file contains commands include, include_once, require, require_once familiar. Although these commands has played an important role for us to re-use the same code, but as the file be included, as well as the interaction between the include file contains the entire PHP application contains relations intricate. And there is a very inefficient, we write a PHP page may have to go hand-written code contains external public documents to be used eleven, and once the project becomes huge, modify the include file references will become a headache, because we must first know where references an external file, we can modify. Fortunately, with the release of PHP5 to a new function __ autoload entrance parameter is the name of the class is not defined. If we declare this function in your own code, it will be called automatically when you attempt to use the class has not yet been defined. By calling this function the scripting engine in PHP error class load required given a last chance before the failure. Here we should be able to think of, we can take advantage of this new feature, coupled with the use of object-oriented programming, we need to refer to external public code are encapsulated into a class inside the storage to the same as the class name file to the automatic loading function is triggered, we can directly contain PHP file with the name of the class, you can achieve the dynamic loading of external files. So we write code, you do not need to advance include external files, but also to achieve the object-oriented programming model, a page to the introduction of new classes only need to directly instantiate the class can, PHP accordance with __autoload the definition automatically go call the external file. Modifications and extensions is easy, as long as we have the class definition and maintenance on it. And even called among multiple classes and instances, without first contains the introduction, as long as the main code __autoload function declaration and the class definition file storage is handled in strict accordance with the rules, then calling each other between classes. and instantiation will auto-complete, which we will be able to rid itself of the original kind of cumbersome and inefficient external file contains way. Now I give you a simple piece of sample code, as long as the definition of a good external class file naming and storage rules, can facilitate the use of this fully automated external file contains. say ();  ?>      / / Inc / demo.php class definition example  

ruby + watir - random rather than obtain duplicate the Menu menu of elements

Test case: using a loop, random to get nine Menu menu, each must click and verify: def channel @b.goto URL channel = 0 while channel <= 8 times = rand(9).to_s AutoTest("channel_#{times}_link").click sleep 1 assert_true(AutoTest("channel_#{times}_link_on").exists?) channel += 1 end end Cycle nine times in the script, to take a random value every time, random number rand () is 0, so I element defines 0 of these nine elements of the Menu menu coding, such as: channel_0_link. But there is a problem rand () function take duplicate values​​, that some Menu menu click on 2 or more times, which our barge. I almost hunted API is not found without repeated sequentially or randomly. Next, I decided to use another random method to solve, in fact, random play is divided into two types, random and shuffle。 def channel_food @b.goto URL linkid=[0,1,2,3,4,5,6,7,8] linkid.shuffle.each{ |i| times = i AutoTest("channel_#{times}_link").click sleep 1 assert_true(AutoTest("channel_#{times}_link_on").exists?) } end The above code, can achieve randomized to get nine Menu menu, each must click and verify demand. each method is to get the data from the array; shuffle method to obtain the value of the re-arranged to use this method to do the shuffle program (does not generate repeat). a=[1,2,3,4,5,6,7,8,9] a.shuffle.each{ |i| b = i puts b }