Software Carpentry
Web Server Programming


You Can Skip This Lecture If...

The Pluggable Web

The CGI Protocol

From Server To CGI

From CGI To Server

MIME Types

Hello, CGI

Invoking a CGI

Generating Dynamic Content


Creating Forms

A Simple Form

Parameter Names

Handling Forms

Form Handling Example

Development Tips

Maintaining State

Maintaining State in Files

HTML Generation

HTML Templating

What About Concurrency?

File Locking

Implementing Locking

Who Are You?


Creating Cookies

Cookie Example

Cookie Tips



Exercise 24.1:

One way to test a CGI application is to send it HTTP requests, and examine the responses. Write a program that takes a hostname, port, and partial URL as command-line parameters, and sends the URL to the server identified by the hostname and port. The program should display the status code, reason, headers, and response page (if any) that are returned by the web server.

For example, if your program is run as httptest localhost 80 /greeting.html, it should send a request for /greeting.html to a web server running on port 80 on the local machine, and display something like:

        content-length [49]
        server ['Apache/2.0.54 (Debian GNU/Linux) DAV/2 SVN/1.1.4 mod_python/3.1.3 Python/2.3.5]
        last-modified ['Wed, 19 Apr 2006 13:59:19 GMT']
        date ['Sun, 30 Apr 2006 14:12:13 GMT']
        content-type ['text/html']
        <h1>Hello, CGI!</h1>

What are the pros and cons of testing a CGI application this way?

Exercise 24.2:

Another way to test a CGI application is to construct a mock container to take the place of the web server. As described in the lecture, CGI applications read data from environment variables and standard input; by using the subprocess module described in the integration lecture, you can run the CGI yourself, passing it whatever test data you want. Write a program that does this. (For bonus marks, explain how you would test the mock container…)

Exercise 24.3:

The third way to test a CGI application is to construct a mock container that calls the CGI directly, rather than creating a new process and passing it data through environment variables and standard input. In order for this to work, the CGI program must import specially-crafted versions of the sys and os libraries that provide the CGI with data from the testing program, rather than reading it from the real sources:

if testing:
    import test_sys as sys
    import test_os as os
    import sys, os

What other changes must be made to the CGI application to allow it to be tested this way? What are the pros and cons of making such changes?

Send comments