Bug 858005 - Part 4: Tests. r=gene
authorAlbert Crespell <acperez@tid.es>
Fri, 31 May 2013 07:23:04 +0200
changeset 174884 34d915243969599116d8ec47c61082d54c51b7c8
parent 174883 7cbdd95bf3715f83482c2f1fdaa5bf01aac67adf
child 174885 b4d9c56e18a8ce319b04150a06c34ee9e67af257
push id445
push userffxbld
push dateMon, 10 Mar 2014 22:05:19 +0000
treeherdermozilla-release@dc38b741b04e [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewersgene
bugs858005
milestone28.0a1
first release with
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
last release without
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
Bug 858005 - Part 4: Tests. r=gene
dom/network/tests/Makefile.in
dom/network/tests/test_networkstats_alarms.html
dom/network/tests/test_networkstats_basics.html
dom/network/tests/unit_stats/test_networkstats_db.js
dom/network/tests/unit_stats/test_networkstats_service.js
--- a/dom/network/tests/Makefile.in
+++ b/dom/network/tests/Makefile.in
@@ -10,10 +10,11 @@ MOCHITEST_FILES = \
   $(NULL)
 
 ifeq (gonk,$(MOZ_WIDGET_TOOLKIT))
 MOCHITEST_FILES = \
   test_networkstats_basics.html \
   test_networkstats_disabled.html \
   test_networkstats_enabled_no_perm.html \
   test_networkstats_enabled_perm.html \
+  test_networkstats_alarms.html \
   $(NULL)
 endif
new file mode 100644
--- /dev/null
+++ b/dom/network/tests/test_networkstats_alarms.html
@@ -0,0 +1,175 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+  <meta charset="utf-8">
+  <title>Test for NetworkStats alarms</title>
+  <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
+</head>
+<body>
+<p id="display"></p>
+<div id="content">
+</div>
+<pre id="test">
+<script type="application/javascript">
+
+function test() {
+  ok(true, "Checking if no alarms are set.");
+
+  req = navigator.mozNetworkStats.getAllAlarms();
+
+  req.onsuccess = function () {
+    ok(true, "Succeeded to get alarms.");
+    ok(Array.isArray(req.result) && req.result.length == 0,
+       "There are no alarms set.");
+    next();
+  };
+
+  req.onerror = function () {
+    ok(false, "getAllAlarms() shouldn't fail!");
+  }
+}
+
+var req;
+var index = -1;
+
+var wifi = {'type': 0, 'id': '0'};
+var mobile = {'type': 1, 'id': '1'};
+
+var steps = [
+  function () {
+    ok(true, "Calling getAllAlarms() with invalid network.");
+
+    req = navigator.mozNetworkStats.getAllAlarms(mobile);
+
+    req.onsuccess = function () {
+      ok(false, "getAllAlarms() shouldn't succeed!");
+    };
+
+    req.onerror = function () {
+      ok(req.error.name == "InvalidInterface", "Get InvalidInterface error");
+      next();
+    }
+  },
+  function () {
+    ok(true, "Calling addAlarm() with invalid network or parameters.");
+
+    try {
+      navigator.mozNetworkStats.addAlarm();
+    } catch(ex) {
+      ok(ex.result == SpecialPowers.Cr.NS_ERROR_XPC_NOT_ENOUGH_ARGS,
+         "addAlarm() throws NS_ERROR_XPC_NOT_ENOUGH_ARGS exception when no parameters");
+    }
+
+    try {
+      navigator.mozNetworkStats.addAlarm(100000);
+    } catch(ex) {
+      ok(ex.result == SpecialPowers.Cr.NS_ERROR_XPC_NOT_ENOUGH_ARGS,
+         "addAlarm() throws NS_ERROR_XPC_NOT_ENOUGH_ARGS exception when no network");
+    }
+
+    try {
+      navigator.mozNetworkStats.addAlarm(wifi);
+    } catch(ex) {
+      ok(ex.result == SpecialPowers.Cr.NS_ERROR_XPC_NOT_ENOUGH_ARGS,
+         "addAlarm() throws NS_ERROR_XPC_NOT_ENOUGH_ARGS exception when no threshold");
+    }
+
+    req = navigator.mozNetworkStats.addAlarm(mobile, -100000);
+
+    req.onsuccess = function () {
+      ok(false, "addAlarm() shouldn't succeed with negative threshold.");
+    };
+
+    req.onerror = function () {
+      ok(req.error.name == "InvalidThresholdValue", "Get InvalidThresholdValue error");
+      next();
+    }
+  },
+  function () {
+    ok(true, "Calling addAlarm()");
+
+    req = navigator.mozNetworkStats.addAlarm(wifi, 1000000);
+
+    req.onsuccess = function () {
+      ok(true, "Succeeded to add alarm. AlarmId: " + req.result);
+      next();
+    };
+    req.onerror = function () {
+      ok(false, "addAlarm() shouldn't fail.");
+    };
+  },
+  function () {
+    ok(true, "Calling getAllAlarms()");
+
+    req = navigator.mozNetworkStats.getAllAlarms(wifi);
+
+    req.onsuccess = function () {
+      ok(req.result.length == 1, "Only one alarm");
+      ok(req.result[0].alarmId == 1, "Get correct alarmId");
+      next();
+    };
+
+    req.onerror = function () {
+      ok(false, "getAllAlarms() shouldn't fail.");
+    }
+  },
+  function () {
+    ok(true, "Calling removeAlarms() to remove alarms.");
+
+    req = navigator.mozNetworkStats.removeAlarms();
+
+    req.onsuccess = function () {
+      ok(req.result, "Succeeded to remove alarms.");
+      next();
+    };
+
+    req.onerror = function () {
+      ok(false, "removeAlarms() shouldn't fail.");
+    }
+  },
+  function () {
+    ok(true, "Checking if all alarms are removed.");
+
+    req = navigator.mozNetworkStats.getAllAlarms();
+
+    req.onsuccess = function () {
+      ok(Array.isArray(req.result) && req.result.length == 0,
+         "Succeeded to remove all alarms.");
+      next();
+    };
+
+    req.onerror = function () {
+      ok(false, "getAllAlarms() shouldn't fail.");
+    }
+  },
+  function () {
+    ok(true, "all done!\n");
+    SpecialPowers.removePermission("networkstats-manage", document);
+    SimpleTest.finish();
+    return;
+  }
+];
+
+function next() {
+  index += 1;
+  if (index >= steps.length) {
+    ok(false, "Shouldn't get here!");
+    return;
+  }
+  try {
+    steps[index]();
+  } catch(ex) {
+    ok(false, "Caught exception", ex);
+  }
+}
+
+SimpleTest.waitForExplicitFinish();
+
+SpecialPowers.addPermission("networkstats-manage", true, document);
+SpecialPowers.pushPrefEnv({'set': [["dom.mozNetworkStats.enabled", true]]}, test);
+
+</script>
+</pre>
+</body>
+</html>
--- a/dom/network/tests/test_networkstats_basics.html
+++ b/dom/network/tests/test_networkstats_basics.html
@@ -8,20 +8,18 @@
 <body>
 <p id="display"></p>
 <div id="content" style="display: none">
 </div>
 <pre id="test">
 <script type="application/javascript">
 
 function test() {
-  ok('mozNetworkStats' in navigator, "navigator.mozMozNetworkStats should exist");
-  ok(navigator.mozNetworkStats, "navigator.mozNetworkStats returns an object");
-
-  netStats = navigator.mozNetworkStats;
+  netStats = window.navigator.mozNetworkStats;
+  ok(netStats, "mozNetworkStats exists");
 
   // Test IDL attributes
   ok('sampleRate' in netStats,
    "sampleRate should be a NetworkStats attribute");
   ok(netStats.sampleRate > 0,
    "sampleRate is greater than 0.");
 
   ok('maxStorageAge' in netStats,
--- a/dom/network/tests/unit_stats/test_networkstats_db.js
+++ b/dom/network/tests/unit_stats/test_networkstats_db.js
@@ -2,22 +2,38 @@
    http://creativecommons.org/publicdomain/zero/1.0/ */
 
 const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
 
 Cu.import("resource://gre/modules/NetworkStatsDB.jsm");
 
 const netStatsDb = new NetworkStatsDB();
 
-function clearWholeDB(callback) {
-  netStatsDb.dbNewTxn("readwrite", function(aTxn, aStore) {
-    aStore.delete();
+function clearStore(store, callback) {
+  netStatsDb.dbNewTxn(store, "readwrite", function(aTxn, aStore) {
+    aStore.openCursor().onsuccess = function (event) {
+      let cursor = event.target.result;
+      if (cursor){
+        cursor.delete();
+        cursor.continue();
+      }
+    };
   }, callback);
 }
 
+add_test(function prepareDatabase() {
+  // Clear whole database to avoid starting tests with unknown state
+  // due to the previous tests.
+  clearStore('net_stats', function() {
+    clearStore('net_alarm', function() {
+      run_next_test();
+    });
+  });
+});
+
 function filterTimestamp(date) {
   var sampleRate = netStatsDb.sampleRate;
   var offset = date.getTimezoneOffset() * 60 * 1000;
   return Math.floor((date.getTime() - offset) / sampleRate) * sampleRate;
 }
 
 function getNetworks() {
   return [{ id: '0', type: Ci.nsIDOMMozNetworkStatsManager.WIFI },
@@ -117,37 +133,41 @@ add_test(function test_clear_interface()
     do_check_eq(error, null);
     run_next_test();
   });
 });
 
 add_test(function test_internalSaveStats_singleSample() {
   var networks = getNetworks();
 
-  var stats = { appId:        0,
-                network:      [networks[0].id, networks[0].type],
-                timestamp:    Date.now(),
-                rxBytes:      0,
-                txBytes:      0,
-                rxTotalBytes: 1234,
-                txTotalBytes: 1234 };
+  var stats = { appId:         0,
+                network:       [networks[0].id, networks[0].type],
+                timestamp:     Date.now(),
+                rxBytes:       0,
+                txBytes:       0,
+                rxSystemBytes: 1234,
+                txSystemBytes: 1234,
+                rxTotalBytes:  1234,
+                txTotalBytes:  1234 };
 
-  netStatsDb.dbNewTxn("readwrite", function(txn, store) {
+  netStatsDb.dbNewTxn("net_stats", "readwrite", function(txn, store) {
     netStatsDb._saveStats(txn, store, stats);
   }, function(error, result) {
     do_check_eq(error, null);
 
     netStatsDb.logAllRecords(function(error, result) {
       do_check_eq(error, null);
       do_check_eq(result.length, 1);
       do_check_eq(result[0].appId, stats.appId);
       do_check_true(compareNetworks(result[0].network, stats.network));
       do_check_eq(result[0].timestamp, stats.timestamp);
       do_check_eq(result[0].rxBytes, stats.rxBytes);
       do_check_eq(result[0].txBytes, stats.txBytes);
+      do_check_eq(result[0].rxSystemBytes, stats.rxSystemBytes);
+      do_check_eq(result[0].txSystemBytes, stats.txSystemBytes);
       do_check_eq(result[0].rxTotalBytes, stats.rxTotalBytes);
       do_check_eq(result[0].txTotalBytes, stats.txTotalBytes);
       run_next_test();
     });
   });
 });
 
 add_test(function test_internalSaveStats_arraySamples() {
@@ -156,45 +176,48 @@ add_test(function test_internalSaveStats
   netStatsDb.clearStats(networks, function (error, result) {
     do_check_eq(error, null);
 
     var network = [networks[0].id, networks[0].type];
 
     var samples = 2;
     var stats = [];
     for (var i = 0; i < samples; i++) {
-      stats.push({ appId:        0,
-                   network:      network,
-                   timestamp:    Date.now() + (10 * i),
-                   rxBytes:      0,
-                   txBytes:      0,
-                   rxTotalBytes: 1234,
-                   txTotalBytes: 1234 });
+      stats.push({ appId:         0,
+                   network:       network,
+                   timestamp:     Date.now() + (10 * i),
+                   rxBytes:       0,
+                   txBytes:       0,
+                   rxSystemBytes: 1234,
+                   txSystemBytes: 1234,
+                   rxTotalBytes:  1234,
+                   txTotalBytes:  1234 });
     }
 
-    netStatsDb.dbNewTxn("readwrite", function(txn, store) {
+    netStatsDb.dbNewTxn("net_stats", "readwrite", function(txn, store) {
       netStatsDb._saveStats(txn, store, stats);
     }, function(error, result) {
       do_check_eq(error, null);
 
       netStatsDb.logAllRecords(function(error, result) {
         do_check_eq(error, null);
 
         // Result has one sample more than samples because clear inserts
         // an empty sample to keep totalBytes synchronized with netd counters
         result.shift();
         do_check_eq(result.length, samples);
-
         var success = true;
         for (var i = 1; i < samples; i++) {
           if (result[i].appId != stats[i].appId ||
               !compareNetworks(result[i].network, stats[i].network) ||
               result[i].timestamp != stats[i].timestamp ||
               result[i].rxBytes != stats[i].rxBytes ||
               result[i].txBytes != stats[i].txBytes ||
+              result[i].rxSystemBytes != stats[i].rxSystemBytes ||
+              result[i].txSystemBytes != stats[i].txSystemBytes ||
               result[i].rxTotalBytes != stats[i].rxTotalBytes ||
               result[i].txTotalBytes != stats[i].txTotalBytes) {
             success = false;
             break;
           }
         }
         do_check_true(success);
         run_next_test();
@@ -208,28 +231,30 @@ add_test(function test_internalRemoveOld
 
   netStatsDb.clearStats(networks, function (error, result) {
     do_check_eq(error, null);
 
     var network = [networks[0].id, networks[0].type];
     var samples = 10;
     var stats = [];
     for (var i = 0; i < samples - 1; i++) {
-      stats.push({ appId:              0,
-                   network:      network, timestamp:    Date.now() + (10 * i),
-                   rxBytes:            0, txBytes:      0,
-                   rxTotalBytes:    1234, txTotalBytes: 1234 });
+      stats.push({ appId:               0,
+                   network:       network, timestamp:     Date.now() + (10 * i),
+                   rxBytes:             0, txBytes:       0,
+                   rxSystemBytes:    1234, txSystemBytes: 1234,
+                   rxTotalBytes:     1234, txTotalBytes:  1234 });
     }
 
-    stats.push({ appId:              0,
-                 network:      network, timestamp:    Date.now() + (10 * samples),
-                 rxBytes:            0, txBytes:      0,
-                 rxTotalBytes:    1234, txTotalBytes: 1234 });
+    stats.push({ appId:               0,
+                 network:       network, timestamp:     Date.now() + (10 * samples),
+                 rxBytes:             0, txBytes:       0,
+                 rxSystemBytes:    1234, txSystemBytes: 1234,
+                 rxTotalBytes:     1234, txTotalBytes:  1234 });
 
-    netStatsDb.dbNewTxn("readwrite", function(txn, store) {
+    netStatsDb.dbNewTxn("net_stats", "readwrite", function(txn, store) {
       netStatsDb._saveStats(txn, store, stats);
       var date = stats[stats.length - 1].timestamp
                  + (netStatsDb.sampleRate * netStatsDb.maxStorageSamples - 1) - 1;
       netStatsDb._removeOldStats(txn, store, 0, network, date);
     }, function(error, result) {
       do_check_eq(error, null);
 
       netStatsDb.logAllRecords(function(error, result) {
@@ -240,20 +265,20 @@ add_test(function test_internalRemoveOld
       });
     });
   });
 });
 
 function processSamplesDiff(networks, lastStat, newStat, callback) {
   netStatsDb.clearStats(networks, function (error, result){
     do_check_eq(error, null);
-    netStatsDb.dbNewTxn("readwrite", function(txn, store) {
+    netStatsDb.dbNewTxn("net_stats", "readwrite", function(txn, store) {
       netStatsDb._saveStats(txn, store, lastStat);
     }, function(error, result) {
-      netStatsDb.dbNewTxn("readwrite", function(txn, store) {
+      netStatsDb.dbNewTxn("net_stats", "readwrite", function(txn, store) {
         let request = store.index("network").openCursor(newStat.network, "prev");
         request.onsuccess = function onsuccess(event) {
           let cursor = event.target.result;
           do_check_neq(cursor, null);
           netStatsDb._processSamplesDiff(txn, store, cursor, newStat);
         };
       }, function(error, result) {
         do_check_eq(error, null);
@@ -268,122 +293,135 @@ function processSamplesDiff(networks, la
 
 add_test(function test_processSamplesDiffSameSample() {
   var networks = getNetworks();
   var network = [networks[0].id, networks[0].type];
 
   var sampleRate = netStatsDb.sampleRate;
   var date = filterTimestamp(new Date());
 
-  var lastStat = { appId:              0,
-                   network:      network, timestamp:    date,
-                   rxBytes:            0, txBytes:      0,
-                   rxTotalBytes:    1234, txTotalBytes: 1234 };
+  var lastStat = { appId:               0,
+                   network:       network, timestamp:     date,
+                   rxBytes:             0, txBytes:       0,
+                   rxSystemBytes:    1234, txSystemBytes: 1234,
+                   rxTotalBytes:     2234, txTotalBytes:  2234 };
 
-  var newStat = { appId:              0,
-                  network:      network, timestamp:    date,
-                  rxBytes:            0, txBytes:      0,
-                  rxTotalBytes:    2234, txTotalBytes: 2234 };
+  var newStat = { appId:               0,
+                  network:       network, timestamp:     date,
+                  rxBytes:             0, txBytes:       0,
+                  rxSystemBytes:    2234, txSystemBytes: 2234,
+                  rxTotalBytes:     2234, txTotalBytes:  2234 };
 
   processSamplesDiff(networks, lastStat, newStat, function(result) {
     do_check_eq(result.length, 1);
     do_check_eq(result[0].appId, newStat.appId);
     do_check_true(compareNetworks(result[0].network, newStat.network));
     do_check_eq(result[0].timestamp, newStat.timestamp);
-    do_check_eq(result[0].rxBytes, newStat.rxTotalBytes - lastStat.rxTotalBytes);
-    do_check_eq(result[0].txBytes, newStat.txTotalBytes - lastStat.txTotalBytes);
-    do_check_eq(result[0].rxTotalBytes, newStat.rxTotalBytes);
-    do_check_eq(result[0].txTotalBytes, newStat.txTotalBytes);
+    do_check_eq(result[0].rxBytes, newStat.rxSystemBytes - lastStat.rxSystemBytes);
+    do_check_eq(result[0].txBytes, newStat.txSystemBytes - lastStat.txSystemBytes);
+    do_check_eq(result[0].rxTotalBytes, lastStat.rxTotalBytes + newStat.rxSystemBytes - lastStat.rxSystemBytes);
+    do_check_eq(result[0].txTotalBytes, lastStat.txTotalBytes + newStat.txSystemBytes - lastStat.txSystemBytes);
+    do_check_eq(result[0].rxSystemBytes, newStat.rxSystemBytes);
+    do_check_eq(result[0].txSystemBytes, newStat.txSystemBytes);
     run_next_test();
   });
 });
 
 add_test(function test_processSamplesDiffNextSample() {
   var networks = getNetworks();
   var network = [networks[0].id, networks[0].type];
 
   var sampleRate = netStatsDb.sampleRate;
   var date = filterTimestamp(new Date());
 
-  var lastStat = { appId:              0,
-                   network:      network, timestamp:    date,
-                   rxBytes:            0, txBytes:      0,
-                   rxTotalBytes:    1234, txTotalBytes: 1234 };
+  var lastStat = { appId:               0,
+                   network:       network, timestamp:     date,
+                   rxBytes:             0, txBytes:       0,
+                   rxSystemBytes:    1234, txSystemBytes: 1234,
+                   rxTotalBytes:     2234, txTotalBytes:  2234 };
 
-  var newStat = { appId:              0,
-                  network:      network, timestamp:    date + sampleRate,
-                  rxBytes:            0, txBytes:      0,
-                  rxTotalBytes:     500, txTotalBytes: 500 };
+  var newStat = { appId:               0,
+                  network:       network, timestamp:     date + sampleRate,
+                  rxBytes:             0, txBytes:       0,
+                  rxSystemBytes:    1734, txSystemBytes: 1734,
+                  rxTotalBytes:        0, txTotalBytes:  0 };
 
   processSamplesDiff(networks, lastStat, newStat, function(result) {
     do_check_eq(result.length, 2);
     do_check_eq(result[1].appId, newStat.appId);
     do_check_true(compareNetworks(result[1].network, newStat.network));
     do_check_eq(result[1].timestamp, newStat.timestamp);
-    do_check_eq(result[1].rxBytes, newStat.rxTotalBytes);
-    do_check_eq(result[1].txBytes, newStat.txTotalBytes);
-    do_check_eq(result[1].rxTotalBytes, newStat.rxTotalBytes);
-    do_check_eq(result[1].txTotalBytes, newStat.txTotalBytes);
+    do_check_eq(result[1].rxBytes, newStat.rxSystemBytes - lastStat.rxSystemBytes);
+    do_check_eq(result[1].txBytes, newStat.txSystemBytes - lastStat.txSystemBytes);
+    do_check_eq(result[1].rxSystemBytes, newStat.rxSystemBytes);
+    do_check_eq(result[1].txSystemBytes, newStat.txSystemBytes);
+    do_check_eq(result[1].rxTotalBytes, lastStat.rxTotalBytes + newStat.rxSystemBytes - lastStat.rxSystemBytes);
+    do_check_eq(result[1].txTotalBytes, lastStat.txTotalBytes + newStat.txSystemBytes - lastStat.txSystemBytes);
     run_next_test();
   });
 });
 
 add_test(function test_processSamplesDiffSamplesLost() {
   var networks = getNetworks();
   var network = [networks[0].id, networks[0].type];
   var samples = 5;
   var sampleRate = netStatsDb.sampleRate;
   var date = filterTimestamp(new Date());
-  var lastStat = { appId:             0,
-                   network:     network, timestamp:    date,
-                   rxBytes:           0, txBytes:      0,
-                   rxTotalBytes:   1234, txTotalBytes: 1234 };
+  var lastStat = { appId:              0,
+                   network:      network, timestamp:     date,
+                   rxBytes:            0, txBytes:       0,
+                   rxSystemBytes:   1234, txSystemBytes: 1234,
+                   rxTotalBytes:    2234, txTotalBytes:  2234};
 
-  var newStat = { appId:              0,
-                  network:      network, timestamp:    date + (sampleRate * samples),
-                  rxBytes:            0, txBytes:      0,
-                  rxTotalBytes:    2234, txTotalBytes: 2234 };
+  var newStat = { appId:               0,
+                  network:       network, timestamp:     date + (sampleRate * samples),
+                  rxBytes:             0, txBytes:       0,
+                  rxSystemBytes:    2234, txSystemBytes: 2234,
+                  rxTotalBytes:        0, txTotalBytes:  0 };
 
   processSamplesDiff(networks, lastStat, newStat, function(result) {
     do_check_eq(result.length, samples + 1);
     do_check_eq(result[0].appId, newStat.appId);
     do_check_true(compareNetworks(result[samples].network, newStat.network));
     do_check_eq(result[samples].timestamp, newStat.timestamp);
     do_check_eq(result[samples].rxBytes, newStat.rxTotalBytes - lastStat.rxTotalBytes);
     do_check_eq(result[samples].txBytes, newStat.txTotalBytes - lastStat.txTotalBytes);
-    do_check_eq(result[samples].rxTotalBytes, newStat.rxTotalBytes);
-    do_check_eq(result[samples].txTotalBytes, newStat.txTotalBytes);
+    do_check_eq(result[samples].rxSystemBytes, newStat.rxSystemBytes);
+    do_check_eq(result[samples].txSystemBytes, newStat.txSystemBytes);
+    do_check_eq(result[samples].rxTotalBytes, lastStat.rxTotalBytes + newStat.rxSystemBytes - lastStat.rxSystemBytes);
+    do_check_eq(result[samples].txTotalBytes, lastStat.txTotalBytes + newStat.txSystemBytes - lastStat.txSystemBytes);
     run_next_test();
   });
 });
 
 add_test(function test_saveStats() {
   var networks = getNetworks();
   var network = [networks[0].id, networks[0].type];
 
   var stats = { appId:       0,
                 networkId:   networks[0].id,
                 networkType: networks[0].type,
                 date:        new Date(),
                 rxBytes:     2234,
                 txBytes:     2234};
 
-  netStatsDb.clearStats(networks, function (error, result) {
-    do_check_eq(error, null);
+  clearStore('net_stats', function() {
     netStatsDb.saveStats(stats, function(error, result) {
       do_check_eq(error, null);
       netStatsDb.logAllRecords(function(error, result) {
         do_check_eq(error, null);
         do_check_eq(result.length, 1);
         do_check_eq(result[0].appId, stats.appId);
         do_check_true(compareNetworks(result[0].network, network));
         let timestamp = filterTimestamp(stats.date);
         do_check_eq(result[0].timestamp, timestamp);
-        do_check_eq(result[0].rxBytes, 0);
-        do_check_eq(result[0].txBytes, 0);
+        do_check_eq(result[0].rxBytes, stats.rxBytes);
+        do_check_eq(result[0].txBytes, stats.txBytes);
+        do_check_eq(result[0].rxSystemBytes, stats.rxBytes);
+        do_check_eq(result[0].txSystemBytes, stats.txBytes);
         do_check_eq(result[0].rxTotalBytes, stats.rxBytes);
         do_check_eq(result[0].txTotalBytes, stats.txBytes);
         run_next_test();
       });
     });
   });
 });
 
@@ -411,28 +449,30 @@ add_test(function test_saveAppStats() {
         // past tests and the new one for appId 1
         do_check_eq(result.length, 2);
         do_check_eq(result[1].appId, stats.appId);
         do_check_true(compareNetworks(result[1].network, network));
         let timestamp = filterTimestamp(stats.date);
         do_check_eq(result[1].timestamp, timestamp);
         do_check_eq(result[1].rxBytes, stats.rxBytes);
         do_check_eq(result[1].txBytes, stats.txBytes);
+        do_check_eq(result[1].rxSystemBytes, 0);
+        do_check_eq(result[1].txSystemBytes, 0);
         do_check_eq(result[1].rxTotalBytes, 0);
         do_check_eq(result[1].txTotalBytes, 0);
         run_next_test();
       });
     });
   });
 });
 
 function prepareFind(network, stats, callback) {
   netStatsDb.clearStats(network, function (error, result) {
     do_check_eq(error, null);
-    netStatsDb.dbNewTxn("readwrite", function(txn, store) {
+    netStatsDb.dbNewTxn("net_stats", "readwrite", function(txn, store) {
       netStatsDb._saveStats(txn, store, stats);
     }, function(error, result) {
         callback(error, result);
     });
   });
 }
 
 add_test(function test_find () {
@@ -444,25 +484,28 @@ add_test(function test_find () {
   var samples = 5;
   var sampleRate = netStatsDb.sampleRate;
   var start = Date.now();
   var saveDate = filterTimestamp(new Date());
   var end = new Date(start + (sampleRate * (samples - 1)));
   start = new Date(start - sampleRate);
   var stats = [];
   for (var i = 0; i < samples; i++) {
-    stats.push({ appId:              appId,
-                 network:      networkWifi, timestamp:    saveDate + (sampleRate * i),
-                 rxBytes:                0, txBytes:      10,
-                 rxTotalBytes:           0, txTotalBytes: 0 });
+    stats.push({ appId:               appId,
+                 network:       networkWifi, timestamp:     saveDate + (sampleRate * i),
+                 rxBytes:                 0, txBytes:       10,
+                 rxSystemBytes:           0, txSystemBytes: 0,
+                 rxTotalBytes:            0, txTotalBytes:  0});
 
-    stats.push({ appId:                appId,
-                 network:      networkMobile, timestamp:    saveDate + (sampleRate * i),
-                 rxBytes:                  0, txBytes:      10,
-                 rxTotalBytes:             0, txTotalBytes: 0 });
+
+    stats.push({ appId:                 appId,
+                 network:       networkMobile, timestamp:     saveDate + (sampleRate * i),
+                 rxBytes:                   0, txBytes:       10,
+                 rxSystemBytes:             0, txSystemBytes: 0,
+                 rxTotalBytes:              0, txTotalBytes:  0});
   }
 
   prepareFind(networks[0], stats, function(error, result) {
     do_check_eq(error, null);
     netStatsDb.find(function (error, result) {
       do_check_eq(error, null);
       do_check_eq(result.network.id, networks[0].id);
       do_check_eq(result.network.type, networks[0].type);
@@ -549,40 +592,217 @@ add_test(function test_saveMultipleAppSt
   netStatsDb.clearStats(networks, function (error, result) {
     do_check_eq(error, null);
     netStatsDb.saveStats(cached[keys[index]],
       function callback(error, result) {
         do_check_eq(error, null);
 
         if (index == keys.length - 1) {
           netStatsDb.logAllRecords(function(error, result) {
-          // Again, result has two samples more than expected samples because
-          // clear inserts one empty sample for each network to keep totalBytes
-          // synchronized with netd counters. so the first two samples have to
-          // be discarted.
-          result.shift();
-          result.shift();
+            // Again, result has two samples more than expected samples because
+            // clear inserts one empty sample for each network to keep totalBytes
+            // synchronized with netd counters. so the first two samples have to
+            // be discarted.
+            result.shift();
+            result.shift();
 
-          do_check_eq(error, null);
-          do_check_eq(result.length, 4);
-          do_check_eq(result[0].appId, 1);
-          do_check_true(compareNetworks(result[0].network,[networkWifi.id, networkWifi.type]));
-          do_check_eq(result[0].rxBytes, 0);
-          do_check_eq(result[0].txBytes, 10);
-          run_next_test();
+            do_check_eq(error, null);
+            do_check_eq(result.length, 4);
+            do_check_eq(result[0].appId, 1);
+            do_check_true(compareNetworks(result[0].network, [networkWifi.id, networkWifi.type]));
+            do_check_eq(result[0].rxBytes, 0);
+            do_check_eq(result[0].txBytes, 10);
+            run_next_test();
           });
+         return;
         }
 
         index += 1;
         netStatsDb.saveStats(cached[keys[index]], callback);
     });
   });
 });
 
+var networkWifi = '00';
+var networkMobile = '11';
+
+var examplePageURL = "http://example.com/index.html";
+var exampleManifestURL = "http://example.com/manifest.webapp";
+
+var testPageURL = "http://test.com/index.html";
+var testManifestURL = "http://test.com/manifest.webapp";
+
+var alarms = [{ id:             null,
+                networkId:      networkWifi,
+                threshold:      10000,
+                data:           {foo: "something"},
+                pageURL:        examplePageURL,
+                manifestURL:    exampleManifestURL },
+              { id:             null,
+                networkId:      networkWifi,
+                threshold:      1000,
+                data:           {foo: "else"},
+                pageURL:        examplePageURL,
+                manifestURL:    exampleManifestURL },
+              { id:             null,
+                networkId:      networkMobile,
+                threshold:      100,
+                data:           {foo: "to"},
+                pageURL:        examplePageURL,
+                manifestURL:    exampleManifestURL },
+              { id:             null,
+                networkId:      networkMobile,
+                threshold:      10,
+                data:           {foo: "test"},
+                pageURL:        testPageURL,
+                manifestURL:    testManifestURL }];
+
+var alarmsDbId = 1;
+
+add_test(function test_addAlarm() {
+  // Add alarms[0] -> DB: [ alarms[0] (id: 1) ]
+  // Check the insertion is OK.
+  netStatsDb.addAlarm(alarms[0], function(error, result) {
+    do_check_eq(error, null);
+    alarmsDbId = result;
+    netStatsDb.getAlarms(Ci.nsINetworkInterface.NETWORK_TYPE_WIFI, exampleManifestURL, function(error, result) {
+      do_check_eq(error, null);
+      do_check_eq(result.length, 1);
+      do_check_eq(result[0].id, alarmsDbId);
+      do_check_eq(result[0].networkId, alarms[0].networkId);
+      do_check_eq(result[0].threshold, alarms[0].threshold);
+      do_check_eq(result[0].data.foo, alarms[0].data.foo);
+      run_next_test();
+    });
+  });
+});
+
+add_test(function test_getFirstAlarm() {
+  // Add alarms[1] -> DB: [ alarms[0] (id: 1), alarms[1] (id: 2) ]
+  // Check first alarm is alarms[1] because threshold is lower.
+  alarmsDbId += 1;
+  netStatsDb.addAlarm(alarms[1], function (error, result) {
+    do_check_eq(error, null);
+    do_check_eq(result, alarmsDbId);
+    netStatsDb.getFirstAlarm(networkWifi, function(error, result) {
+      do_check_eq(error, null);
+      do_check_eq(result.id, alarmsDbId);
+      do_check_eq(result.networkId, alarms[1].networkId);
+      do_check_eq(result.threshold, alarms[1].threshold);
+      do_check_eq(result.data.foo, alarms[1].data.foo);
+      do_check_eq(result.pageURL, alarms[1].pageURL);
+      do_check_eq(result.manifestURL, alarms[1].manifestURL);
+      run_next_test();
+    });
+  });
+});
+
+add_test(function test_removeAlarm() {
+  // Remove alarms[1] (id: 2) -> DB: [ alarms[0] (id: 1) ]
+  // Check get first return alarms[0].
+  netStatsDb.removeAlarm(alarmsDbId, alarms[0].manifestURL, function (error, result) {
+    do_check_eq(error, null);
+    netStatsDb.getFirstAlarm(networkWifi, function(error, result) {
+      do_check_eq(error, null);
+      do_check_eq(result.id, alarmsDbId - 1);
+      do_check_eq(result.networkId, alarms[0].networkId);
+      do_check_eq(result.threshold, alarms[0].threshold);
+      do_check_eq(result.data.foo, alarms[0].data.foo);
+      do_check_eq(result.pageURL, alarms[0].pageURL);
+      do_check_eq(result.manifestURL, alarms[0].manifestURL);
+      run_next_test();
+    });
+  });
+});
+
+add_test(function test_removeAppAlarm() {
+  // Remove alarms[0] (id: 1) -> DB: [ ]
+  netStatsDb.removeAlarm(alarmsDbId - 1, alarms[0].manifestURL, function (error, result) {
+    do_check_eq(error, null);
+    netStatsDb.getAlarms(networkWifi, exampleManifestURL, function(error, result) {
+      do_check_eq(error, null);
+      do_check_eq(result.length, 0);
+      run_next_test();
+    });
+  });
+});
+
+add_test(function test_getAlarms() {
+  // Add all alarms -> DB: [ alarms[0] (id: 3),
+  //                         alarms[1] (id: 4),
+  //                         alarms[2] (id: 5),
+  //                         alarms[3] (id: 6) ]
+  // Check that getAlarms for wifi returns 2 alarms.
+  // Check that getAlarms for all connections returns 3 alarms.
+
+  var callback = function () {
+    netStatsDb.getAlarms(networkWifi, exampleManifestURL, function(error, result) {
+      do_check_eq(error, null);
+      do_check_eq(result.length, 2);
+      netStatsDb.getAlarms(null, exampleManifestURL, function(error, result) {
+        do_check_eq(error, null);
+        do_check_eq(result.length, 3);
+        run_next_test();
+      });
+    });
+  };
+
+  var index = 0;
+
+  var addFunction = function () {
+    alarmsDbId += 1;
+    netStatsDb.addAlarm(alarms[index], function (error, result) {
+      do_check_eq(error, null);
+      index += 1;
+      do_check_eq(result, alarmsDbId);
+      if (index >= alarms.length) {
+        callback();
+        return;
+      }
+      addFunction();
+    });
+  };
+
+  addFunction();
+});
+
+add_test(function test_removeAppAllAlarms() {
+  // Remove all alarms for exampleManifestURL -> DB: [ alarms[3] (id: 6) ]
+  netStatsDb.removeAlarms(exampleManifestURL, function (error, result) {
+    do_check_eq(error, null);
+    netStatsDb.getAlarms(null, exampleManifestURL, function(error, result) {
+      do_check_eq(error, null);
+      do_check_eq(result.length, 0);
+      netStatsDb.getAlarms(null, testManifestURL, function(error, result) {
+        do_check_eq(error, null);
+        do_check_eq(result.length, 1);
+        run_next_test();
+      });
+    });
+  });
+});
+
+add_test(function test_updateAlarm() {
+  // Update alarms[3] (id: 6) -> DB: [ alarms[3]* (id: 6) ]
+
+  var updatedAlarm = alarms[1];
+  updatedAlarm.id = alarmsDbId;
+  updatedAlarm.threshold = 10;
+
+  netStatsDb.updateAlarm(updatedAlarm, function (error, result) {
+    do_check_eq(error, null);
+    netStatsDb.getFirstAlarm(networkWifi, function(error, result) {
+      do_check_eq(error, null);
+      do_check_eq(result.id, updatedAlarm.id);
+      do_check_eq(result.networkId, updatedAlarm.networkId);
+      do_check_eq(result.threshold, updatedAlarm.threshold);
+      do_check_eq(result.data.foo, updatedAlarm.data.foo);
+      do_check_eq(result.pageURL, updatedAlarm.pageURL);
+      do_check_eq(result.manifestURL, updatedAlarm.manifestURL);
+      run_next_test();
+    });
+  });
+});
+
 function run_test() {
   do_get_profile();
-
-  // Clear whole database to avoid start tests with unknown state
-  // due to previous tests.
-  clearWholeDB(function(){
-    run_next_test();
-  });
+  run_next_test();
 }
--- a/dom/network/tests/unit_stats/test_networkstats_service.js
+++ b/dom/network/tests/unit_stats/test_networkstats_service.js
@@ -134,17 +134,105 @@ add_test(function test_queue() {
   NetworkStatsService.updateStats(netId1, callback);
   NetworkStatsService.updateStats(netId2, callback);
 
   do_check_eq(NetworkStatsService.updateQueue.length, 2);
   do_check_eq(NetworkStatsService.updateQueue[0].callbacks.length, 2);
   do_check_eq(NetworkStatsService.updateQueue[0].callbacks[0], null);
   do_check_neq(NetworkStatsService.updateQueue[0].callbacks[1], null);
 
+  // Clear queue because in test environment requests for mobile networks
+  // can not be handled.
+  NetworkStatsService.updateQueue =  [];
   run_next_test();
 });
 
+var wifiId = '00';
+
+add_test(function test_updateThreshold() {
+  let alarm = { networkId: wifiId, threshold: 10000 };
+
+  NetworkStatsService._updateThreshold(alarm, function onSet(error, threshold){
+    do_check_eq(error, null);
+    do_check_neq(threshold.systemThreshold, undefined);
+    do_check_neq(threshold.absoluteThreshold, undefined);
+    run_next_test();
+  });
+});
+
+var testPageURL = "http://test.com";
+var testManifestURL = "http://test.com/manifest.webapp";
+
+add_test(function test_setAlarm() {
+  let alarm = { id: null,
+                networkId: wifiId,
+                threshold: 10000,
+                absoluteThreshold: null,
+                alarmStart: null,
+                alarmEnd: null,
+                data: null,
+                pageURL: testPageURL,
+                manifestURL: testManifestURL };
+
+  NetworkStatsService._setAlarm(alarm, function onSet(error, result) {
+    do_check_eq(result, 1);
+    run_next_test();
+  });
+});
+
+add_test(function test_setAlarm_invalid_threshold() {
+  let alarm = { id: null,
+                networkId: wifiId,
+                threshold: -10000,
+                absoluteThreshold: null,
+                alarmStart: null,
+                alarmEnd: null,
+                data: null,
+                pageURL: testPageURL,
+                manifestURL: testManifestURL };
+
+  NetworkStatsService._setAlarm(alarm, function onSet(error, result) {
+    do_check_eq(error, "InvalidStateError");
+    run_next_test();
+  });
+});
+
+add_test(function test_fireAlarm() {
+  // Add a fake alarm into database.
+  let alarm = { id: null,
+                networkId: wifiId,
+                threshold: 10000,
+                absoluteThreshold: null,
+                alarmStart: null,
+                alarmEnd: null,
+                data: null,
+                pageURL: testPageURL,
+                manifestURL: testManifestURL };
+
+  NetworkStatsService._db.addAlarm(alarm, function addSuccessCb(error, newId) {
+    NetworkStatsService._db.getAlarms(Ci.nsINetworkInterface.NETWORK_TYPE_WIFI,
+                                      testManifestURL, function onGet(error, result) {
+      do_check_eq(error, null);
+      do_check_eq(result.length, 1);
+
+      // Result of getAlarms is based on expected child's data format, so
+      // some changes are needed to be able to use it.
+      result[0].networkId = wifiId;
+      result[0].pageURL = testPageURL;
+      result[0].manifestURL = testManifestURL;
+
+      NetworkStatsService._fireAlarm(result[0], false);
+      NetworkStatsService._db.getAlarms(Ci.nsINetworkInterface.NETWORK_TYPE_WIFI,
+                                        testManifestURL, function onGet(error, result) {
+        do_check_eq(error, undefined);
+        do_check_eq(result.length, 0);
+        run_next_test();
+      });
+    });
+  });
+});
+
 function run_test() {
   do_get_profile();
 
   Cu.import("resource://gre/modules/NetworkStatsService.jsm");
   run_next_test();
 }