Check for balanced context.save() and context.restore() calls
[dygraphs.git] / auto_tests / tests / CanvasAssertions.js
index cd9994d..6481c60 100644 (file)
@@ -1,4 +1,4 @@
-// Copyright (c)  2011 Google, Inc.
+// Copyright (c) 2011 Google, Inc.
 //
 // Permission is hereby granted, free of charge, to any person obtaining a copy
 // of this software and associated documentation files (the "Software"), to deal
@@ -42,8 +42,8 @@ CanvasAssertions.assertLineDrawn = function(proxy, p1, p2, attrs) {
   // found = 1 when prior loop found p1.
   // found = 2 when prior loop found p2.
   var priorFound = 0;
-  for (var callNum in proxy.calls__) {
-    var call = proxy.calls__[callNum];
+  for (var i = 0; i < proxy.calls__.length; i++) {
+    var call = proxy.calls__[i];
 
     // This disables lineTo -> moveTo pairs.
     if (call.name == "moveTo" && priorFound > 0) {
@@ -83,7 +83,44 @@ CanvasAssertions.assertLineDrawn = function(proxy, p1, p2, attrs) {
   };
   fail("Can't find a line drawn between " + p1 +
       " and " + p2 + " with attributes " + toString(attrs));
-}
+};
+
+/**
+ * Verifies that every call to context.save() has a matching call to
+ * context.restore().
+ */
+CanvasAssertions.assertBalancedSaveRestore = function(proxy) {
+  var depth = 0;
+  for (var i = 0; i < proxy.calls__.length; i++) {
+    var call = proxy.calls__[i];
+    if (call.name == "save") depth++
+    if (call.name == "restore") {
+      if (depth == 0) {
+        fail("Too many calls to restore()");
+      }
+      depth--;
+    }
+  }
+
+  if (depth > 0) {
+    fail("Missing matching 'context.restore()' calls.");
+  }
+};
+
+/**
+ * Checks how many lines of the given color have been drawn.
+ * @return {Integer} The number of lines of the given color.
+ */
+CanvasAssertions.numLinesDrawn = function(proxy, color) {
+  var num_lines = 0;
+  for (var i = 0; i < proxy.calls__.length; i++) {
+    var call = proxy.calls__[i];
+    if (call.name == "lineTo" && call.properties.strokeStyle == color) {
+      num_lines++;
+    }
+  }
+  return num_lines;
+};
 
 CanvasAssertions.matchPixels = function(expected, actual) {
   // Expect array of two integers. Assuming the values are within one
@@ -91,7 +128,7 @@ CanvasAssertions.matchPixels = function(expected, actual) {
   // who knows what pixel a value of 5.8888 results in.
   return Math.abs(expected[0] - actual[0]) < 1 &&
       Math.abs(expected[1] - actual[1]) < 1;
-}
+};
 
 CanvasAssertions.matchAttributes = function(expected, actual) {
   for (var attr in expected) {
@@ -100,4 +137,4 @@ CanvasAssertions.matchAttributes = function(expected, actual) {
     }
   }
   return true;
-}
+};