Bug 1238507 - Convert necko test binaries to cppunittests r?mcmanus draft
authorValentin Gosu <valentin.gosu@gmail.com>
Mon, 11 Jan 2016 13:01:43 +0100
changeset 320454 960cc093aee0915443a257f4e401f69c699d78ab
parent 318937 29258f59e5456a1a518ccce6b473b50c1173477e
child 512739 29f3c6bf594dff769aac4030e82136d11fdcba50
push id9194
push uservalentin.gosu@gmail.com
push dateMon, 11 Jan 2016 12:02:10 +0000
reviewersmcmanus
bugs1238507
milestone46.0a1
Bug 1238507 - Convert necko test binaries to cppunittests r?mcmanus - TestServ now includes code copied over from TestStreamLoader, to test the server unattended - Tests may still take optional command line arguments, if we wish to run them manually
netwerk/test/PropertiesTest.cpp
netwerk/test/TestServ.cpp
netwerk/test/TestStandardURL.cpp
netwerk/test/moz.build
testing/cppunittest.ini
--- a/netwerk/test/PropertiesTest.cpp
+++ b/netwerk/test/PropertiesTest.cpp
@@ -1,14 +1,16 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "TestCommon.h"
+#include "TestHarness.h"
+
 #include "mozilla/Snprintf.h"
 #include "nsXPCOM.h"
 #include "nsStringAPI.h"
 #include "nsIPersistentProperties2.h"
 #include "nsIServiceManager.h"
 #include "nsIComponentRegistrar.h"
 #include "nsIURL.h"
 #include "nsNetCID.h"
@@ -25,46 +27,43 @@
 #define TEST_URL "resource:/res/test.properties"
 static NS_DEFINE_CID(kPersistentPropertiesCID, NS_IPERSISTENTPROPERTIES_CID);
 
 /***************************************************************************/
 
 int
 main(int argc, char* argv[])
 {
-  if (test_common_init(&argc, &argv) != 0)
+  ScopedXPCOM xpcom("PropertiesTest");
+  if (xpcom.failed())
     return -1;
 
   nsresult ret;
-
-  nsCOMPtr<nsIServiceManager> servMan;
-  NS_InitXPCOM2(getter_AddRefs(servMan), nullptr, nullptr);
-
-  nsIInputStream* in = nullptr;
+  nsCOMPtr<nsIInputStream> in;
 
   nsCOMPtr<nsIScriptSecurityManager> secman =
     do_GetService(NS_SCRIPTSECURITYMANAGER_CONTRACTID, &ret);
   if (NS_FAILED(ret)) return 1;
   nsCOMPtr<nsIPrincipal> systemPrincipal;
     ret = secman->GetSystemPrincipal(getter_AddRefs(systemPrincipal));
    if (NS_FAILED(ret)) return 1;
 
   nsCOMPtr<nsIURI> uri;
   ret = NS_NewURI(getter_AddRefs(uri), NS_LITERAL_CSTRING(TEST_URL));
   if (NS_FAILED(ret)) return 1;
 
-  nsIChannel *channel = nullptr;
-  ret = NS_NewChannel(&channel,
+  nsCOMPtr<nsIChannel> channel;
+  ret = NS_NewChannel(getter_AddRefs(channel),
                       uri,
                       systemPrincipal,
                       nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL,
                       nsIContentPolicy::TYPE_OTHER);
   if (NS_FAILED(ret)) return 1;
 
-  ret = channel->Open2(&in);
+  ret = channel->Open2(getter_AddRefs(in));
   if (NS_FAILED(ret)) return 1;
 
   nsIPersistentProperties* props;
   ret = CallCreateInstance(kPersistentPropertiesCID, &props);
   if (NS_FAILED(ret) || (!props)) {
     printf("create nsIPersistentProperties failed\n");
     return 1;
   }
--- a/netwerk/test/TestServ.cpp
+++ b/netwerk/test/TestServ.cpp
@@ -1,59 +1,95 @@
 /* vim:set ts=4 sw=4 et cindent: */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "TestCommon.h"
+#include "TestHarness.h"
+
 #include <stdlib.h>
 #include "nsIServiceManager.h"
 #include "nsIServerSocket.h"
 #include "nsISocketTransport.h"
 #include "nsIInputStream.h"
 #include "nsIOutputStream.h"
 #include "nsNetCID.h"
 #include "nsComponentManagerUtils.h"
 #include "nsStringAPI.h"
 #include "nsCOMPtr.h"
-#include "mozilla/Logging.h"
+
+#include "nsNetUtil.h"
+#include "nsServiceManagerUtils.h"
+#include "nsThreadUtils.h"
+#include "mozilla/Attributes.h"
+#include "nsIScriptSecurityManager.h"
+
+class MyStreamLoaderObserver final : public nsIStreamLoaderObserver
+{
+  ~MyStreamLoaderObserver() {}
+
+public:
+  NS_DECL_ISUPPORTS
+  NS_DECL_NSISTREAMLOADEROBSERVER
+};
 
-//
-// set NSPR_LOG_MODULES=Test:5
-//
-static PRLogModuleInfo *gTestLog = nullptr;
-#define LOG(args) MOZ_LOG(gTestLog, mozilla::LogLevel::Debug, args)
+NS_IMPL_ISUPPORTS(MyStreamLoaderObserver, nsIStreamLoaderObserver)
+
+NS_IMETHODIMP
+MyStreamLoaderObserver::OnStreamComplete(nsIStreamLoader *loader,
+                                         nsISupports     *ctxt,
+                                         nsresult         status,
+                                         uint32_t         resultLen,
+                                         const uint8_t   *result)
+{
+  printf("OnStreamComplete [status=%x resultLen=%u]\n", status, resultLen);
+
+  nsCOMPtr<nsIRequest> request;
+  loader->GetRequest(getter_AddRefs(request));
+  printf("  request=%p\n", request.get());
+
+  QuitPumpingEvents();
+  return NS_OK;
+}
 
 class MySocketListener : public nsIServerSocketListener
 {
 protected:
     virtual ~MySocketListener() {}
 
 public:
     NS_DECL_THREADSAFE_ISUPPORTS
     NS_DECL_NSISERVERSOCKETLISTENER
 
-    MySocketListener() {}
+    MySocketListener(int32_t aRequestLimit)
+        : mRequestLimit(aRequestLimit)
+        , mRequestCount(0)
+    {
+    }
+private:
+    int32_t mRequestLimit;
+    int32_t mRequestCount;
 };
 
 NS_IMPL_ISUPPORTS(MySocketListener, nsIServerSocketListener)
 
 NS_IMETHODIMP
 MySocketListener::OnSocketAccepted(nsIServerSocket *serv,
                                    nsISocketTransport *trans)
 {
-    LOG(("MySocketListener::OnSocketAccepted [serv=%p trans=%p]\n", serv, trans));
+    printf("MySocketListener::OnSocketAccepted [serv=%p trans=%p]\n", serv, trans);
 
     nsAutoCString host;
     int32_t port;
 
     trans->GetHost(host);
     trans->GetPort(&port);
 
-    LOG(("  -> %s:%d\n", host.get(), port));
+    printf("  -> %s:%d\n", host.get(), port);
 
     nsCOMPtr<nsIInputStream> input;
     nsCOMPtr<nsIOutputStream> output;
     nsresult rv;
 
     rv = trans->OpenInputStream(nsITransport::OPEN_BLOCKING, 0, 0, getter_AddRefs(input));
     if (NS_FAILED(rv))
         return rv;
@@ -71,76 +107,132 @@ MySocketListener::OnSocketAccepted(nsISe
 
     const char response[] = "HTTP/1.0 200 OK\r\nContent-Type: text/plain\r\n\r\nFooooopy!!\r\n";
     rv = output->Write(response, sizeof(response) - 1, &n);
     if (NS_FAILED(rv))
         return rv;
 
     input->Close();
     output->Close();
+
+    mRequestCount++;
+    if (mRequestLimit > 0 && mRequestCount >= mRequestLimit) {
+        serv->Close();
+    }
+
     return NS_OK;
 }
 
 NS_IMETHODIMP
 MySocketListener::OnStopListening(nsIServerSocket *serv, nsresult status)
 {
-    LOG(("MySocketListener::OnStopListening [serv=%p status=%x]\n", serv, status));
-    QuitPumpingEvents();
+    printf("MySocketListener::OnStopListening [serv=%p status=%x]\n", serv, status);
     return NS_OK;
 }
 
 static nsresult
-MakeServer(int32_t port)
+MakeServer(int32_t port, int32_t requestLimit)
 {
     nsresult rv;
     nsCOMPtr<nsIServerSocket> serv = do_CreateInstance(NS_SERVERSOCKET_CONTRACTID, &rv);
     if (NS_FAILED(rv))
         return rv;
 
     rv = serv->Init(port, true, 5);
     if (NS_FAILED(rv))
         return rv;
 
     rv = serv->GetPort(&port);
     if (NS_FAILED(rv))
         return rv;
-    LOG(("  listening on port %d\n", port));
+    printf("  listening on port %d\n", port);
+
+    rv = serv->AsyncListen(new MySocketListener(requestLimit));
+    return rv;
+}
+
+int
+test_streamLoader()
+{
+    nsresult rv;
+    nsCOMPtr<nsIURI> uri;
+    rv = NS_NewURI(getter_AddRefs(uri), nsDependentCString("http://localhost:9999"));
+    if (NS_FAILED(rv))
+      return -1;
+
+    nsCOMPtr<nsIScriptSecurityManager> secman =
+      do_GetService(NS_SCRIPTSECURITYMANAGER_CONTRACTID, &rv);
+    NS_ENSURE_SUCCESS(rv, -1);
+       nsCOMPtr<nsIPrincipal> systemPrincipal;
+    rv = secman->GetSystemPrincipal(getter_AddRefs(systemPrincipal));
+    NS_ENSURE_SUCCESS(rv, -1);
 
-    rv = serv->AsyncListen(new MySocketListener());
-    return rv;
+    nsCOMPtr<nsIChannel> chan;
+    rv = NS_NewChannel(getter_AddRefs(chan),
+                       uri,
+                       systemPrincipal,
+                       nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_DATA_INHERITS,
+                       nsIContentPolicy::TYPE_OTHER);
+
+    if (NS_FAILED(rv))
+      return -1;
+
+    nsCOMPtr<nsIStreamLoaderObserver> observer = new MyStreamLoaderObserver();
+    if (!observer)
+      return -1;
+
+    nsCOMPtr<nsIStreamLoader> loader;
+    rv = NS_NewStreamLoader(getter_AddRefs(loader), observer);
+    if (NS_FAILED(rv))
+      return -1;
+
+    rv = chan->AsyncOpen2(loader);
+    if (NS_FAILED(rv))
+      return -1;
+
+    return 0;
 }
 
 int
 main(int argc, char* argv[])
 {
-    if (test_common_init(&argc, &argv) != 0)
+    // ./TestServ [port]
+    // If run without arguments it will create a server on port 9999 and
+    // open a connection to it. The server will then be closed.
+    // If given an argument, it will create a server and run indefinitely
+    nsresult rv;
+
+    ScopedXPCOM xpcom("Test Serv");
+    if (xpcom.failed())
         return -1;
 
-    nsresult rv= (nsresult)-1;
-    if (argc < 2) {
-        printf("usage: %s <port>\n", argv[0]);
-        return -1;
-    }
+    {
+        int port = 9999;
+        int requestLimit = 1;
 
-    gTestLog = PR_NewLogModule("Test");
+        if (argc > 1) {
+            port = atoi(argv[1]);
+            // Unlimited requests if run manually
+            requestLimit = 0;
+        }
 
-    /* 
-     * The following code only deals with XPCOM registration stuff. and setting
-     * up the event queues. Copied from TestSocketIO.cpp
-     */
+        rv = MakeServer(port, requestLimit);
+        if (NS_FAILED(rv)) {
+            printf("MakeServer failed [rv=%x]\n", rv);
+            return -1;
+        }
 
-    rv = NS_InitXPCOM2(nullptr, nullptr, nullptr);
-    if (NS_FAILED(rv)) return -1;
-
-    {
-        rv = MakeServer(atoi(argv[1]));
-        if (NS_FAILED(rv)) {
-            LOG(("MakeServer failed [rv=%x]\n", rv));
-            return -1;
+        if (argc == 1) {
+            // If this is an automated test,
+            // we test the server by opening a connection.
+            if (test_streamLoader()) {
+                return -1;
+            }
         }
 
         // Enter the message pump to allow the URL load to proceed.
         PumpEvents();
     } // this scopes the nsCOMPtrs
-    // no nsCOMPtrs are allowed to be alive when you call NS_ShutdownXPCOM
-    NS_ShutdownXPCOM(nullptr);
+
+    printf("success\n");
+
     return 0;
 }
--- a/netwerk/test/TestStandardURL.cpp
+++ b/netwerk/test/TestStandardURL.cpp
@@ -1,37 +1,39 @@
 #include <stdio.h>
 #include <stdlib.h>
 
 #include "TestCommon.h"
+#include "TestHarness.h"
+
 #include "nsCOMPtr.h"
 #include "nsIServiceManager.h"
 #include "nsNetCID.h"
 #include "nsIURL.h"
 #include "prinrval.h"
 #include "nsStringAPI.h"
 #include "nsComponentManagerUtils.h"
 
 static nsIURL     *test_url = 0;
-static nsCString   test_param;
+static nsCString   test_spec;
 
 static void run_test(const char *testname, int count, void (* testfunc)())
 {
     PRIntervalTime start, end;
     start = PR_IntervalNow();
     for (; count; --count)
         testfunc();
     end = PR_IntervalNow();
     printf("completed %s test in %u milliseconds\n", testname,
             PR_IntervalToMilliseconds(end - start));
 }
 
 static void set_spec_test()
 {
-    test_url->SetSpec(test_param);
+    test_url->SetSpec(test_spec);
 }
 
 static void get_spec_test()
 {
     nsAutoCString spec;
     test_url->GetSpec(spec);
 }
 
@@ -84,38 +86,39 @@ static void ref_test()
     nsAutoCString ref;
     test_url->GetRef(ref);
     test_url->SetRef(NS_LITERAL_CSTRING("#some-book-mark"));
     test_url->SetRef(ref);
 }
 
 int main(int argc, char **argv)
 {
-    if (test_common_init(&argc, &argv) != 0)
-        return -1;
+    // usage: TestStandardURL [url] [count]
 
-    if (argc < 2) {
-        printf("usage: TestURL url [count]\n");
+    ScopedXPCOM xpcom("TestStandardURL");
+    if (xpcom.failed()) {
         return -1;
     }
 
     int count = 1000;
-    if (argc == 3)
+    test_spec = "http://example.com";
+
+    if (argc > 1) {
+        test_spec = argv[1];
+    }
+    if (argc > 2) {
         count = atoi(argv[2]);
-    else
-        printf("using a default count of %d\n", count);
+    }
 
     nsCOMPtr<nsIURL> url( do_CreateInstance(NS_STANDARDURL_CONTRACTID) );
     if (!url) {
         printf("failed to instantiate component: %s\n", NS_STANDARDURL_CONTRACTID);
         return -1;
     }
-
     test_url = url;
-    test_param = argv[1];
 
     run_test("SetSpec", count, set_spec_test);
     run_test("GetSpec", count, get_spec_test);
     run_test("Resolve", count, resolve_test);
     run_test("SetScheme", count, set_scheme_test);
     run_test("GetScheme", count, get_scheme_test);
     run_test("[GS]etHost", count, host_test);
     run_test("SetPath", count, set_path_test);
--- a/netwerk/test/moz.build
+++ b/netwerk/test/moz.build
@@ -11,25 +11,22 @@ MOCHITEST_MANIFESTS += ['mochitests/moch
 
 XPCSHELL_TESTS_MANIFESTS += [
     'unit/xpcshell.ini',
     'unit/xpcshell_b2g.ini',
     'unit_ipc/xpcshell.ini',
 ]
 
 GeckoSimplePrograms([
-    'PropertiesTest',
     'ReadNTLM',
     'TestBlockingSocket',
     'TestDNS',
     'TestIncrementalDownload',
     'TestOpen',
     'TestProtocols',
-    'TestServ',
-    'TestStandardURL',
     'TestStreamLoader',
     'TestUpload',
     'TestURLParser',
     'urltest',
 ])
 
 # XXX Make this work in libxul builds.
 #SIMPLE_PROGRAMS += [
@@ -37,18 +34,21 @@ GeckoSimplePrograms([
 #    TestIOThreads',
 #    TestSocketTransport',
 #    TestStreamPump',
 #    TestStreamTransport',
 #    TestUDPSocketProvider',
 #]
 
 CppUnitTests([
+    'PropertiesTest',
     'TestBind',
     'TestCookie',
+    'TestServ',
+    'TestStandardURL',
     'TestUDPSocket',
 ])
 
 RESOURCE_FILES += [
     'urlparse.dat',
     'urlparse_unx.dat',
 ]
 
--- a/testing/cppunittest.ini
+++ b/testing/cppunittest.ini
@@ -1,8 +1,11 @@
+[PropertiesTest]
+[TestServ]
+[TestStandardURL]
 [ShowAlignments]
 [ShowSSEConfig]
 [TestAppShellSteadyState]
 [TestArrayUtils]
 [TestAtomics]
 [TestAudioBuffers]
 skip-if = os == 'b2g'  # Bug 1062937
 [TestAudioEventTimeline]