Test.cs
上传用户:jingke1993
上传日期:2022-06-08
资源大小:140k
文件大小:24k
源码类别:

xml/soap/webservice

开发平台:

Visual C++

  1. using System;
  2. using System.Xml;
  3. using System.Collections;
  4. using System.IO;
  5. using System.Text;
  6. using System.Net;
  7. using System.Diagnostics;
  8. namespace Sgml
  9. {
  10. /// <summary>
  11. /// Summary description for Class1.
  12. /// </summary>
  13. class TestSuite
  14. {
  15.         
  16.         int tests = 0;
  17.         int passed = 0;
  18.         bool domain = false;
  19.         bool crawl = false;
  20.         bool debug = false;
  21.         bool basify = false;
  22.         bool testdoc = false;
  23.         bool teststream = false;
  24.         string proxy = null;
  25.         Encoding encoding = null;
  26.         string output = null;
  27.         bool formatted = false;
  28.         bool noxmldecl = false;
  29.         /// <summary>
  30. /// The main entry point for the application.
  31. /// </summary>
  32.         [STAThread]
  33.         static void Main(string[] args) {
  34.             TestSuite suite = new TestSuite();
  35.             suite.ParseCommandLine(args);
  36.             suite.Run();
  37.         }
  38.         void ParseCommandLine(string[] args) {
  39.             for (int i = 0; i < args.Length; i++){
  40.                 string arg = args[i];
  41.                 if (arg[0] == '-'){
  42.                     switch (arg.Substring(1)){
  43.                         case "debug":
  44.                             debug = true;
  45.                             break;
  46.                         case "base":
  47.                             basify = true;
  48.                             break;
  49.                         case "crawl":
  50.                             crawl = true;
  51.                             if (args[++i] == "domain")
  52.                                 domain = true;
  53.                             break;          
  54.                         case "testdoc":
  55.                             testdoc = true;
  56.                             break;
  57.                         case "teststream":
  58.                             teststream = true;
  59.                             break;
  60.                     }
  61.                 }
  62.             }
  63.         }
  64.         void Run(){
  65.             Uri baseUri = new Uri(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName);            
  66.             RunTest(baseUri, "..\..\html.suite");
  67.             RunTest(baseUri, "..\..\ofx.suite");
  68.             RegressionTest1();
  69.             return;       
  70.         }
  71.         void RunTest(Uri baseUri, string inputUri) {
  72.             Uri resolved = new Uri(baseUri, inputUri);
  73.             string path = resolved.LocalPath;
  74.             this.passed = 0;
  75.             this.tests = 0;
  76.             SgmlReader reader = new SgmlReader();
  77.             RunTest(reader, path);   
  78.                         
  79.             Console.WriteLine("{0} Tests passed", this.passed);
  80.             if (this.passed != this.tests) {
  81.                 Console.WriteLine("{0} Tests failed", this.tests-this.passed);
  82.             }
  83.             Console.WriteLine();
  84.             
  85.             return;
  86.         }
  87.        
  88.         /**************************************************************************
  89.          * Run a test suite.  Tests suites are organized into expected input/output
  90.          * blocks separated by back quotes (`).  It runs the input and compares it
  91.          * with the expected output and reports any failures.
  92.          **************************************************************************/
  93.         void RunTest(SgmlReader reader, string file) {
  94.             Console.WriteLine(file);
  95.             StreamReader sr = new StreamReader(file);
  96.             StringBuilder input = new StringBuilder();
  97.             StringBuilder expectedOutput = new StringBuilder();
  98.             StringBuilder current = null;
  99.             StringBuilder args = new StringBuilder();
  100.             Uri baseUri = new Uri(new Uri(Directory.GetCurrentDirectory()+"\"), file);
  101.             reader.SetBaseUri(baseUri.AbsoluteUri);
  102.             
  103.             int start = 1;
  104.             int line = 1;
  105.             int pos = 1;
  106.             bool skipToEOL = false;
  107.             bool readArgs = false;
  108.             int i;
  109.             do {
  110.                 i = sr.Read();
  111.                 char ch = (char)i;
  112.                 if (pos == 1 && ch == '`') {
  113.                     if (current == null) {
  114.                         current = input;
  115.                         current.Length = 0;
  116.                         readArgs = true;
  117.                     } else if (current == input) {
  118.                         current = expectedOutput;
  119.                     }
  120.                     else {
  121.                         RunTest(reader, start, args.ToString(), input.ToString(), expectedOutput.ToString());
  122.                         start = line;
  123.                         input.Length = 0;
  124.                         args.Length = 0;
  125.                         expectedOutput.Length = 0;
  126.                         current = input;
  127.                         readArgs = true;
  128.                     }
  129.                     skipToEOL = true;
  130.                 } else {
  131.                     if (current != null) {
  132.                         if (readArgs){
  133.                             args.Append(ch);
  134.                         } else if (!skipToEOL){
  135.                             current.Append(ch);
  136.                         }
  137.                     }
  138.                     if (ch == 'r') {
  139.                         line++; pos = 1;
  140.                         if (sr.Peek() == 'n') {
  141.                             i = sr.Read();
  142.                             if (!skipToEOL) current.Append((char)i);                            
  143.                             if (readArgs) args.Append(ch);
  144.                         }
  145.                         skipToEOL = false;
  146.                         readArgs = false;
  147.                     } else if (ch == 'n'){
  148.                         skipToEOL = false;
  149.                         readArgs = false;
  150.                         line++; pos = 1;
  151.                     }
  152.                 }
  153.             } while (i != -1);
  154.             if (current.Length>0 && expectedOutput.Length>0) {
  155.                 RunTest(reader, start, args.ToString(), input.ToString(), expectedOutput.ToString());
  156.             }
  157.         }
  158.         void RunTest(SgmlReader reader, int line, string args, string input, string expectedOutput){
  159.             bool testdoc = false;
  160.             foreach (string arg in args.Split(' ')){
  161.                 string sarg = arg.Trim();
  162.                 if (sarg.Length==0) continue;
  163.                 if (sarg[0] == '-'){
  164.                     switch (sarg.Substring(1)){
  165.                         case "html":
  166.                             reader.DocType = "html";
  167.                             break;
  168.                         case "lower":
  169.                             reader.CaseFolding = CaseFolding.ToLower;
  170.                             break;
  171.                         case "upper":
  172.                             reader.CaseFolding = CaseFolding.ToUpper;
  173.                             break;
  174.                         case "testdoc":
  175.                             testdoc = true;
  176.                             break;
  177.                     }
  178.                 }
  179.             }
  180.             this.tests++;
  181.             reader.InputStream = new StringReader(input);
  182.             reader.WhitespaceHandling = WhitespaceHandling.None;
  183.             StringWriter output = new StringWriter();
  184.             XmlTextWriter w = new XmlTextWriter(output);
  185.             w.Formatting = Formatting.Indented;
  186.             if (testdoc) {
  187.                 XmlDocument doc = new XmlDocument();
  188.                 doc.Load(reader);
  189.                 doc.WriteTo(w);
  190.             } else {
  191.                 reader.Read();
  192.                 while (!reader.EOF) {
  193.                     w.WriteNode(reader, true);
  194.                 }
  195.             }            
  196.             w.Close();
  197.             string actualOutput = output.ToString();
  198.             if (actualOutput.Trim() != expectedOutput.Trim()) {
  199.                 Console.WriteLine("ERROR: Test failed on line {0}", line);
  200.                 Console.WriteLine("---- Expected output");
  201.                 Console.WriteLine(expectedOutput);
  202.                 Console.WriteLine("---- Actual output");
  203.                 Console.WriteLine(actualOutput);
  204.             } else {
  205.                 this.passed++;
  206.             }
  207.         }
  208.         void Process(SgmlReader reader, string uri, bool loadAsStream) {   
  209.             if (uri == null) {
  210.                 reader.InputStream = Console.In;
  211.             } 
  212.             else if (loadAsStream) {
  213.                 Uri location = new Uri(uri);
  214.                 if (location.IsFile) {   
  215.                     reader.InputStream = new StreamReader(uri);
  216.                 } else {
  217.                     WebRequest wr = WebRequest.Create(location);
  218.                     reader.InputStream = new StreamReader(wr.GetResponse().GetResponseStream());
  219.                 }
  220.             } else {
  221.                 reader.Href = uri;
  222.             }
  223.             if (debug) {
  224.                 Debug(reader);
  225.                 reader.Close();
  226.                 return;
  227.             } 
  228.             if (crawl) {
  229.                 StartCrawl(reader, uri, basify);
  230.                 return;
  231.             } 
  232.             if (this.encoding == null) {
  233.                 this.encoding = reader.GetEncoding();
  234.             }
  235.             
  236.             XmlTextWriter w = null;
  237.             if (output != null) {
  238.                 w = new XmlTextWriter(output, this.encoding);          
  239.             } 
  240.             else {
  241.                 w = new XmlTextWriter(Console.Out);
  242.             }
  243.             if (formatted) w.Formatting = Formatting.Indented;
  244.             if (!noxmldecl) {
  245.                 w.WriteStartDocument();
  246.             }
  247.             if (testdoc) {
  248.                 XmlDocument doc = new XmlDocument();
  249.                 try {
  250.                     doc.Load(reader);
  251.                     doc.WriteTo(w);
  252.                 } catch (XmlException e) {
  253.                     Console.WriteLine("Error:" + e.Message);
  254.                     Console.WriteLine("at line " + e.LineNumber + " column " + e.LinePosition);
  255.                 }
  256.             } else {
  257.                 reader.Read();
  258.                 while (!reader.EOF) {
  259.                     w.WriteNode(reader, true);
  260.                 }
  261.             }
  262.             w.Flush();
  263.             w.Close();          
  264.         }
  265.         
  266.         /***************************************************************************
  267.         * Useful debugging code...
  268.         * **************************************************************************/
  269.         void StartCrawl(SgmlReader reader, string uri, bool basify) {      
  270.             Console.WriteLine("Loading '"+reader.BaseURI+"'");
  271.             XmlDocument doc = new XmlDocument();
  272.             try {         
  273.                 doc.XmlResolver = null; // don't do any downloads!
  274.                 doc.Load(reader);
  275.             } 
  276.             catch (Exception e) {
  277.                 Console.WriteLine("Error loading documentn"+e.Message);
  278.             }       
  279.             reader.Close();
  280.             if (basify) {
  281.                 // html and head are option, if they are there use them otherwise not.
  282.                 XmlElement be = (XmlElement)doc.SelectSingleNode("//base");
  283.                 if (be == null) {
  284.                     be = doc.CreateElement("base");
  285.                     be.SetAttribute("href", doc.BaseURI);
  286.                     XmlElement head = (XmlElement)doc.SelectSingleNode("//head");
  287.                     if (head != null) {
  288.                         head.InsertBefore(be, head.FirstChild);
  289.                     }
  290.                     else {
  291.                         XmlElement html = (XmlElement)doc.SelectSingleNode("//html");
  292.                         if (html != null) html.InsertBefore(be, html.FirstChild);
  293.                         else doc.DocumentElement.InsertBefore(be, doc.DocumentElement.FirstChild);
  294.                     }
  295.                 }
  296.             }
  297.             try {
  298.                 Crawl(reader.Dtd, doc, reader.ErrorLog);
  299.             } 
  300.             catch (Exception e) {
  301.                 Console.WriteLine("Uncaught exception: " + e.Message);
  302.             }
  303.         }
  304.         enum NodeTypeFlags {
  305.             None = 0,
  306.             Element = 0x1,
  307.             Attribute = 0x2,
  308.             Text = 0x4,
  309.             CDATA = 0x8,
  310.             EntityReference = 0x10,
  311.             Entity = 0x20,
  312.             ProcessingInstruction = 0x40,
  313.             Comment = 0x80,
  314.             Document = 0x100,
  315.             DocumentType = 0x200,
  316.             DocumentFragment = 0x400,
  317.             Notation = 0x800,
  318.             Whitespace = 0x1000,
  319.             SignificantWhitespace = 0x2000,
  320.             EndElement = 0x4000,
  321.             EndEntity = 0x8000,
  322.             filler = 0x10000,
  323.             XmlDeclaration = 0x20000,
  324.         }
  325.         NodeTypeFlags[] NodeTypeMap = new NodeTypeFlags[19] {
  326.                                                                 NodeTypeFlags.None,
  327.                                                                 NodeTypeFlags.Element,
  328.                                                                 NodeTypeFlags.Attribute,
  329.                                                                 NodeTypeFlags.Text,
  330.                                                                 NodeTypeFlags.CDATA,
  331.                                                                 NodeTypeFlags.EntityReference,
  332.                                                                 NodeTypeFlags.Entity,
  333.                                                                 NodeTypeFlags.ProcessingInstruction,
  334.                                                                 NodeTypeFlags.Comment,
  335.                                                                 NodeTypeFlags.Document,
  336.                                                                 NodeTypeFlags.DocumentType,
  337.                                                                 NodeTypeFlags.DocumentFragment,
  338.                                                                 NodeTypeFlags.Notation,
  339.                                                                 NodeTypeFlags.Whitespace,
  340.                                                                 NodeTypeFlags.SignificantWhitespace,
  341.                                                                 NodeTypeFlags.EndElement,
  342.                                                                 NodeTypeFlags.EndEntity,
  343.                                                                 NodeTypeFlags.filler,
  344.                                                                 NodeTypeFlags.XmlDeclaration,
  345.         };
  346.         void Debug(SgmlReader sr) {
  347.             NodeTypeFlags[] AllowedContentMap = new NodeTypeFlags[19] {
  348.                                                                           NodeTypeFlags.None, // none
  349.                                                                           NodeTypeFlags.Element | NodeTypeFlags.Attribute | NodeTypeFlags.Text | NodeTypeFlags.CDATA | NodeTypeFlags.EntityReference | NodeTypeFlags.ProcessingInstruction | NodeTypeFlags.Comment | NodeTypeFlags.Whitespace | NodeTypeFlags.SignificantWhitespace | NodeTypeFlags.EndElement, // element
  350.                                                                           NodeTypeFlags.Text | NodeTypeFlags.EntityReference, // attribute
  351.                                                                           NodeTypeFlags.None, // text
  352.                                                                           NodeTypeFlags.None, // cdata
  353.                                                                           NodeTypeFlags.None, // entity reference
  354.                                                                           NodeTypeFlags.None, // entity
  355.                                                                           NodeTypeFlags.None, // processing instruction
  356.                                                                           NodeTypeFlags.None, // comment
  357.                                                                           NodeTypeFlags.Comment | NodeTypeFlags.DocumentType | NodeTypeFlags.Element | NodeTypeFlags.EndElement | NodeTypeFlags.ProcessingInstruction | NodeTypeFlags.Whitespace | NodeTypeFlags.SignificantWhitespace | NodeTypeFlags.XmlDeclaration, // document
  358.                                                                           NodeTypeFlags.None, // document type
  359.                                                                           NodeTypeFlags.None, // document fragment (not expecting these)
  360.                                                                           NodeTypeFlags.None, // notation
  361.                                                                           NodeTypeFlags.None, // whitespace
  362.                                                                           NodeTypeFlags.None, // signification whitespace
  363.                                                                           NodeTypeFlags.None, // end element
  364.                                                                           NodeTypeFlags.None, // end entity
  365.                                                                           NodeTypeFlags.None, // filler
  366.                                                                           NodeTypeFlags.None, // xml declaration.
  367.             };
  368.             Stack s = new Stack();
  369.             while (sr.Read()) {
  370.                 if (sr.NodeType == XmlNodeType.EndElement) {
  371.                     s.Pop();
  372.                 }
  373.                 if (s.Count > 0) {
  374.                     XmlNodeType pt = (XmlNodeType)s.Peek();
  375.                     NodeTypeFlags p = NodeTypeMap[(int)pt];
  376.                     NodeTypeFlags f = NodeTypeMap[(int)sr.NodeType];
  377.                     if ((AllowedContentMap[(int)pt]& f) != f) {
  378.                         Console.WriteLine("Invalid content!!");
  379.                     }
  380.                 }
  381.                 if (s.Count != sr.Depth-1) {
  382.                     Console.WriteLine("Depth is wrong!");
  383.                 }
  384.                 if ( (sr.NodeType == XmlNodeType.Element && !sr.IsEmptyElement) ||
  385.                     sr.NodeType == XmlNodeType.Document) {
  386.                     s.Push(sr.NodeType);
  387.                 }
  388.                 for (int i = 1; i < sr.Depth; i++) 
  389.                     Console.Write("  ");
  390.                 Console.Write(sr.NodeType.ToString() + " " + sr.Name);
  391.                 if (sr.NodeType == XmlNodeType.Element && sr.AttributeCount > 0) {
  392.                     sr.MoveToAttribute(0);
  393.                     Console.Write(" (" + sr.Name+"="+sr.Value + ")");
  394.                     sr.MoveToElement();
  395.                 }       
  396.                 if (sr.Value != null) {
  397.                     Console.Write(" " + sr.Value.Replace("n"," ").Replace("r",""));
  398.                 }
  399.                 Console.WriteLine();
  400.             }
  401.         }
  402.         int depth = 0;
  403.         int count = 0;
  404.         Hashtable visited = new Hashtable();
  405.         bool Crawl(SgmlDtd dtd, XmlDocument doc, TextWriter log) {
  406.             depth++;
  407.             StringBuilder indent = new StringBuilder();
  408.             for (int i = 0; i < depth; i++)
  409.                 indent.Append(" ");
  410.       
  411.             count++;
  412.             Uri baseUri = new Uri(doc.BaseURI);
  413.             XmlElement baseElmt = (XmlElement)doc.SelectSingleNode("/html/head/base");
  414.             if (baseElmt != null) {
  415.                 string href = baseElmt.GetAttribute("href");
  416.                 if (href != "") {
  417.                     try {
  418.                         baseUri = new Uri(href);
  419.                     }
  420.                     catch (Exception ) {
  421.                         Console.WriteLine("### Error parsing BASE href '"+href+"'");
  422.                     }
  423.                 }
  424.             }
  425.             foreach (XmlElement a in doc.SelectNodes("//a")) {
  426.                 string href = a.GetAttribute("href");
  427.                 if (href != "" && href != null && depth<5) {
  428.                     Uri local = new Uri(baseUri, href);
  429.                     if (domain && baseUri.Host != local.Host)
  430.                         continue;
  431.                     string ext = Path.GetExtension(local.AbsolutePath).ToLower();
  432.                     if (ext == ".jpg" || ext == ".gif" || ext==".mpg")
  433.                         continue;
  434.                     string url = local.AbsoluteUri;
  435.                     if (!visited.ContainsKey(url)) {
  436.                         visited.Add(url, url);
  437.                         log.WriteLine(indent+"Loading '"+url+"'");
  438.                         log.Flush();
  439.                         StreamReader stm = null;
  440.                         try {
  441.                             HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);
  442.                             wr.Timeout = 10000; 
  443.                             if (proxy != null) wr.Proxy = new WebProxy(proxy);
  444.                             wr.PreAuthenticate = false; 
  445.                             // Pass the credentials of the process. 
  446.                             wr.Credentials = CredentialCache.DefaultCredentials; 
  447.                             WebResponse resp = wr.GetResponse();
  448.                             Uri actual = resp.ResponseUri;
  449.                             if (actual.AbsoluteUri != url) {
  450.                                 local = new Uri(actual.AbsoluteUri);
  451.                                 log.WriteLine(indent+"Redirected to '"+actual.AbsoluteUri+"'");
  452.                                 log.Flush();
  453.                             }           
  454.                             if (resp.ContentType != "text/html") {
  455.                                 log.WriteLine(indent+"Skipping ContentType="+resp.ContentType);
  456.                                 log.Flush();
  457.                                 resp.Close();
  458.                             } 
  459.                             else {
  460.                                 stm = new StreamReader(resp.GetResponseStream());
  461.                             }
  462.                         } 
  463.                         catch (Exception e) {
  464.                             log.WriteLine(indent+"### Error opening URL: " + e.Message);
  465.                             log.Flush();
  466.                         }
  467.                         if (stm != null) {
  468.                             SgmlReader reader = new SgmlReader();
  469.                             reader.Dtd = dtd;
  470.                             reader.SetBaseUri(local.AbsoluteUri);
  471.                             reader.InputStream = stm;
  472.                             reader.WebProxy = proxy;
  473.                             XmlDocument d2 = new XmlDocument();
  474.                             d2.XmlResolver = null; // don't do any downloads!
  475.                             try {
  476.                                 d2.Load(reader);
  477.                                 reader.Close();
  478.                                 stm.Close();
  479.                                 if (!Crawl(dtd, d2, log))
  480.                                     return false;
  481.                             } 
  482.                             catch (Exception e) {
  483.                                 log.WriteLine(indent+"### Error parsing document '"+local.AbsoluteUri+"', "+e.Message);
  484.                                 log.Flush();
  485.                                 reader.Close();
  486.                             }
  487.                         }
  488.                     }
  489.                 }
  490.             }
  491.             depth--;
  492.             return true;
  493.         }
  494.         void RegressionTest1() {
  495.             // Make sure we can do MoveToElement after reading multiple attributes.
  496.             SgmlReader r = new SgmlReader();
  497.             r.InputStream = new StringReader("<test id='10' x='20'><a/><!--comment-->test</test>");
  498.             if (r.Read()) {
  499.                 while (r.MoveToNextAttribute()) {
  500.                     Trace.WriteLine(r.Name);
  501.                 }
  502.                 if (r.MoveToElement()) {
  503.                     Trace.WriteLine(r.ReadInnerXml());
  504.                 }
  505.             }
  506.         }
  507. }
  508. }