Add Python virtualenv version checking

If the virtualenv is installed with a version of Python the doesnt
match the system installed version of Python, subtle errors can
occur (see BUG).

BUG=chromium:701914
TEST=Run venv tests

Change-Id: I6f4d98468e179ad2c40017463b527bd5d6f81605
Reviewed-on: https://chromium-review.googlesource.com/455988
Commit-Ready: Aviv Keshet <akeshet@chromium.org>
Tested-by: Allen Li <ayatane@chromium.org>
Reviewed-by: Aviv Keshet <akeshet@chromium.org>
Reviewed-by: Chris Ching <chingcodes@chromium.org>
diff --git a/cros_venv/venvlib.py b/cros_venv/venvlib.py
index c8edae0..85788c6 100644
--- a/cros_venv/venvlib.py
+++ b/cros_venv/venvlib.py
@@ -26,6 +26,12 @@
 _BASE_DEPENDENCIES = ('setuptools==28.2.0', 'pip==8.1.2')
 
 
+def _py_version(path):
+    """Get the version of the given Python binary."""
+    return subprocess.check_output(
+        [path, '-V'], stderr=subprocess.STDOUT).decode()
+
+
 class Venv(object):
     """Wraps all operations on a virtualenv directory."""
 
@@ -59,7 +65,7 @@
         """Create or update virtualenv."""
         _makedirs_exist_ok(self._venv_dir)
         with self._lock():
-            if not self._venv_initialized():
+            if not (self._venv_initialized() and self._venv_python_matches()):
                 self._init_venv()
             if not self._reqs_up_to_date():
                 self._install_reqs()
@@ -84,6 +90,16 @@
             # option can be removed.
             '--setuptools'])
 
+    def _venv_python_matches(self):
+        """Check if the Python version in virtualenv matches what we want.
+
+        If the virtualenv Python doesn't exist (hasn't been set up yet),
+        return False.
+        """
+        if not os.path.exists(self._venv_python):
+            return False
+        return _py_version(self._venv_python) == _py_version(_VENV_PY)
+
     def _reqs_up_to_date(self):
         """Return whether the virtualenv reqs file is up to date."""
         if not os.path.exists(self._installed_reqs_file):