Repository: FEniCS/ufl (language: python)

Issue:
Make tests pass flake8
Currently, the test directory is included in flake8's excludes. This should be removed and the tests should be made to pass flake8


Discussion / hints:

Fix patch:
diff --git a/setup.cfg b/setup.cfg
index 55704a7bb..7bcb914d4 100644
--- a/setup.cfg
+++ b/setup.cfg
@@ -59,7 +59,10 @@ ci =
 
 [flake8]
 max-line-length = 120
-exclude = doc/sphinx/source/conf.py,test
+exclude = doc/sphinx/source/conf.py
 
 [pydocstyle]
 convention = google
+
+[isort]
+line_length = 120


Test patch:
diff --git a/test/conftest.py b/test/conftest.py
index 2b2a2fb8e..e2c610a6e 100644
--- a/test/conftest.py
+++ b/test/conftest.py
@@ -1,11 +1,9 @@
-# -*- coding: utf-8 -*-
+import os
 
 import pytest
 
-import os
-
 import ufl
-from ufl import as_ufl, inner, dx
+from ufl import as_ufl, dx, inner
 from ufl.algorithms import compute_form_data
 
 
diff --git a/test/mockobjects.py b/test/mockobjects.py
index 6af48f43b..4c68e0e21 100644
--- a/test/mockobjects.py
+++ b/test/mockobjects.py
@@ -1,6 +1,4 @@
-# -*- coding: utf-8 -*-
-
-from ufl import *
+from ufl import Measure, Mesh, triangle
 
 
 class MockMesh:
@@ -15,7 +13,8 @@ def ufl_domain(self):
         return Mesh(triangle, ufl_id=self.ufl_id(), cargo=self)
 
     def ufl_measure(self, integral_type="dx", subdomain_id="everywhere", metadata=None, subdomain_data=None):
-        return Measure(integral_type, subdomain_id=subdomain_id, metadata=metadata, domain=self, subdomain_data=subdomain_data)
+        return Measure(integral_type, subdomain_id=subdomain_id, metadata=metadata, domain=self,
+                       subdomain_data=subdomain_data)
 
 
 class MockMeshFunction:
diff --git a/test/test_algorithms.py b/test/test_algorithms.py
index c68bb15c7..c752cfed0 100755
--- a/test/test_algorithms.py
+++ b/test/test_algorithms.py
@@ -1,5 +1,3 @@
-# -*- coding: utf-8 -*-
-
 __authors__ = "Martin Sandve Alnæs"
 __date__ = "2008-03-12 -- 2009-01-28"
 
@@ -7,16 +5,12 @@
 # Modified by Garth N. Wells, 2009
 
 import pytest
-from pprint import *
 
-from ufl import (FiniteElement, TestFunction, TrialFunction, Matrix, triangle,
-                 div, grad, Argument, dx, adjoint, Coefficient,
-                 FacetNormal, inner, dot, ds)
-from ufl.algorithms import (extract_arguments, expand_derivatives,
-                            expand_indices, extract_elements,
-                            extract_unique_elements, extract_coefficients)
-from ufl.corealg.traversal import (pre_traversal, post_traversal,
-                                   unique_pre_traversal, unique_post_traversal)
+from ufl import (Argument, Coefficient, FacetNormal, FiniteElement, TestFunction, TrialFunction, adjoint, div, dot, ds,
+                 dx, grad, inner, triangle)
+from ufl.algorithms import (expand_derivatives, expand_indices, extract_arguments, extract_coefficients,
+                            extract_elements, extract_unique_elements)
+from ufl.corealg.traversal import post_traversal, pre_traversal, unique_post_traversal, unique_pre_traversal
 
 # TODO: add more tests, covering all utility algorithms
 
@@ -64,7 +58,7 @@ def test_extract_coefficients_vs_fixture(coefficients, forms):
 def test_extract_elements_and_extract_unique_elements(forms):
     b = forms[2]
     integrals = b.integrals_by_type("cell")
-    integrand = integrals[0].integrand()
+    integrals[0].integrand()
 
     element1 = FiniteElement("CG", triangle, 1)
     element2 = FiniteElement("CG", triangle, 1)
diff --git a/test/test_analyse_demos.py b/test/test_analyse_demos.py
index 444aa926c..e9f41451d 100755
--- a/test/test_analyse_demos.py
+++ b/test/test_analyse_demos.py
@@ -1,13 +1,12 @@
-# -*- coding: utf-8 -*-
-
 __authors__ = "Martin Sandve Alnæs"
 __date__ = "2008-09-28 -- 2008-09-28"
 
 import os
-import pytest
-from ufl.algorithms import load_ufl_file, compute_form_data, validate_form
 from glob import glob
 
+import pytest
+
+from ufl.algorithms import load_ufl_file, validate_form
 
 demodir = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "demo"))
 
diff --git a/test/test_apply_algebra_lowering.py b/test/test_apply_algebra_lowering.py
index a66332313..97ad44b1c 100755
--- a/test/test_apply_algebra_lowering.py
+++ b/test/test_apply_algebra_lowering.py
@@ -1,9 +1,8 @@
-# -*- coding: utf-8 -*-
-
 import pytest
-from ufl import *
-from ufl.compound_expressions import *
+
+from ufl import Coefficient, FiniteElement, Index, TensorElement, as_tensor, interval, sqrt, tetrahedron, triangle
 from ufl.algorithms.renumbering import renumber_indices
+from ufl.compound_expressions import cross_expr, determinant_expr, inverse_expr
 
 
 @pytest.fixture
@@ -86,25 +85,25 @@ def test_inverse1(A1):
 
 
 def xtest_inverse2(A2):
-    expected = todo
+    expected = "TODO"
     assert inverse_expr(A2) == renumber_indices(expected)
 
 
 def xtest_inverse3(A3):
-    expected = todo
+    expected = "TODO"
     assert inverse_expr(A3) == renumber_indices(expected)
 
 
 def xtest_pseudo_inverse21(A21):
-    expected = todo
+    expected = "TODO"
     assert renumber_indices(inverse_expr(A21)) == renumber_indices(expected)
 
 
 def xtest_pseudo_inverse31(A31):
-    expected = todo
+    expected = "TODO"
     assert renumber_indices(inverse_expr(A31)) == renumber_indices(expected)
 
 
 def xtest_pseudo_inverse32(A32):
-    expected = todo
+    expected = "TODO"
     assert renumber_indices(inverse_expr(A32)) == renumber_indices(expected)
diff --git a/test/test_apply_function_pullbacks.py b/test/test_apply_function_pullbacks.py
index f0a00dd35..87bef3a4f 100755
--- a/test/test_apply_function_pullbacks.py
+++ b/test/test_apply_function_pullbacks.py
@@ -1,11 +1,10 @@
-#!/usr/bin/env py.test
-# -*- coding: utf-8 -*-
-
 import numpy
-from ufl import *
+
+from ufl import (Cell, Coefficient, FiniteElement, TensorElement, VectorElement, as_domain, as_tensor, as_vector, dx,
+                 indices, triangle)
 from ufl.algorithms.apply_function_pullbacks import apply_single_function_pullbacks
 from ufl.algorithms.renumbering import renumber_indices
-from ufl.classes import Jacobian, JacobianInverse, JacobianDeterminant, ReferenceValue, CellOrientation
+from ufl.classes import Jacobian, JacobianDeterminant, JacobianInverse, ReferenceValue
 
 
 def check_single_function_pullback(g, mappings):
@@ -115,7 +114,7 @@ def test_apply_single_function_pullbacks_triangle3d():
     detJ = JacobianDeterminant(domain)
     Jinv = JacobianInverse(domain)
     # o = CellOrientation(domain)
-    i, j, k, l = indices(4)
+    i, j, k, l = indices(4)  # noqa: E741
 
     # Contravariant H(div) Piola mapping:
     M_hdiv = ((1.0/detJ) * J)  # Not applying cell orientation here
@@ -147,16 +146,14 @@ def test_apply_single_function_pullbacks_triangle3d():
             # Vd
             *(as_tensor(M_hdiv[i, j]*as_vector([rvdm[3], rvdm[4]])[j], (i,))[n]
               for n in range(3))
-    ]),
-        vcm: as_vector([
+        ]), vcm: as_vector([
             # Vd
             *(as_tensor(M_hdiv[i, j]*as_vector([rvcm[0], rvcm[1]])[j], (i,))[n]
               for n in range(3)),
             # Vc
             *(as_tensor(Jinv[i, j]*as_vector([rvcm[2], rvcm[3]])[i], (j,))[n]
               for n in range(3))
-    ]),
-        tm: as_vector([
+        ]), tm: as_vector([
             # Vc
             *(as_tensor(Jinv[i, j]*as_vector([rtm[0], rtm[1]])[i], (j,))[n]
               for n in range(3)),
@@ -164,8 +161,7 @@ def test_apply_single_function_pullbacks_triangle3d():
             rtm[2], rtm[3], rtm[4],
             rtm[5], rtm[6], rtm[7],
             rtm[8], rtm[9], rtm[10],
-    ]),
-        sm: as_vector([
+        ]), sm: as_vector([
             # T
             rsm[0], rsm[1], rsm[2],
             rsm[3], rsm[4], rsm[5],
@@ -174,14 +170,14 @@ def test_apply_single_function_pullbacks_triangle3d():
             rsm[9], rsm[10], rsm[11],
             rsm[10], rsm[12], rsm[13],
             rsm[11], rsm[13], rsm[14],
-    ]),
+        ]),
         # Case from failing ffc demo:
         vd0m: as_vector([
             M_hdiv[0, j]*as_vector([rvd0m[0], rvd0m[1]])[j],
             M_hdiv[1, j]*as_vector([rvd0m[0], rvd0m[1]])[j],
             M_hdiv[2, j]*as_vector([rvd0m[0], rvd0m[1]])[j],
             rvd0m[2]
-    ]),
+        ]),
         # This combines it all:
         w: as_vector([
             # S
@@ -204,7 +200,7 @@ def test_apply_single_function_pullbacks_triangle3d():
             rw[21],
             # U
             rw[22],
-    ]),
+        ]),
     }
 
     # Check functions of various elements outside a mixed context
@@ -298,7 +294,7 @@ def test_apply_single_function_pullbacks_triangle():
     J = Jacobian(domain)
     detJ = JacobianDeterminant(domain)
     Jinv = JacobianInverse(domain)
-    i, j, k, l = indices(4)
+    i, j, k, l = indices(4)  # noqa: E741
 
     # Contravariant H(div) Piola mapping:
     M_hdiv = (1.0/detJ) * J
@@ -324,7 +320,7 @@ def test_apply_single_function_pullbacks_triangle():
             # Vd
             *(as_tensor(M_hdiv[i, j]*as_vector([rvdm[2], rvdm[3]])[j], (i,))[n]
               for n in range(2)),
-    ]),
+        ]),
         vcm: as_vector([
             # Vd
             *(as_tensor(M_hdiv[i, j]*as_vector([rvcm[0], rvcm[1]])[j], (i,))[n]
@@ -332,7 +328,7 @@ def test_apply_single_function_pullbacks_triangle():
             # Vc
             *(as_tensor(Jinv[i, j]*as_vector([rvcm[2], rvcm[3]])[i], (j,))[n]
               for n in range(2)),
-    ]),
+        ]),
         tm: as_vector([
             # Vc
             *(as_tensor(Jinv[i, j]*as_vector([rtm[0], rtm[1]])[i], (j,))[n]
@@ -340,7 +336,7 @@ def test_apply_single_function_pullbacks_triangle():
             # T
             rtm[2], rtm[3],
             rtm[4], rtm[5],
-    ]),
+        ]),
         sm: as_vector([
             # T
             rsm[0], rsm[1],
@@ -348,7 +344,7 @@ def test_apply_single_function_pullbacks_triangle():
             # S
             rsm[4], rsm[5],
             rsm[5], rsm[6],
-    ]),
+        ]),
         # This combines it all:
         w: as_vector([
             # S
@@ -368,7 +364,7 @@ def test_apply_single_function_pullbacks_triangle():
             rw[12],
             # U
             rw[13],
-    ]),
+        ]),
     }
 
     # Check functions of various elements outside a mixed context
diff --git a/test/test_apply_restrictions.py b/test/test_apply_restrictions.py
index 6e79c5f79..854a2458f 100755
--- a/test/test_apply_restrictions.py
+++ b/test/test_apply_restrictions.py
@@ -1,9 +1,7 @@
-#!/usr/bin/env py.test
-# -*- coding: utf-8 -*-
-
 from pytest import raises
-from ufl import *
-from ufl.algorithms.apply_restrictions import apply_restrictions, apply_default_restrictions
+
+from ufl import Coefficient, FacetNormal, FiniteElement, SpatialCoordinate, as_tensor, grad, i, triangle
+from ufl.algorithms.apply_restrictions import apply_default_restrictions, apply_restrictions
 from ufl.algorithms.renumbering import renumber_indices
 
 
diff --git a/test/test_arithmetic.py b/test/test_arithmetic.py
index cf26ff85c..ddb1883ad 100755
--- a/test/test_arithmetic.py
+++ b/test/test_arithmetic.py
@@ -1,10 +1,6 @@
-#!/usr/bin/env py.test
-# -*- coding: utf-8 -*-
-
-import pytest
-
-from ufl import *
-from ufl.classes import Division, FloatValue, IntValue, ComplexValue
+from ufl import (Identity, SpatialCoordinate, as_matrix, as_ufl, as_vector, elem_div, elem_mult, elem_op, sin,
+                 tetrahedron, triangle)
+from ufl.classes import ComplexValue, Division, FloatValue, IntValue
 
 
 def test_scalar_casting(self):
diff --git a/test/test_automatic_differentiation.py b/test/test_automatic_differentiation.py
index c91655655..60c3f4799 100755
--- a/test/test_automatic_differentiation.py
+++ b/test/test_automatic_differentiation.py
@@ -1,24 +1,22 @@
-#!/usr/bin/env py.test
-# -*- coding: utf-8 -*-
+"""Automatic differentiation tests.
 
-"""
 These tests should cover the behaviour of the automatic differentiation
 algorithm at a technical level, and are thus implementation specific.
 Other tests check for mathematical correctness of diff and derivative.
 """
 
 import pytest
-from itertools import chain
-
-import ufl
 
-# This imports everything external code will see from ufl
-from ufl import *
-
-import ufl.algorithms
-from ufl.corealg.traversal import unique_post_traversal
-from ufl.conditional import Conditional
+from ufl import (And, Argument, CellDiameter, CellVolume, Circumradius, Coefficient, Constant, FacetArea, FacetNormal,
+                 FiniteElement, Identity, Jacobian, JacobianDeterminant, JacobianInverse, MaxCellEdgeLength,
+                 MaxFacetEdgeLength, MinCellEdgeLength, MinFacetEdgeLength, Not, Or, PermutationSymbol,
+                 SpatialCoordinate, TensorElement, VectorElement, acos, as_matrix, as_tensor, as_ufl, as_vector, asin,
+                 atan, bessel_I, bessel_J, bessel_K, bessel_Y, cofac, conditional, cos, cross, derivative, det, dev,
+                 diff, dot, eq, erf, exp, ge, grad, gt, indices, inner, interval, inv, le, ln, lt, ne, outer, replace,
+                 sin, skew, sqrt, sym, tan, tetrahedron, tr, triangle, variable)
 from ufl.algorithms import expand_derivatives
+from ufl.conditional import Conditional
+from ufl.corealg.traversal import unique_post_traversal
 
 
 class ExpressionCollection(object):
@@ -43,7 +41,7 @@ def __init__(self, cell):
         invJ = JacobianInverse(cell)
         # FIXME: Add all new geometry types here!
 
-        I = Identity(d)
+        ident = Identity(d)
         eps = PermutationSymbol(d)
 
         U = FiniteElement("U", cell, None)
@@ -63,7 +61,7 @@ class ObjectCollection(object):
         for key, value in list(locals().items()):
             setattr(self.shared_objects, key, value)
 
-        self.literals = list(map(as_ufl, [0, 1, 3.14, I, eps]))
+        self.literals = list(map(as_ufl, [0, 1, 3.14, ident, eps]))
         self.geometry = [x, n, c, R, h, f, mince, maxce, minfe, maxfe, J, detJ, invJ]
         self.functions = [u, du, v, dv, w, dw]
 
@@ -99,10 +97,10 @@ class ObjectCollection(object):
                             (u**6, u**7, u**8)))
 
         # Indexed,  ListTensor, ComponentTensor, IndexSum
-        i, j, k, l = indices(4)
+        i, j, k, l = indices(4)  # noqa: E741
         self.indexing = ([
                 v[0], w[d-1, 0], v[i], w[i, j],
-                v[:], w[0,:], w[:, 0],
+                v[:], w[0, :], w[:, 0],
                 v[...], w[0, ...], w[..., 0],
                 v[i]*v[j], w[i, 0]*v[j], w[d-1, j]*v[i],
                 v[i]*v[i], w[i, 0]*w[0, i], v[i]*w[0, i],
@@ -178,7 +176,7 @@ class ObjectCollection(object):
             self.crossproducts = ([
                 cross(v, v),
                 cross(v, 2*v),
-                cross(v, w[0,:]),
+                cross(v, w[0, :]),
                 cross(v, w[:, 1]),
                 cross(w[:, 0], v),
             ])
@@ -210,27 +208,32 @@ def ad_algorithm(expr):
     if alt == 0:
         return expand_derivatives(expr)
     elif alt == 1:
-        return expand_derivatives(expr,
+        return expand_derivatives(
+            expr,
             apply_expand_compounds_before=True,
             apply_expand_compounds_after=False,
             use_alternative_wrapper_algorithm=True)
     elif alt == 2:
-        return expand_derivatives(expr,
+        return expand_derivatives(
+            expr,
             apply_expand_compounds_before=False,
             apply_expand_compounds_after=True,
             use_alternative_wrapper_algorithm=False)
     elif alt == 3:
-        return expand_derivatives(expr,
+        return expand_derivatives(
+            expr,
             apply_expand_compounds_before=False,
             apply_expand_compounds_after=False,
             use_alternative_wrapper_algorithm=False)
     elif alt == 4:
-        return expand_derivatives(expr,
+        return expand_derivatives(
+            expr,
             apply_expand_compounds_before=False,
             apply_expand_compounds_after=False,
             use_alternative_wrapper_algorithm=True)
     elif alt == 5:
-        return expand_derivatives(expr,
+        return expand_derivatives(
+            expr,
             apply_expand_compounds_before=False,
             apply_expand_compounds_after=False,
             use_alternative_wrapper_algorithm=False)
@@ -253,7 +256,7 @@ def _test_no_derivatives_but_still_changed(self, collection):
         # print '\n', str(before), '\n', str(after), '\n'
         self.assertEqualTotalShape(before, after)
         # assert before == after # Without expand_compounds
-        self.assertNotEqual(before, after) # With expand_compounds
+        self.assertNotEqual(before, after)  # With expand_compounds
 
 
 def test_only_terminals_no_change(self, d_expr):
@@ -266,7 +269,7 @@ def test_no_derivatives_no_change(self, d_expr):
     _test_no_derivatives_no_change(self, ex.noncompounds)
 
 
-def xtest_compounds_no_derivatives_no_change(self, d_expr): # This test fails with expand_compounds enabled
+def xtest_compounds_no_derivatives_no_change(self, d_expr):  # This test fails with expand_compounds enabled
     d, ex = d_expr
     _test_no_derivatives_no_change(self, ex.compounds)
 
@@ -285,13 +288,13 @@ def _test_zero_derivatives_of_terminals_produce_the_right_types_and_shapes(self,
 
     for t in collection.terminals:
         for var in (u, v, w):
-            before = derivative(t, var) # This will often get preliminary simplified to zero
+            before = derivative(t, var)  # This will often get preliminary simplified to zero
             after = ad_algorithm(before)
             expected = 0*t
             # print '\n', str(expected), '\n', str(after), '\n', str(before), '\n'
             assert after == expected
 
-            before = derivative(c*t, var) # This will usually not get simplified to zero
+            before = derivative(c*t, var)  # This will usually not get simplified to zero
             after = ad_algorithm(before)
             expected = 0*t
             # print '\n', str(expected), '\n', str(after), '\n', str(before), '\n'
@@ -315,13 +318,13 @@ def _test_zero_diffs_of_terminals_produce_the_right_types_and_shapes(self, colle
     vw = variable(w)
     for t in collection.terminals:
         for var in (vu, vv, vw):
-            before = diff(t, var) # This will often get preliminary simplified to zero
+            before = diff(t, var)  # This will often get preliminary simplified to zero
             after = ad_algorithm(before)
             expected = 0*outer(t, var)
             # print '\n', str(expected), '\n', str(after), '\n', str(before), '\n'
             assert after == expected
 
-            before = diff(c*t, var) # This will usually not get simplified to zero
+            before = diff(c*t, var)  # This will usually not get simplified to zero
             after = ad_algorithm(before)
             expected = 0*outer(t, var)
             # print '\n', str(expected), '\n', str(after), '\n', str(before), '\n'
@@ -454,7 +457,7 @@ def _test_nonzero_diffs_of_noncompounds_produce_the_right_types_and_shapes(self,
 
     # for t in chain(collection.noncompounds, collection.compounds):
     for t in collection.noncompounds:
-        t = replace(t, {u:vu, v:vv, w:vw})
+        t = replace(t, {u: vu, v: vv, w: vw})
         for var in (vu, vv, vw):
             # Include d/dx [z ? y: x] but not d/dx [x ? f: z]
             if isinstance(t, Conditional) and (var in unique_post_traversal(t.ufl_operands[0])):
@@ -468,7 +471,7 @@ def _test_nonzero_diffs_of_noncompounds_produce_the_right_types_and_shapes(self,
             after = ad_algorithm(before)
             if debug:
                 print(('\n', 'after:    ', str(after), '\n'))
-            expected_shape = 0*outer(t, var) # expected shape, not necessarily value
+            expected_shape = 0*outer(t, var)  # expected shape, not necessarily value
             if debug:
                 print(('\n', 'expected_shape: ', str(expected_shape), '\n'))
             # print '\n', str(expected_shape), '\n', str(after), '\n', str(before), '\n'
@@ -495,7 +498,7 @@ def test_grad_coeff(self, d_expr):
             print(('\n', str(before), '\n', str(after), '\n'))
 
         self.assertEqualTotalShape(before, after)
-        if f is u: # Differing by being wrapped in indexing types
+        if f is u:  # Differing by being wrapped in indexing types
             assert before == after
 
         before = grad(grad(f))
diff --git a/test/test_book_snippets.py b/test/test_book_snippets.py
index a740014dc..ed1088405 100755
--- a/test/test_book_snippets.py
+++ b/test/test_book_snippets.py
@@ -1,6 +1,5 @@
-#!/usr/bin/env py.test
-# -*- coding: utf-8 -*-
-"""
+"""Test book snippets.
+
 This file contains snippets from the FEniCS book,
 and allows us to test that these can still run
 with future versions of UFL. Please don't change
@@ -8,10 +7,14 @@
 snippets as long as possible.
 """
 
-import pytest
-
-from ufl import *
-from ufl.algorithms import *
+from ufl import (Argument, Cell, Coefficient, Coefficients, Constant, Dx, FiniteElement, Identity, Index, MixedElement,
+                 SpatialCoordinate, TensorConstant, TensorElement, TestFunction, TestFunctions, TrialFunction,
+                 TrialFunctions, VectorConstant, VectorElement, action, adjoint, as_matrix, as_tensor, as_ufl,
+                 conditional, cos, derivative, diff, dot, ds, dx, exp, grad, i, indices, inner, j, k, lt, outer, pi,
+                 replace, sensitivity_rhs, sin, split, system, tetrahedron, tr, triangle, variable)
+from ufl.algorithms import (Transformer, compute_form_data, expand_compounds, expand_derivatives, expand_indices,
+                            post_traversal, tree_format)
+from ufl.corealg.multifunction import MultiFunction
 
 
 def test_uflcode_269(self):
@@ -27,8 +30,8 @@ def test_uflcode_269(self):
     c2 = Constant(cell)
 
     # Deformation gradient Fij = dXi/dxj
-    I = Identity(cell.geometric_dimension())
-    F = I + grad(u)
+    ident = Identity(cell.geometric_dimension())
+    F = ident + grad(u)
 
     # Right Cauchy-Green strain tensor C with invariants
     C = variable(F.T*F)
@@ -43,16 +46,16 @@ def test_uflcode_269(self):
 
     # Weak forms
     L = inner(F*S, grad(phi0))*dx
-    a = derivative(L, u, phi1)
+    derivative(L, u, phi1)
 
 
 def test_uflcode_316(self):
     shapestring = 'triangle'
-    cell = Cell(shapestring)
+    cell = Cell(shapestring)  # noqa: F841
 
 
 def test_uflcode_323(self):
-    cell = tetrahedron
+    cell = tetrahedron  # noqa: F841
 
 
 def test_uflcode_356(self):
@@ -62,8 +65,8 @@ def test_uflcode_356(self):
     V = VectorElement("Lagrange", cell, 2)
     T = TensorElement("DG", cell, 0, symmetry=True)
 
-    TH = V*P
-    ME = MixedElement(T, V, P)
+    TH = V*P  # noqa: F841
+    ME = MixedElement(T, V, P)  # noqa: F841
 
 
 def test_uflcode_400(self):
@@ -75,8 +78,8 @@ def test_uflcode_400(self):
     v = TestFunction(V)
     u = TrialFunction(V)
     # ...
-    a = w*dot(grad(u), grad(v))*dx
-    L = f*v*dx + g**2*v*ds(0) + h*v*ds(1)
+    a = w*dot(grad(u), grad(v))*dx  # noqa: F841
+    L = f*v*dx + g**2*v*ds(0) + h*v*ds(1)  # noqa: F841
 
 
 def test_uflcode_469(self):
@@ -89,25 +92,25 @@ def test_uflcode_469(self):
     dx02 = dx(0, {"integration_order": 2})
     dx14 = dx(1, {"integration_order": 4})
     dx12 = dx(1, {"integration_order": 2})
-    L = f*v*dx02 + g*v*dx14 + h*v*dx12
+    L = f*v*dx02 + g*v*dx14 + h*v*dx12  # noqa: F841
 
 
 def test_uflcode_552(self):
     element = FiniteElement("CG", triangle, 1)
     # ...
-    phi = Argument(element, 2)
-    v = TestFunction(element)
-    u = TrialFunction(element)
+    phi = Argument(element, 2)  # noqa: F841
+    v = TestFunction(element)  # noqa: F841
+    u = TrialFunction(element)  # noqa: F841
 
 
 def test_uflcode_563(self):
     cell = triangle
     element = FiniteElement("CG", cell, 1)
     # ...
-    w = Coefficient(element)
-    c = Constant(cell)
-    v = VectorConstant(cell)
-    M = TensorConstant(cell)
+    w = Coefficient(element)  # noqa: F841
+    c = Constant(cell)  # noqa: F841
+    v = VectorConstant(cell)  # noqa: F841
+    M = TensorConstant(cell)  # noqa: F841
 
 
 def test_uflcode_574(self):
@@ -138,7 +141,7 @@ def test_uflcode_644(self):
     v = Coefficient(V)
     # ...
     A = outer(u, v)
-    Aij = A[i, j]
+    Aij = A[i, j]  # noqa: F841
 
 
 def test_uflcode_651(self):
@@ -147,12 +150,12 @@ def test_uflcode_651(self):
     v = Coefficient(V)
     # ...
     Aij = v[j]*u[i]
-    A = as_tensor(Aij, (i, j))
+    A = as_tensor(Aij, (i, j))  # noqa: F841
 
 
 def test_uflcode_671(self):
-    i = Index()
-    j, k, l = indices(3)
+    i = Index()  # noqa: F841
+    j, k, l = indices(3)  # noqa: F841, E741
 
 
 def test_uflcode_684(self):
@@ -162,7 +165,7 @@ def test_uflcode_684(self):
     th = pi/2
     A = as_matrix([[cos(th), -sin(th)],
                    [sin(th), cos(th)]])
-    u = A*v
+    u = A*v  # noqa: F841
 
 
 def test_uflcode_824(self):
@@ -170,7 +173,7 @@ def test_uflcode_824(self):
     f = Coefficient(V)
     # ...
     df = Dx(f, i)
-    df = f.dx(i)
+    df = f.dx(i)  # noqa: F841
 
 
 def test_uflcode_886(self):
@@ -180,33 +183,18 @@ def test_uflcode_886(self):
     g = sin(x[0])
     v = variable(g)
     f = exp(v**2)
-    h = diff(f, v)
+    h = diff(f, v)  # noqa: F841
     # ...
     # print v
     # print h
 
 
-def test_python_894(self):
-    # We don't have to keep the string output compatible, so no test here.
-    pass
-    #>>> print v
-    # var0(sin((x)[0]))
-    #>>> print h
-    # d/d[var0(sin((x)[0]))] (exp((var0(sin((x)[0]))) ** 2))
-
-
 def test_uflcode_930(self):
     condition = lt(1, 0)
     true_value = 1
     false_value = 0
     # ...
-    f = conditional(condition, true_value, false_value)
-
-
-def test_uflcode_1003(self):
-    # Not testable, but this is tested below anyway
-    "a = derivative(L, w, u)"
-    pass
+    f = conditional(condition, true_value, false_value)  # noqa: F841
 
 
 def test_uflcode_1026(self):
@@ -217,7 +205,7 @@ def test_uflcode_1026(self):
     w = Coefficient(element)
     f = 0.5*w**2*dx
     F = derivative(f, w, v)
-    J = derivative(F, w, u)
+    J = derivative(F, w, u)  # noqa: F841
 
 
 def test_uflcode_1050(self):
@@ -227,7 +215,7 @@ def test_uflcode_1050(self):
     x, y = split(u)
     f = inner(grad(x), grad(x))*dx + y*dot(x, x)*dx
     F = derivative(f, u)
-    J = derivative(F, u)
+    J = derivative(F, u)  # noqa: F841
 
 
 def test_uflcode_1085(self):
@@ -239,7 +227,7 @@ def test_uflcode_1085(self):
     v = TestFunction(V)
     M = Coefficient(T)
     a = M[i, j]*u[k].dx(j)*v[k].dx(i)*dx
-    astar = adjoint(a)
+    astar = adjoint(a)  # noqa: F841
 
 
 def test_uflcode_1120(self):
@@ -250,8 +238,8 @@ def test_uflcode_1120(self):
     f = Coefficient(V)
     g = Coefficient(V)
     L = f**2 / (2*g)*v*dx
-    L2 = replace(L, {f: g, g: 3})
-    L3 = g**2 / 6*v*dx
+    L2 = replace(L, {f: g, g: 3})  # noqa: F841
+    L3 = g**2 / 6*v*dx  # noqa: F841
 
 
 def test_uflcode_1157(self):
@@ -277,7 +265,7 @@ def test_uflcode_1190(self):
     a, L = system(pde)
     # ...
     u = Coefficient(element)
-    sL = diff(L, c) - action(diff(a, c), u)
+    sL = diff(L, c) - action(diff(a, c), u)  # noqa: F841
 
 
 def test_uflcode_1195(self):
@@ -292,22 +280,14 @@ def test_uflcode_1195(self):
     a, L = system(pde)
     u = Coefficient(element)
     # ...
-    sL = sensitivity_rhs(a, u, L, c)
+    sL = sensitivity_rhs(a, u, L, c)  # noqa: F841
 
 
 def test_uflcode_1365(self):
     e = 0
     v = variable(e)
     f = sin(v)
-    g = diff(f, v)
-
-
-def test_python_1426(self):
-    # Covered by the below test
-    pass
-    # from ufl.algorithms import Graph
-    # G = Graph(expression)
-    # V, E = G
+    g = diff(f, v)  # noqa: F841
 
 
 def test_python_1446(self):
@@ -317,7 +297,7 @@ def test_python_1446(self):
     v = TestFunction(V)
     c = Constant(cell)
     f = Coefficient(V)
-    e = c*f**2*u*v
+    e = c*f**2*u*v  # noqa: F841
 
     # The linearized Graph functionality has been removed from UFL:
     # from ufl.algorithms import Graph, partition
@@ -336,7 +316,7 @@ def test_python_1512(self):
     v = TestFunction(V)
     c = Constant(cell)
     f = Coefficient(V)
-    e = c*f**2*u*v
+    e = c*f**2*u*v  # noqa: F841
 
     # The linearized Graph functionality has been removed from UFL:
     # from ufl.algorithms import Graph, partition
@@ -354,7 +334,7 @@ def test_python_1557(self):
     v = TestFunction(V)
     c = Constant(cell)
     f = Coefficient(V)
-    e = c*f**2*u*v
+    e = c*f**2*u*v  # noqa: F841
 
     # The linearized Graph functionality has been removed from UFL:
     # from ufl.algorithms import Graph, partition
@@ -371,23 +351,12 @@ def test_python_1557(self):
     #        v = V[i]
 
 
-def test_python_1843(self):
-    def apply_ad(e, ad_routine):
-        if e._ufl_is_terminal_:
-            return e
-        ops = [apply_ad(o, ad_routine) for o in e.ufl_operands]
-        e = e._ufl_expr_reconstruct_(*ops)
-        if isinstance(e, Derivative):
-            e = ad_routine(e)
-        return e
-
-
 def test_uflcode_1901(self):
     cell = triangle
     element = FiniteElement("Lagrange", cell, 1)
     # ...
-    v = Argument(element, 2)
-    w = Coefficient(element)
+    v = Argument(element, 2)  # noqa: F841
+    w = Coefficient(element)  # noqa: F841
 
 
 def test_python_1942(self):
@@ -422,18 +391,12 @@ def post_action(e):
 
 
 def test_python_1990(self):
-    from ufl.classes import IntValue, Sum
     expression = as_ufl(3)
 
     def int_operation(x):
         return 7
-    # ...
-    if isinstance(expression, IntValue):
-        result = int_operation(expression)
-    elif isinstance(expression, Sum):
-        result = sum_operation(expression)
-    # etc.
-    # ...
+
+    result = int_operation(expression)
     self.assertTrue(result == 7)
 
 
@@ -488,7 +451,7 @@ def terminal(self, e):
 
     f = Constant(triangle)
     r = Replacer({f: f**2})
-    g = r.visit(2*f)
+    g = r.visit(2*f)  # noqa: F841
 
 
 def test_python_2189(self):
@@ -504,10 +467,10 @@ def test_python_2189(self):
     ad = expand_derivatives(ac)
     ai = expand_indices(ad)
 
-    af = tree_format(a)
-    acf = tree_format(ac)
-    adf = "\n", tree_format(ad)
-    aif = tree_format(ai)
+    af = tree_format(a)  # noqa: F841
+    acf = tree_format(ac)  # noqa: F841
+    adf = "\n", tree_format(ad)  # noqa: F841
+    aif = tree_format(ai)  # noqa: F841
 
     if 0:
         print(("\na: ", str(a), "\n", tree_format(a)))
@@ -581,4 +544,4 @@ def test_python_2462(self):
     # ...
     # print repr(preprocess(myform).preprocessed_form)
     # ...
-    r = repr(compute_form_data(myform).preprocessed_form)
+    r = repr(compute_form_data(myform).preprocessed_form)  # noqa: F841
diff --git a/test/test_cell.py b/test/test_cell.py
index 8ec754622..5d9472a1d 100644
--- a/test/test_cell.py
+++ b/test/test_cell.py
@@ -1,6 +1,7 @@
-import ufl
 import pytest
 
+import ufl
+
 
 def test_interval():
     cell = ufl.interval
@@ -51,7 +52,6 @@ def test_tesseract():
     assert cell.num_faces() == 24
 
 
-
 @pytest.mark.parametrize("cell", [ufl.interval])
 def test_cells_1d(cell):
     assert cell.num_facets() == cell.num_vertices()
diff --git a/test/test_change_to_local.py b/test/test_change_to_local.py
index b123c054f..80bdb2101 100755
--- a/test/test_change_to_local.py
+++ b/test/test_change_to_local.py
@@ -1,15 +1,9 @@
-#!/usr/bin/env py.test
-# -*- coding: utf-8 -*-
-"""
-Tests of the change to local representaiton algorithms.
-"""
+"""Tests of the change to local representaiton algorithms."""
 
-import pytest
-
-from ufl import *
-from ufl.classes import ReferenceGrad, JacobianInverse
-from ufl.algorithms import tree_format, change_to_reference_grad
+from ufl import Coefficient, FiniteElement, FunctionSpace, Mesh, VectorElement, as_tensor, grad, indices, triangle
+from ufl.algorithms import change_to_reference_grad
 from ufl.algorithms.renumbering import renumber_indices
+from ufl.classes import JacobianInverse, ReferenceGrad
 
 
 def test_change_to_reference_grad():
@@ -58,8 +52,8 @@ def test_change_to_reference_grad():
 
     expr = grad(grad(grad(v)))
     actual = change_to_reference_grad(expr)
-    expected = as_tensor(
-        Jinv[s, k] * (Jinv[r, j] * (Jinv[q, i] * ReferenceGrad(ReferenceGrad(ReferenceGrad(v)))[t, q, r, s])), (t, i, j, k))
+    expected = as_tensor(Jinv[s, k] * (Jinv[r, j] * (
+        Jinv[q, i] * ReferenceGrad(ReferenceGrad(ReferenceGrad(v)))[t, q, r, s])), (t, i, j, k))
     assert renumber_indices(actual) == renumber_indices(expected)
 
     # print tree_format(expected)
diff --git a/test/test_change_to_reference_frame.py b/test/test_change_to_reference_frame.py
index 264d12463..c70076856 100755
--- a/test/test_change_to_reference_frame.py
+++ b/test/test_change_to_reference_frame.py
@@ -1,76 +1,12 @@
-#!/usr/bin/env py.test
-# -*- coding: utf-8 -*-
 """Tests of the change to reference frame algorithm."""
 
-import pytest
-
-from ufl import *
-
-from ufl.classes import Form, Integral, Expr, ReferenceGrad, ReferenceValue
-
-'''
-from ufl.classes import ReferenceGrad, JacobianInverse
-from ufl.algorithms import tree_format, change_to_reference_grad
-
-from ufl.log import error, warning
-
-from ufl.core.multiindex import Index, indices
-from ufl.corealg.multifunction import MultiFunction
-from ufl.corealg.map_dag import map_expr_dag
-
-from ufl.classes import (Expr, FormArgument, GeometricQuantity,
-                         Terminal, ReferenceGrad, Grad, Restricted, ReferenceValue,
-                         Jacobian, JacobianInverse, JacobianDeterminant,
-                         FacetJacobian, FacetJacobianInverse, FacetJacobianDeterminant,
-                         CellFacetJacobian,
-                         ReferenceCellEdgeVectors, ReferenceFacetEdgeVectors,
-                         FacetNormal, CellNormal, ReferenceNormal,
-                         CellVolume, FacetArea,
-                         CellOrientation, FacetOrientation, QuadratureWeight,
-                         SpatialCoordinate, Indexed, MultiIndex, FixedIndex)
-
-from ufl.constantvalue import as_ufl, Identity
-from ufl.tensoralgebra import Transposed
-from ufl.tensors import as_tensor, as_vector, as_scalar, ComponentTensor
-from ufl.operators import sqrt, max_value, min_value, sign
-from ufl.permutation import compute_indices
-
-from ufl.algorithms.transformer import ReuseTransformer, apply_transformer
-from ufl.compound_expressions import determinant_expr, cross_expr, inverse_expr
-from ufl.finiteelement import FiniteElement, EnrichedElement, VectorElement, MixedElement, TensorProductElement, TensorElement, FacetElement, InteriorElement, BrokenElement.
-'''
-
-
-def change_integral_to_reference_frame(form, context):
-    if False:  # TODO: integral.is_in_reference_frame():
-        # TODO: Assume reference frame integral is written purely in
-        #       reference frame or tramsform integrand here as well?
-        return integrand
-    else:
-        # Change integrand expression to reference frame
-        integrand = change_to_reference_frame(integral.integrand())
-
-        # Compute and apply integration scaling factor
-        scale, degree = compute_integrand_scaling_factor(integral.ufl_domain(),
-                                                         integral.integral_type())
-
-        return integral.reconstruct(integrand * scale)  # TODO: , reference=True)
-
-
-def change_expr_to_reference_frame(expr):
-    expr = ReferenceValue(expr)
-    return expr
+from ufl import Coefficient, FiniteElement, TensorElement, VectorElement, triangle
+from ufl.classes import Expr, ReferenceValue
 
 
 def change_to_reference_frame(expr):
-    if isinstance(expr, Form):
-        return change_form_to_reference_frame(expr)
-    elif isinstance(expr, Integral):
-        return change_integral_to_reference_frame(expr)
-    elif isinstance(expr, Expr):
-        return change_expr_to_reference_frame(expr)
-    else:
-        error("Invalid type.")
+    assert isinstance(expr, Expr)
+    return ReferenceValue(expr)
 
 
 def test_change_unmapped_form_arguments_to_reference_frame():
@@ -174,100 +110,6 @@ def test_change_hcurl_form_arguments_to_reference_frame():
     '''
 
 
-def new_analyse_modified_terminal(expr):
-    assert expr._ufl_is_terminal_ or expr._ufl_is_terminal_modifier_type_
-    m = expr
-
-    # The outermost expression may index to get a specific scalar value
-    if isinstance(m, Indexed):
-        unindexed, multi_index = m.ufl_operands
-        indices = tuple(int(i) for i in multi_index)
-    else:
-        unindexed = m
-        indices = ()
-
-    # The evaluation mode is one of current point,
-    # a cell entity midpoint, or averaging over a cell entity
-    if unindexed._ufl_is_evaluation_type_:  # averages and point evaluations
-        v, = v.ufl_operand
-        evaluation = unindexed.ufl_handler_name
-    else:
-        v = unindexed
-        evaluation = "current_point"
-
-    # We're either in reference frame or global, checks below ensure we don't mix the two
-    frame = "reference" if v._ufl_is_reference_type_ else "global"
-
-    # Peel off derivatives (grad^n,div,curl,div(grad),grad(div) etc.)
-    t = v
-    derivatives = []
-    while t._ufl_is_derivative_type_:
-        # ensure frame consistency
-        assert t._ufl_is_reference_type_ == v._ufl_is_reference_type_
-        derivatives.append(t._ufl_class_)
-        t, = t.ufl_operands
-    core = t
-    derivatives = tuple(derivatives)
-
-    # This can be an intermediate step to use derivatives instead of ngrads:
-    num_derivatives = len(derivatives)
-
-    # If we had a reference type before unwrapping terminal,
-    # there should be a ReferenceValue inside all the derivatives
-    if v._ufl_is_reference_type_:
-        assert isinstance(t, ReferenceValue)
-        t, = t.ufl_operands
-
-    # At the core we may have a restriction
-    if t._ufl_is_restriction_type_:
-        restriction = t.side()
-        t, = t.ufl_operands
-    else:
-        restriction = ""
-
-    # And then finally the terminal
-    assert t._ufl_is_terminal_
-    terminal = t
-
-    # This will only be correct for derivatives = grad^n
-    gdim = terminal.ufl_domain().geometric_dimension()
-    derivatives_shape = (gdim,)*num_derivatives
-
-    # Get shapes
-    expr_shape = expr.ufl_shape
-    unindexed_shape = unindexed.ufl_shape
-    core_shape = core.ufl_shape
-
-    # Split indices
-    core_indices = indices[:len(core_shape)]
-    derivative_indices = indices[len(core_shape):]
-
-    # Apply paranoid dimension checking
-    assert len(indices) == len(unindexed_shape)
-    assert all(0 <= i for i in indices)
-    assert all(i < j for i, j in zip(indices, unindexed_shape))
-    assert len(core_indices) == len(core_shape)
-    assert all(0 <= i for i in core_indices)
-    assert all(i < j for i, j in zip(core_indices, core_shape))
-    assert len(derivative_indices) == len(derivatives_shape)  # This will fail for e.g. div(grad(f))
-    assert all(0 <= i for i in derivative_indices)
-    assert all(i < j for i, j in zip(derivative_indices, derivatives_shape))
-
-    # Return values:
-    mt = ModifiedTerminal(
-        # TODO: Use keyword args
-        expr,
-        indices,
-        evaluation,
-        frame,
-        num_derivatives,
-        derivatives,
-        restriction,
-        terminal
-    )
-    return mt
-
-
 '''
 New form preprocessing pipeline:
 
@@ -281,9 +123,13 @@ def new_analyse_modified_terminal(expr):
 ii) process integrands:
     a) apply_coefficient_completion # replace coefficients to ensure proper elements and domains
     b) lower_compound_operators # expand_compounds
-    c) change_to_reference_frame # change f->rv(f), m->M*rv(m), grad(f)->K*rgrad(rv(f)), grad(grad(f))->K*rgrad(K*rgrad(rv(f))), grad(expr)->K*rgrad(expr)
-                                 # if grad(expr)->K*rgrad(expr) should be valid, then rgrad must be applicable to quite generic expressions
-    d) apply_derivatives         # one possibility is to add an apply_mapped_derivatives AD algorithm which includes mappings
+    c) change_to_reference_frame # change f->rv(f), m->M*rv(m),
+                                          grad(f)->K*rgrad(rv(f)),
+                                          grad(grad(f))->K*rgrad(K*rgrad(rv(f))), grad(expr)->K*rgrad(expr)
+                                 # if grad(expr)->K*rgrad(expr) should be valid,
+                                   then rgrad must be applicable to quite generic expressions
+    d) apply_derivatives         # one possibility is to add an apply_mapped_derivatives AD
+                                   algorithm which includes mappings
     e) apply_geometry_lowering
     f) apply_restrictions # requiring grad(f)('+') instead of grad(f('+')) would simplify a lot...
 iii) extract final metadata about elements and coefficient ordering
diff --git a/test/test_check_arities.py b/test/test_check_arities.py
index bf2a5b324..0d5521ac2 100755
--- a/test/test_check_arities.py
+++ b/test/test_check_arities.py
@@ -1,9 +1,9 @@
-#!/usr/bin/env py.test
-# -*- coding: utf-8 -*-
 import pytest
-from ufl import *
-from ufl.algorithms.compute_form_data import compute_form_data
+
+from ufl import (Coefficient, FacetNormal, FunctionSpace, Mesh, SpatialCoordinate, TestFunction, TrialFunction,
+                 VectorElement, adjoint, cofac, conj, derivative, ds, dx, grad, inner, tetrahedron)
 from ufl.algorithms.check_arities import ArityMismatch
+from ufl.algorithms.compute_form_data import compute_form_data
 
 
 def test_check_arities():
@@ -26,11 +26,9 @@ def test_check_arities():
     L = derivative(M, u, dv)
     a = derivative(L, u, du)
 
-    fd = compute_form_data(M)
-    fd = compute_form_data(L)
-    fd = compute_form_data(a)
-
-    assert True
+    compute_form_data(M)
+    compute_form_data(L)
+    compute_form_data(a)
 
 
 def test_complex_arities():
diff --git a/test/test_classcoverage.py b/test/test_classcoverage.py
index af96b4e6e..28bb83776 100755
--- a/test/test_classcoverage.py
+++ b/test/test_classcoverage.py
@@ -1,16 +1,21 @@
-#!/usr/bin/env py.test
-# -*- coding: utf-8 -*-
-
 __authors__ = "Martin Sandve Alnæs"
 __date__ = "2008-09-06 -- 2009-02-10"
 
-import pytest
-
 import ufl
-from ufl import *
-from ufl.constantvalue import as_ufl
-from ufl.classes import *
-from ufl.algorithms import *
+from ufl import *  # noqa: F403, F401
+from ufl import (And, Argument, CellDiameter, CellVolume, Circumradius, Coefficient, Constant, FacetArea, FacetNormal,
+                 FiniteElement, Identity, Jacobian, JacobianDeterminant, JacobianInverse, MaxFacetEdgeLength,
+                 MinFacetEdgeLength, MixedElement, Not, Or, PermutationSymbol, SpatialCoordinate, TensorConstant,
+                 TensorElement, VectorConstant, VectorElement, acos, action, as_matrix, as_tensor, as_ufl, as_vector,
+                 asin, atan, cell_avg, cofac, conditional, cos, cosh, cross, curl, derivative, det, dev, diff, div, dot,
+                 ds, dS, dx, eq, exp, facet_avg, ge, grad, gt, i, inner, inv, j, k, l, le, ln, lt, nabla_div,
+                 nabla_grad, ne, outer, rot, sin, sinh, skew, sqrt, sym, tan, tanh, tetrahedron, tr, transpose,
+                 triangle, variable)
+from ufl.algorithms import *  # noqa: F403, F401
+from ufl.classes import *  # noqa: F403, F401
+from ufl.classes import (Acos, Asin, Atan, CellCoordinate, Cos, Cosh, Exp, Expr, FacetJacobian,
+                         FacetJacobianDeterminant, FacetJacobianInverse, FloatValue, IntValue, Ln, Outer, Sin, Sinh,
+                         Sqrt, Tan, Tanh, all_ufl_classes)
 
 has_repr = set()
 has_dict = set()
@@ -29,7 +34,7 @@ def _test_object(a, shape, free_indices):
     assert hash(a) == hash(e)
 
     # Can't really test str more than that it exists
-    s = str(a)
+    str(a)
 
     # Check that some properties are at least available
     fi = a.ufl_free_indices
@@ -64,7 +69,7 @@ def _test_object2(a):
     assert hash(a) == hash(e)
 
     # Can't really test str more than that it exists
-    s = str(a)
+    str(a)
 
 
 def _test_form(a):
@@ -74,7 +79,7 @@ def _test_form(a):
     assert hash(a) == hash(e)
 
     # Can't really test str more than that it exists
-    s = str(a)
+    str(a)
 
 
 def testExports(self):
@@ -148,12 +153,12 @@ def testAll(self):
     a = IntValue(123)
     _test_object(a, (), ())
 
-    I = Identity(1)
-    _test_object(I, (1, 1), ())
-    I = Identity(2)
-    _test_object(I, (2, 2), ())
-    I = Identity(3)
-    _test_object(I, (3, 3), ())
+    ident = Identity(1)
+    _test_object(ident, (1, 1), ())
+    ident = Identity(2)
+    _test_object(ident, (2, 2), ())
+    ident = Identity(3)
+    _test_object(ident, (3, 3), ())
 
     e = PermutationSymbol(2)
     _test_object(e, (2, 2), ())
@@ -166,9 +171,9 @@ def testAll(self):
     _test_object(xi, (dim,), ())
 
     # g = CellBarycenter(cell)
-    #_test_object(g, (dim,), ())
+    # _test_object(g, (dim,), ())
     # g = FacetBarycenter(cell)
-    #_test_object(g, (dim,), ())
+    # _test_object(g, (dim,), ())
 
     g = Jacobian(cell)
     _test_object(g, (dim, dim), ())
@@ -187,7 +192,7 @@ def testAll(self):
     g = FacetNormal(cell)
     _test_object(g, (dim,), ())
     # g = CellNormal(cell)
-    #_test_object(g, (dim,), ())
+    # _test_object(g, (dim,), ())
 
     g = CellVolume(cell)
     _test_object(g, (), ())
@@ -196,7 +201,7 @@ def testAll(self):
     g = Circumradius(cell)
     _test_object(g, (), ())
     # g = CellSurfaceArea(cell)
-    #_test_object(g, (), ())
+    # _test_object(g, (), ())
 
     g = FacetArea(cell)
     _test_object(g, (), ())
@@ -205,7 +210,7 @@ def testAll(self):
     g = MaxFacetEdgeLength(cell)
     _test_object(g, (), ())
     # g = FacetDiameter(cell)
-    #_test_object(g, (), ())
+    # _test_object(g, (), ())
 
     a = variable(v0)
     _test_object(a, (), ())
@@ -242,8 +247,8 @@ def testAll(self):
     a = f2[l, 1]
     _test_object(a, (), (l,))
 
-    I = Identity(dim)
-    a = inv(I)
+    ident = Identity(dim)
+    a = inv(ident)
     _test_object(a, (dim, dim), ())
     a = inv(v2)
     _test_object(a, (dim, dim), ())
@@ -524,14 +529,14 @@ def testAll(self):
     _test_object(a, (), ())
 
     # a = PositiveRestricted(v0)
-    #_test_object(a, (), ())
+    # _test_object(a, (), ())
     a = v0('+')
     _test_object(a, (), ())
     a = v0('+')*f0
     _test_object(a, (), ())
 
     # a = NegativeRestricted(v0)
-    #_test_object(a, (), ())
+    # _test_object(a, (), ())
     a = v0('-')
     _test_object(a, (), ())
     a = v0('-') + f0
diff --git a/test/test_complex.py b/test/test_complex.py
index 72926d225..d908e1367 100755
--- a/test/test_complex.py
+++ b/test/test_complex.py
@@ -1,19 +1,17 @@
-#!/usr/bin/env py.test
-# -*- coding: utf-8 -*-
-import pytest
 import cmath
-import ufl
-from ufl.constantvalue import Zero, ComplexValue
-from ufl.algebra import Conj, Real, Imag
-from ufl.algorithms.apply_algebra_lowering import apply_algebra_lowering
-from ufl.algorithms.remove_complex_nodes import remove_complex_nodes
+
+import pytest
+
+from ufl import (Coefficient, FiniteElement, TestFunction, TrialFunction, as_tensor, as_ufl, atan, conditional, conj,
+                 cos, cosh, dot, dx, exp, ge, grad, gt, imag, inner, le, ln, lt, max_value, min_value, outer, real, sin,
+                 sqrt, triangle)
+from ufl.algebra import Conj, Imag, Real
 from ufl.algorithms import estimate_total_polynomial_degree
-from ufl.algorithms.comparison_checker import do_comparison_check, ComplexComparisonError
+from ufl.algorithms.apply_algebra_lowering import apply_algebra_lowering
+from ufl.algorithms.comparison_checker import ComplexComparisonError, do_comparison_check
 from ufl.algorithms.formtransformations import compute_form_adjoint
-from ufl import (TestFunction, TrialFunction, triangle, FiniteElement,
-                 as_ufl, inner, grad, dx, dot, outer, conj, sqrt, sin, cosh,
-                 atan, ln, exp, as_tensor, real, imag, conditional,
-                 min_value, max_value, gt, lt, cos, ge, le, Coefficient)
+from ufl.algorithms.remove_complex_nodes import remove_complex_nodes
+from ufl.constantvalue import ComplexValue, Zero
 
 
 def test_conj(self):
@@ -67,7 +65,8 @@ def test_complex_algebra(self):
     assert z2/z1 == ComplexValue(1-1j)
     assert pow(z2, z1) == ComplexValue((1+1j)**1j)
     assert sqrt(z2) * as_ufl(1) == ComplexValue(cmath.sqrt(1+1j))
-    assert ((sin(z2) + cosh(z2) - atan(z2)) * z1) == ComplexValue((cmath.sin(1+1j) + cmath.cosh(1+1j) - cmath.atan(1+1j))*1j)
+    assert (sin(z2) + cosh(z2) - atan(z2)) * z1 == ComplexValue(
+        (cmath.sin(1+1j) + cmath.cosh(1+1j) - cmath.atan(1+1j))*1j)
     assert (abs(z2) - ln(z2))/exp(z1) == ComplexValue((abs(1+1j) - cmath.log(1+1j))/cmath.exp(1j))
 
 
@@ -106,7 +105,8 @@ def test_apply_algebra_lowering_complex(self):
 
     assert lowered_a == gu[lowered_a_index] * gv[lowered_a_index]
     assert lowered_b == gv[lowered_b_index] * conj(gu[lowered_b_index])
-    assert lowered_c == as_tensor(conj(gu[lowered_c_indices[0]]) * gv[lowered_c_indices[1]], (lowered_c_indices[0],) + (lowered_c_indices[1],))
+    assert lowered_c == as_tensor(
+        conj(gu[lowered_c_indices[0]]) * gv[lowered_c_indices[1]], (lowered_c_indices[0],) + (lowered_c_indices[1],))
 
 
 def test_remove_complex_nodes(self):
diff --git a/test/test_conditionals.py b/test/test_conditionals.py
index 5b1b7badf..3b6dffce2 100755
--- a/test/test_conditionals.py
+++ b/test/test_conditionals.py
@@ -1,14 +1,10 @@
-#!/usr/bin/env py.test
-# -*- coding: utf-8 -*-
-
 __authors__ = "Martin Sandve Alnæs"
 __date__ = "2008-08-20 -- 2012-11-30"
 
 import pytest
 
-from ufl import *
-# from ufl.algorithms import *
-from ufl.classes import *
+from ufl import Coefficient, FiniteElement, conditional, eq, ge, gt, le, lt, ne, triangle
+from ufl.classes import EQ, GE, GT, LE, LT, NE
 
 
 @pytest.fixture
@@ -30,17 +26,6 @@ def test_conditional_does_not_allow_bool_condition(f, g):
         conditional(True, 1, 0)
 
 
-def test_eq_produces_ufl_expr(f, g):
-    expr1 = eq(f, f)
-    expr2 = eq(f, g)
-    expr3 = eq(f, g)
-    assert isinstance(expr1, EQ)
-    assert isinstance(expr2, EQ)
-    assert not bool(expr1 == expr2)
-    assert bool(expr1 != expr2)
-    assert bool(expr2 == expr3)
-
-
 def test_eq_oper_produces_bool(f, g):
     expr1 = f == f
     expr2 = f == g
@@ -50,15 +35,6 @@ def test_eq_oper_produces_bool(f, g):
     assert not expr2
 
 
-def xtest_eq_produces_ufl_expr(f, g):
-    expr1 = f == g
-    expr2 = eq(f, g)
-    assert isinstance(expr1, EQ)
-    assert isinstance(expr2, EQ)
-    assert bool(expr1 == expr2)
-    assert not bool(expr1 != expr2)
-
-
 def test_eq_produces_ufl_expr(f, g):
     expr1 = eq(f, g)
     expr2 = eq(f, f)
diff --git a/test/test_degree_estimation.py b/test/test_degree_estimation.py
index 3c344a8e3..8f05713c5 100755
--- a/test/test_degree_estimation.py
+++ b/test/test_degree_estimation.py
@@ -1,14 +1,11 @@
-#!/usr/bin/env py.test
-# -*- coding: utf-8 -*-
-
 __authors__ = "Martin Sandve Alnæs"
 __date__ = "2008-03-12 -- 2009-01-28"
 
-import pytest
-from pprint import *
 
-from ufl import *
-from ufl.algorithms import *
+from ufl import (Argument, Coefficient, Coefficients, FacetNormal, FiniteElement, SpatialCoordinate,
+                 TensorProductElement, VectorElement, cos, div, dot, grad, i, inner, nabla_div, nabla_grad, sin, tan,
+                 triangle)
+from ufl.algorithms import estimate_total_polynomial_degree
 
 
 def test_total_degree_estimation():
diff --git a/test/test_derivative.py b/test/test_derivative.py
index 2a023b9ae..e8ce1837d 100755
--- a/test/test_derivative.py
+++ b/test/test_derivative.py
@@ -3,11 +3,13 @@
 
 from itertools import chain
 
-import pytest
-
-from ufl import *
-from ufl.algorithms import (compute_form_data, expand_indices, post_traversal,
-                            strip_variables)
+from ufl import (CellDiameter, CellVolume, Circumradius, Coefficient, Constant, FacetArea, FacetNormal, FiniteElement,
+                 FunctionSpace, Identity, Index, Jacobian, JacobianInverse, Mesh, SpatialCoordinate, TensorElement,
+                 TestFunction, TrialFunction, VectorElement, acos, as_matrix, as_tensor, as_vector, asin, atan,
+                 conditional, cos, derivative, diff, dot, dx, exp, i, indices, inner, interval, j, k, ln, lt,
+                 nabla_grad, outer, quadrilateral, replace, sign, sin, split, sqrt, tan, tetrahedron, triangle,
+                 variable, zero)
+from ufl.algorithms import compute_form_data, expand_indices, strip_variables
 from ufl.algorithms.apply_algebra_lowering import apply_algebra_lowering
 from ufl.algorithms.apply_derivatives import apply_derivatives
 from ufl.algorithms.apply_geometry_lowering import apply_geometry_lowering
@@ -280,22 +282,6 @@ def df(w, v): return sign(w)*v
     _test(self, f, df)
 
 
-def testConditional(self):
-    def cond(w): return lt(1.0, 2.0)
-
-    def f(w): return conditional(cond(w), 2*w, 3*w)
-
-    def df(w, v): return 2*v
-    _test(self, f, df)
-
-    def cond(w): return lt(2.0, 1.0)
-
-    def f(w): return conditional(cond(w), 2*w, 3*w)
-
-    def df(w, v): return 3*v
-    _test(self, f, df)
-
-
 def testConditional(self):  # This will fail without bugfix in derivative
     def cond(w): return lt(w, 1.0)
 
@@ -324,22 +310,22 @@ def testListTensor(self):
     v = variable(as_ufl(42))
     f = as_tensor((
         ((0, 0), (0, 0)),
-            ((v, 2*v), (0, 0)),
-            ((v**2, 1), (2, v/2)),
+        ((v, 2*v), (0, 0)),
+        ((v**2, 1), (2, v/2)),
     ))
     assert f.ufl_shape == (3, 2, 2)
     g = as_tensor((
         ((0, 0), (0, 0)),
-            ((1, 2), (0, 0)),
-            ((84, 0), (0, 0.5)),
+        ((1, 2), (0, 0)),
+        ((84, 0), (0, 0.5)),
     ))
     assert g.ufl_shape == (3, 2, 2)
     dfv = diff(f, v)
     x = None
-    for i in range(3):
-        for j in range(2):
-            for k in range(2):
-                self.assertEqual(dfv[i, j, k](x), g[i, j, k](x))
+    for a in range(3):
+        for b in range(2):
+            for c in range(2):
+                self.assertEqual(dfv[a, b, c](x), g[a, b, c](x))
 
 # --- Coefficient and argument input configurations
 
@@ -388,7 +374,7 @@ def test_multiple_coefficient_derivative(self):
 
 def test_indexed_coefficient_derivative(self):
     cell = triangle
-    I = Identity(cell.geometric_dimension())
+    ident = Identity(cell.geometric_dimension())
     V = FiniteElement("CG", cell, 1)
     W = VectorElement("CG", cell, 1)
     u = Coefficient(W)
@@ -400,7 +386,7 @@ def test_indexed_coefficient_derivative(self):
 
     actual = derivative(a, u[0], v)
 
-    dw = v*u[k].dx(0) + u[i]*I[0, k]*v.dx(i)
+    dw = v*u[k].dx(0) + u[i]*ident[0, k]*v.dx(i)
     expected = 2 * w[k] * dw
 
     assertEqualBySampling(actual, expected)
@@ -408,7 +394,6 @@ def test_indexed_coefficient_derivative(self):
 
 def test_multiple_indexed_coefficient_derivative(self):
     cell = tetrahedron
-    I = Identity(cell.geometric_dimension())
     V = FiniteElement("CG", cell, 1)
     V2 = V*V
     W = VectorElement("CG", cell, 1)
@@ -437,24 +422,23 @@ def test_segregated_derivative_of_convection(self):
 
     Lv = {}
     Lvu = {}
-    for i in range(cell.geometric_dimension()):
-        Lv[i] = derivative(L, v[i], dv)
-        for j in range(cell.geometric_dimension()):
-            Lvu[i, j] = derivative(Lv[i], u[j], du)
-
-    for i in range(cell.geometric_dimension()):
-        for j in range(cell.geometric_dimension()):
-            form = Lvu[i, j]*dx
+    for a in range(cell.geometric_dimension()):
+        Lv[a] = derivative(L, v[a], dv)
+        for b in range(cell.geometric_dimension()):
+            Lvu[a, b] = derivative(Lv[a], u[b], du)
+
+    for a in range(cell.geometric_dimension()):
+        for b in range(cell.geometric_dimension()):
+            form = Lvu[a, b]*dx
             fd = compute_form_data(form)
             pf = fd.preprocessed_form
-            a = expand_indices(pf)
-            # print (i,j), str(a)
+            expand_indices(pf)
 
     k = Index()
-    for i in range(cell.geometric_dimension()):
-        for j in range(cell.geometric_dimension()):
-            actual = Lvu[i, j]
-            expected = du*u[i].dx(j)*dv + u[k]*du.dx(k)*dv
+    for a in range(cell.geometric_dimension()):
+        for b in range(cell.geometric_dimension()):
+            actual = Lvu[a, b]
+            expected = du*u[a].dx(b)*dv + u[k]*du.dx(k)*dv
             assertEqualBySampling(actual, expected)
 
 # --- User provided derivatives of coefficients
@@ -654,10 +638,10 @@ def test_mass_derived_from_functional(self):
 
     f = (w**2/2)*dx
     L = w*v*dx
-    a = u*v*dx
+    a = u*v*dx  # noqa: F841
     F = derivative(f, w, v)
-    J1 = derivative(L, w, u)
-    J2 = derivative(F, w, u)
+    J1 = derivative(L, w, u)  # noqa: F841
+    J2 = derivative(F, w, u)  # noqa: F841
     # TODO: assert something
 
 # --- Interaction with replace
@@ -715,6 +699,7 @@ def test_index_simplification_reference_grad(self):
     assert expr.ufl_free_indices == ()
     assert expr.ufl_shape == ()
 
+
 # --- Scratch space
 
 def test_foobar(self):
@@ -737,5 +722,5 @@ def NS_a(u, v):
         return inner(epsilon(u), epsilon(v))
 
     L = NS_a(U, v)*dx
-    a = derivative(L, U, du)
+    a = derivative(L, U, du)  # noqa: F841
     # TODO: assert something
diff --git a/test/test_diff.py b/test/test_diff.py
index d0eeeac57..47305bc4e 100755
--- a/test/test_diff.py
+++ b/test/test_diff.py
@@ -1,15 +1,12 @@
-#!/usr/bin/env py.test
-# -*- coding: utf-8 -*-
-
 __authors__ = "Martin Sandve Alnæs"
 __date__ = "2009-02-17 -- 2014-10-14"
 
 import pytest
-import math
 
-from ufl import *
-from ufl.constantvalue import as_ufl
+from ufl import (Coefficient, FiniteElement, FunctionSpace, Mesh, SpatialCoordinate, VectorElement, as_vector, atan,
+                 cos, diff, exp, indices, ln, sin, tan, triangle, variable)
 from ufl.algorithms import expand_derivatives
+from ufl.constantvalue import as_ufl
 
 
 def get_variables():
diff --git a/test/test_domains.py b/test/test_domains.py
index 2422a8822..81671aba4 100755
--- a/test/test_domains.py
+++ b/test/test_domains.py
@@ -1,15 +1,12 @@
-#!/usr/bin/env py.test
-# -*- coding: utf-8 -*-
-"""
-Tests of domain language and attaching domains to forms.
-"""
+"""Tests of domain language and attaching domains to forms."""
 
-from mockobjects import MockMesh, MockMeshFunction
 import pytest
+from mockobjects import MockMesh
 
-from ufl import *
-from ufl.domain import as_domain, default_domain
+from ufl import (Cell, Coefficient, Constant, FiniteElement, FunctionSpace, Mesh, VectorElement, ds, dS, dx, hexahedron,
+                 interval, quadrilateral, tetrahedron, triangle)
 from ufl.algorithms import compute_form_data
+from ufl.domain import as_domain, default_domain
 
 all_cells = (interval, triangle, tetrahedron,
              quadrilateral, hexahedron)
@@ -197,14 +194,14 @@ def test_everywhere_integrals_with_backwards_compatibility():
 
     # Check some integral data
     assert ida.integral_type == "cell"
-    assert(len(ida.subdomain_id) == 1)
+    assert len(ida.subdomain_id) == 1
     assert ida.subdomain_id[0] == "otherwise"
     assert ida.metadata == {}
 
     # Integrands are not equal because of renumbering
     itg1 = ida.integrals[0].integrand()
     itg2 = a.integrals()[0].integrand()
-    assert type(itg1) == type(itg2)
+    assert type(itg1) is type(itg2)
     assert itg1.ufl_element() == itg2.ufl_element()
 
 
@@ -217,298 +214,33 @@ def test_merge_sort_integral_data():
     c = Constant(D)
     a = c * dS((2, 4)) + u * dx + u * ds + 2 * u * dx(3) + 2 * c * dS + 2 * u * dx((1, 4))
     form_data = compute_form_data(a, do_append_everywhere_integrals=False).integral_data
-    assert(len(form_data) == 5)
+    assert len(form_data) == 5
 
     # Check some integral data
     assert form_data[0].integral_type == "cell"
-    assert(len(form_data[0].subdomain_id) == 1)
+    assert len(form_data[0].subdomain_id) == 1
     assert form_data[0].subdomain_id[0] == "otherwise"
     assert form_data[0].metadata == {}
 
     assert form_data[1].integral_type == "cell"
-    assert(len(form_data[1].subdomain_id) == 3)
+    assert len(form_data[1].subdomain_id) == 3
     assert form_data[1].subdomain_id[0] == 1
     assert form_data[1].subdomain_id[1] == 3
     assert form_data[1].subdomain_id[2] == 4
     assert form_data[1].metadata == {}
 
     assert form_data[2].integral_type == "exterior_facet"
-    assert(len(form_data[2].subdomain_id) == 1)
+    assert len(form_data[2].subdomain_id) == 1
     assert form_data[2].subdomain_id[0] == "otherwise"
     assert form_data[2].metadata == {}
 
     assert form_data[3].integral_type == "interior_facet"
-    assert(len(form_data[3].subdomain_id) == 1)
+    assert len(form_data[3].subdomain_id) == 1
     assert form_data[3].subdomain_id[0] == "otherwise"
     assert form_data[3].metadata == {}
 
     assert form_data[4].integral_type == "interior_facet"
-    assert(len(form_data[4].subdomain_id) == 2)
+    assert len(form_data[4].subdomain_id) == 2
     assert form_data[4].subdomain_id[0] == 2
     assert form_data[4].subdomain_id[1] == 4
     assert form_data[4].metadata == {}
-
-
-def xtest_mixed_elements_on_overlapping_regions():  # Old sketch, not working
-
-    # Create domain and both disjoint and overlapping regions
-    cell = tetrahedron
-    D = Mesh(cell, label='D')
-    DD = Region(D, (0, 4), "DD")
-    DL = Region(D, (1, 2), "DL")
-    DR = Region(D, (2, 3), "DR")
-
-    # Create function spaces on D
-    V = FiniteElement("CG", D, 1)
-    VD = FiniteElement("DG", DD, 1)
-    VC = FiniteElement("R", DD, 0)
-    VL = VectorElement("DG", DL, 2)
-    VR = FiniteElement("CG", DR, 3)
-
-    # Create mixed space over all these spaces
-    M = MixedElement(V, VD, VC, VL, VR)
-
-    # Check that we can get the degree for each value component of the mixed
-    # space
-    assert M.degree(0) == 1
-    assert M.degree(1) == 1
-    assert M.degree(2) == 0
-
-    assert M.degree(3) == 2  # Vector element
-    assert M.degree(4) == 2
-    assert M.degree(5) == 2
-
-    assert M.degree(6) == 3
-    assert M.degree() == 3
-
-    # Check that we can get the domain for each value component of the mixed
-    # space
-    assert M.ufl_domain(0) == D
-    assert M.ufl_domain(1) == DD
-    assert M.ufl_domain(2) == DD
-
-    assert M.ufl_domain(3) == DL  # Vector element
-    assert M.ufl_domain(4) == DL
-    assert M.ufl_domain(5) == DL
-
-    assert M.ufl_domain(6) == DR
-    # assert M.ufl_domain() == None # FIXME: What?
-
-    # Create a mixed function and fetch components with names for more
-    # readable test code below
-    m = Coefficient(M)
-    md = m[1]
-    mc = m[2]
-    ml = as_vector((m[3], m[4], m[5]))
-    mr = m[6]
-
-    # These should all work out fine with function and integration domains
-    # perfectly matching
-    a = m[0] ** 2 * dx(D)
-    ad = (md ** 2 + mc ** 2) * dx(DD)
-    al = ml ** 2 * dx(DL)
-    ar = mr ** 2 * dx(DR)
-
-    # TODO: Check properties of forms, maybe by computing and inspecting form
-    # data.
-
-    # These should all work out fine with because integration domains are
-    # contained in the function domains
-    ad = m[0] ** 2 * dx(DD)
-    al = m[0] ** 2 * dx(DL)
-    ar = m[0] ** 2 * dx("DR")
-    a0 = m[0] ** 2 * dx(0)
-    a12 = m[0] ** 2 * dx((1, 2))
-    a3 = m[0] ** 2 * dx(3)
-
-    # TODO: Check properties of forms, maybe by computing and inspecting form
-    # data.
-
-    # These should fail because the functions are undefined on the integration domains
-    # self.assertRaises(BaseException, lambda: mr**2*dx(DD)) # FIXME: Make this fail
-    # self.assertRaises(BaseException, lambda: mr**2*dx(DD)) # FIXME: Make this
-    # fail
-
-
-def xtest_form_domain_model():  # Old sketch, not working
-    # Create domains with different celltypes
-    # TODO: Figure out PyDOLFIN integration with Mesh
-    DA = Mesh(tetrahedron, label='DA')
-    DB = Mesh(hexahedron, label='DB')
-
-    # Check python protocol behaviour
-    assert DA != DB
-    assert {DA, DA} == {DA}
-    assert {DB, DB} == {DB}
-    assert {DA, DB} == {DB, DA}
-    assert sorted((DA, DB, DA, DB)) == sorted((DB, DA, DA, DB))
-
-    # Check basic properties
-    assert DA.name() == 'DA'
-    assert DA.geometric_dimension() == 3
-    assert DA.topological_dimension() == 3
-    assert DA.ufl_cell() == tetrahedron
-
-    # Check region/domain getters
-    assert DA.top_domain() == DA
-    assert DA.subdomain_ids() == None
-    # assert DA.region_names() == []
-    # assert DA.regions() == []
-
-    # BDA = Boundary(DA) # TODO
-    # IDAB = Intersection(DA,DB) # TODO
-    # ODAB = Overlap(DA,DB) # TODO
-
-    # Create overlapping regions of each domain
-    DAL = Region(DA, (1, 2), "DAL")
-    DAR = Region(DA, (2, 3), "DAR")
-    DBL = Region(DB, (0, 1), "DBL")
-    DBR = Region(DB, (1, 4), "DBR")
-
-    # Check that regions are available through domains
-    # assert DA.region_names() == ['DAL', 'DAR']
-    # assert DA.regions() == [DAL, DAR]
-    # assert DA["DAR"] == DAR
-    # assert DA["DAL"] == DAL
-
-    # Create function spaces on DA
-    VA = FiniteElement("CG", DA, 1)
-    VAL = FiniteElement("CG", DAL, 1)
-    VAR = FiniteElement("CG", DAR, 1)
-
-    # Create function spaces on DB
-    VB = FiniteElement("CG", DB, 1)
-    VBL = FiniteElement("CG", DBL, 1)
-    VBR = FiniteElement("CG", DBR, 1)
-
-    # Check that regions are available through elements
-    assert VA.ufl_domain() == DA
-    assert VAL.ufl_domain() == DAL
-    assert VAR.ufl_domain() == DAR
-
-    # Create functions in each space on DA
-    fa = Coefficient(VA)
-    fal = Coefficient(VAL)
-    far = Coefficient(VAR)
-
-    # Create functions in each space on DB
-    fb = Coefficient(VB)
-    fbl = Coefficient(VBL)
-    fbr = Coefficient(VBR)
-
-    # Checks of coefficient domains is covered well in the mixed element test
-
-    # Create measure objects directly based on domain and region objects
-    dxa = dx(DA)
-    dxal = dx(DAL)
-    dxar = dx('DAR')  # Get Region by name
-
-    # Create measure proxy objects from strings and ints, requiring
-    # domains and regions to be part of their integrands
-    dxb = dx('DB')   # Get Mesh by name
-    dxbl = dx(Region(DB, (1, 4), 'DBL2'))
-    # Provide a region with different name but same subdomain ids as
-    # DBL
-    dxbr = dx((1, 4))
-    # Assume unique Mesh and provide subdomain ids explicitly
-
-    # Not checking measure objects in detail, as long as
-    # they carry information to construct integrals below
-    # they are good to go.
-
-    # Create integrals on each region with matching spaces and measures
-    Ma = fa * dxa
-    Mar = far * dxar
-    Mal = fal * dxal
-    Mb = fb * dxb
-    Mbr = fbr * dxbr
-    Mbl = fbl * dxbl
-
-    # TODO: Check forms, by getting and inspecting domains somehow.
-
-    # TODO: How do we express the distinction between "everywhere" and
-    # "nowhere"? subdomain_ids=None vs []?
-
-    # Create forms from integrals over overlapping regions on same top domain
-    Marl = Mar + Mal
-    Mbrl = Mbr + Mbl
-
-    # Create forms from integrals over top domain and regions
-    Mac = Ma + Marl
-    Mbc = Mb + Mbrl
-
-    # Create forms from separate top domains
-    Mab = Ma + Mb
-
-    # Create forms from separate top domains with overlapping regions
-    Mabrl = Mac + Mbc
-
-    # self.assertFalse(True) # Getting here, but it's not bloody likely that
-    # everything above is actually working. Add assertions!
-
-
-def xtest_subdomain_stuff():  # Old sketch, not working
-    D = Mesh(triangle)
-
-    D1 = D[1]
-    D2 = D[2]
-    D3 = D[3]
-
-    DL = Region(D, (D1, D2), 'DL')
-    DR = Region(D, (D2, D3), 'DR')
-    DM = Overlap(DL, DR)
-
-    assert DM == D2
-
-    VL = VectorElement(DL, "CG", 1)
-    VR = FiniteElement(DR, "CG", 2)
-    V = VL * VR
-
-    def sub_elements_on_subdomains(W):
-        # Get from W: (already there)
-        subelements = (VL, VR)
-        # Get from W:
-        subdomains = (D1, D2, D3)
-        # Build in W:
-        dom2elm = {D1: (VL,),
-                   D2: (VL, VR),
-                   D3: (VR,), }
-        # Build in W:
-        elm2dom = {VL: (D1, D2),
-                   VR: (D2, D3)}
-
-    # ElementSwitch represents joining of elements restricted to disjunct
-    # subdomains.
-
-    # An element restricted to a domain union becomes a switch
-    # of elements restricted to each disjoint subdomain
-    VL_D1 = VectorElement(D1, "CG", 1)
-    VL_D2 = VectorElement(D2, "CG", 1)
-    VLalt = ElementSwitch({D1: VL_D1,
-                           D2: VL_D2})
-    # Ditto
-    VR_D2 = FiniteElement(D2, "CG", 2)
-    VR_D3 = FiniteElement(D3, "CG", 2)
-    VRalt = ElementSwitch({D2: VR_D2,
-                           D3: VR_D3})
-    # A mixed element of ElementSwitches is mixed only on the overlapping
-    # domains:
-    Valt1 = VLalt * VRalt
-    Valt2 = ElementSwitch({D1: VL_D1,
-                           D2: VL_D2 * VR_D2,
-                           D3: VR_D3})
-
-    ul, ur = TrialFunctions(V)
-    vl, vr = TestFunctions(V)
-
-    # Implemented by user:
-    al = dot(ul, vl) * dx(DL)
-    ar = ur * vr * dx(DR)
-
-    # Disjunctified by UFL:
-    alonly = dot(ul, vl) * dx(D1)
-    # integral_1 knows that only subelement VL is active
-    am = (dot(ul, vl) + ur * vr) * dx(D2)
-    # integral_2 knows that both subelements are active
-    aronly = ur * vr * \
-        dx(D3)  # integral_3 knows that only subelement VR is active
diff --git a/test/test_duals.py b/test/test_duals.py
index 272294391..f21054857 100644
--- a/test/test_duals.py
+++ b/test/test_duals.py
@@ -1,21 +1,16 @@
-#!/usr/bin/env py.test
-# -*- coding: utf-8 -*-
-
-from ufl import (FiniteElement, FunctionSpace, MixedFunctionSpace,
-                 Coefficient, Matrix, Cofunction, FormSum, Argument, Coargument,
-                 TestFunction, TrialFunction, Adjoint, Action,
-                 action, adjoint, derivative, inner, tetrahedron, triangle, interval, dx)
-from ufl.constantvalue import Zero
-from ufl.form import ZeroBaseForm
-
 __authors__ = "India Marsden"
-__date__ = "2020-12-28 -- 2020-12-28"
+__date__ = "2020-12-28"
 
 import pytest
 
-from ufl.domain import default_domain
-from ufl.duals import is_primal, is_dual
+from ufl import (Action, Adjoint, Argument, Coargument, Coefficient, Cofunction, FiniteElement, FormSum, FunctionSpace,
+                 Matrix, MixedFunctionSpace, TestFunction, TrialFunction, action, adjoint, derivative, dx, inner,
+                 interval, tetrahedron, triangle)
 from ufl.algorithms.ad import expand_derivatives
+from ufl.constantvalue import Zero
+from ufl.domain import default_domain
+from ufl.duals import is_dual, is_primal
+from ufl.form import ZeroBaseForm
 
 
 def test_mixed_functionspace(self):
@@ -72,7 +67,7 @@ def test_dual_coefficients():
     assert not is_primal(w)
 
     with pytest.raises(ValueError):
-        x = Cofunction(V)
+        Cofunction(V)
 
 
 def test_dual_arguments():
@@ -95,7 +90,7 @@ def test_dual_arguments():
     assert not is_primal(w)
 
     with pytest.raises(ValueError):
-        x = Coargument(V, 4)
+        Coargument(V, 4)
 
 
 def test_addition():
diff --git a/test/test_elements.py b/test/test_elements.py
index 49a700cd7..f096860e4 100755
--- a/test/test_elements.py
+++ b/test/test_elements.py
@@ -1,11 +1,5 @@
-#!/usr/bin/env py.test
-# -*- coding: utf-8 -*-
-
-# Last changed: 2014-02-24
-
-import pytest
-
-from ufl import *
+from ufl import (Coefficient, FiniteElement, MixedElement, TensorElement, VectorElement, WithMapping, dx, hexahedron,
+                 inner, interval, quadrilateral, tetrahedron, triangle)
 
 all_cells = (interval, triangle, tetrahedron, quadrilateral, hexahedron)
 
@@ -80,7 +74,7 @@ def test_tensor_symmetry():
 
 
 def test_mixed_tensor_symmetries():
-    from ufl.algorithms import expand_indices, expand_compounds
+    from ufl.algorithms import expand_compounds, expand_indices
 
     S = FiniteElement('CG', triangle, 1)
     V = VectorElement('CG', triangle, 1)
@@ -180,6 +174,7 @@ def test_missing_cell():
         element = TensorElement("DG L2", cell, 1, shape=(2, 2))
         assert element == eval(repr(element))
 
+
 def test_invalid_degree():
     cell = triangle
     for degree in (1, None):
diff --git a/test/test_equals.py b/test/test_equals.py
index fd9522ead..4c36ad7cd 100755
--- a/test/test_equals.py
+++ b/test/test_equals.py
@@ -1,14 +1,6 @@
-#!/usr/bin/env py.test
-# -*- coding: utf-8 -*-
+"""Test of expression comparison."""
 
-"""
-Test of expression comparison.
-"""
-
-import pytest
-
-# This imports everything external code will see from ufl
-from ufl import *
+from ufl import Coefficient, Cofunction, FiniteElement, triangle
 
 
 def test_comparison_of_coefficients():
@@ -36,6 +28,7 @@ def test_comparison_of_coefficients():
     assert not v1 == u1
     assert not v2 == u2
 
+
 def test_comparison_of_cofunctions():
     V = FiniteElement("CG", triangle, 1)
     U = FiniteElement("CG", triangle, 2)
@@ -62,7 +55,6 @@ def test_comparison_of_cofunctions():
     assert not v2 == u2
 
 
-
 def test_comparison_of_products():
     V = FiniteElement("CG", triangle, 1)
     v = Coefficient(V)
diff --git a/test/test_evaluate.py b/test/test_evaluate.py
index 30e3a34f1..29488e207 100755
--- a/test/test_evaluate.py
+++ b/test/test_evaluate.py
@@ -1,13 +1,11 @@
-#!/usr/bin/env py.test
-# -*- coding: utf-8 -*-
-
 __authors__ = "Martin Sandve Alnæs"
 __date__ = "2009-02-13 -- 2009-02-13"
 
-import pytest
 import math
 
-from ufl import *
+from ufl import (Argument, Coefficient, FiniteElement, Identity, SpatialCoordinate, as_matrix, as_vector, cos, cross,
+                 det, dev, dot, exp, i, indices, inner, j, ln, outer, sin, skew, sqrt, sym, tan, tetrahedron, tr,
+                 triangle)
 from ufl.constantvalue import as_ufl
 
 
@@ -27,14 +25,14 @@ def testZero():
 
 def testIdentity():
     cell = triangle
-    I = Identity(cell.geometric_dimension())
+    ident = Identity(cell.geometric_dimension())
 
-    s = 123 * I[0, 0]
+    s = 123 * ident[0, 0]
     e = s((5, 7))
     v = 123
     assert e == v
 
-    s = 123 * I[1, 0]
+    s = 123 * ident[1, 0]
     e = s((5, 7))
     v = 0
     assert e == v
@@ -107,9 +105,9 @@ def testIndexSum():
 def testIndexSum2():
     cell = triangle
     x = SpatialCoordinate(cell)
-    I = Identity(cell.geometric_dimension())
+    ident = Identity(cell.geometric_dimension())
     i, j = indices(2)
-    s = (x[i] * x[j]) * I[i, j]
+    s = (x[i] * x[j]) * ident[i, j]
     e = s((5, 7))
     # v = sum_i sum_j x_i x_j delta_ij = x_0 x_0 + x_1 x_1
     v = 5 ** 2 + 7 ** 2
@@ -277,15 +275,15 @@ def test_cross():
             as_vector((0, x[2], 0))],
     ]
     for t in ts:
-        for i in range(3):
-            for j in range(3):
-                cij = cross(t[i], t[j])
-                dij = dot(cij, cij)
-                eij = dij(xv)
-                tni = dot(t[i], t[i])(xv)
-                tnj = dot(t[j], t[j])(xv)
-                vij = tni * tnj if i != j else 0
-                assert eij == vij
+        for a in range(3):
+            for b in range(3):
+                cab = cross(t[a], t[b])
+                dab = dot(cab, cab)
+                eab = dab(xv)
+                tna = dot(t[a], t[a])(xv)
+                tnb = dot(t[b], t[b])(xv)
+                vab = tna * tnb if a != b else 0
+                assert eab == vab
 
 
 def xtest_dev():
diff --git a/test/test_expand_indices.py b/test/test_expand_indices.py
index f0ae687c6..77977552f 100755
--- a/test/test_expand_indices.py
+++ b/test/test_expand_indices.py
@@ -1,20 +1,17 @@
-#!/usr/bin/env py.test
-# -*- coding: utf-8 -*-
-
 __authors__ = "Martin Sandve Alnæs"
 __date__ = "2009-03-19 -- 2012-03-20"
 
 # Modified by Anders Logg, 2008
 # Modified by Garth N. Wells, 2009
 
-import pytest
 import math
-from pprint import *
 
-from ufl import *
-from ufl.algorithms import *
+import pytest
+
+from ufl import (Coefficient, FiniteElement, Identity, TensorElement, VectorElement, as_tensor, cos, det, div, dot, dx,
+                 exp, grad, i, inner, j, k, l, ln, nabla_div, nabla_grad, outer, sin, triangle)
+from ufl.algorithms import compute_form_data, expand_derivatives, expand_indices
 from ufl.algorithms.renumbering import renumber_indices
-from ufl.classes import Sum, Product
 
 # TODO: Test expand_indices2 throuroughly for correctness, then efficiency:
 # expand_indices, expand_indices2 = expand_indices2, expand_indices
@@ -191,7 +188,6 @@ def test_basic_expand_indices(self, fixt):
 
 
 def test_expand_indices_index_sum(self, fixt):
-    sf = fixt.sf
     vf = fixt.vf
     tf = fixt.tf
     compare = fixt.compare
@@ -208,7 +204,6 @@ def test_expand_indices_index_sum(self, fixt):
 def test_expand_indices_derivatives(self, fixt):
     sf = fixt.sf
     vf = fixt.vf
-    tf = fixt.tf
     compare = fixt.compare
 
     # Basic derivatives
@@ -219,15 +214,13 @@ def test_expand_indices_derivatives(self, fixt):
 
 
 def test_expand_indices_hyperelasticity(self, fixt):
-    sf = fixt.sf
     vf = fixt.vf
-    tf = fixt.tf
     compare = fixt.compare
 
     # Deformation gradient
-    I = Identity(2)
+    ident = Identity(2)
     u = vf
-    F = I + grad(u)
+    F = ident + grad(u)
     # F = (1 + vf[0].dx(0), vf[0].dx(1), vf[1].dx(0), 1 + vf[1].dx(1))
     # F = (1 + 0.50,        0.51,        0.70,        1 + 0.71)
     F00 = 1 + 0.50
@@ -254,7 +247,7 @@ def test_expand_indices_hyperelasticity(self, fixt):
     compare(C[1, 0], C10)
     compare(C[1, 1], C11)
 
-    E = (C-I)/2
+    E = (C-ident)/2
     E00 = (C00-1)/2
     E01 = (C01)/2
     E10 = (C10)/2
@@ -323,26 +316,3 @@ def test_expand_indices_nabla_div_grad(self, fixt):
 
     a = nabla_div(nabla_grad(tf))
     compare(inner(a, a), (10.00+11.00)**2 + (10.01+11.01)**2 + (10.10+11.10)**2 + (10.11+11.11)**2)
-
-
-def xtest_expand_indices_list_tensor_problem(self, fixt):
-    print()
-    print(('='*40))
-    # TODO: This is the case marked in the expand_indices2 implementation
-    # as not working. Fix and then try expand_indices2 on other tests!
-    V = VectorElement("CG", triangle, 1)
-    w = Coefficient(V)
-    v = as_vector([w[0], 0])
-    a = v[i]*w[i]
-    # TODO: Compare
-    print((type(a), str(a)))
-    A, comp = a.ufl_operands
-    print((type(A), str(A)))
-    print((type(comp), str(comp)))
-
-    ei1 = expand_indices(a)
-    ei2 = expand_indices2(a)
-    print((str(ei1)))
-    print((str(ei2)))
-    print(('='*40))
-    print()
diff --git a/test/test_external_operator.py b/test/test_external_operator.py
index d586c04a6..4a40a1c75 100644
--- a/test/test_external_operator.py
+++ b/test/test_external_operator.py
@@ -1,23 +1,18 @@
-#!/usr/bin/env py.test
-# -*- coding: utf-8 -*-
+"""Test ExternalOperator object."""
 
 __authors__ = "Nacime Bouziani"
 __date__ = "2019-03-26"
 
-
-"""
-Test ExternalOperator object
-"""
-
 import pytest
 
 # This imports everything external code will see from ufl
-from ufl import *
-from ufl.core.external_operator import ExternalOperator
-from ufl.form import BaseForm
-from ufl.algorithms.apply_derivatives import apply_derivatives
+from ufl import (Action, Argument, Coefficient, Constant, FiniteElement, Form, FunctionSpace, TestFunction,
+                 TrialFunction, action, adjoint, cos, derivative, dx, inner, sin, triangle)
 from ufl.algorithms import expand_derivatives
+from ufl.algorithms.apply_derivatives import apply_derivatives
+from ufl.core.external_operator import ExternalOperator
 from ufl.domain import default_domain
+from ufl.form import BaseForm
 
 
 @pytest.fixture
@@ -183,9 +178,8 @@ def test_differentiation_procedure_action(V1, V2):
 
 
 def test_extractions(V1):
-    from ufl.algorithms.analysis import (extract_coefficients, extract_arguments,
-                                         extract_arguments_and_coefficients, extract_base_form_operators,
-                                         extract_constants)
+    from ufl.algorithms.analysis import (extract_arguments, extract_arguments_and_coefficients,
+                                         extract_base_form_operators, extract_coefficients, extract_constants)
 
     u = Coefficient(V1)
     c = Constant(triangle)
@@ -258,9 +252,14 @@ def test_adjoint_action_jacobian(V1, V2, V3):
     vstar_N, = N.arguments()
 
     # Arguments for the Gateaux-derivative
-    u_hat = lambda number: Argument(V1, number)   # V1: degree 1 # dFdu.arguments()[-1]
-    m_hat = lambda number: Argument(V2, number)   # V2: degree 2 # dFdm.arguments()[-1]
-    vstar_N = lambda number: Argument(V3.dual(), number)  # V3: degree 3
+    def u_hat(number):
+        return Argument(V1, number)   # V1: degree 1 # dFdu.arguments()[-1]
+
+    def m_hat(number):
+        return Argument(V2, number)   # V2: degree 2 # dFdm.arguments()[-1]
+
+    def vstar_N(number):
+        return Argument(V3.dual(), number)  # V3: degree 3
 
     # Coefficients for the action
     w = Coefficient(V1)  # for u
@@ -410,9 +409,8 @@ def test_multiple_external_operators(V1, V2):
     F = (inner(N1, v) + inner(N2, v) + inner(N3, v) + inner(N4, v)) * dx
 
     dFdu = expand_derivatives(derivative(F, u))
-    assert dFdu == Action(dFdN1, dN1du) + Action(dFdN3, dN3du) +\
-                   Action(dFdN4_partial, Action(dN4dN1_partial, dN1du)) +\
-                   Action(dFdN4_partial, dN4du_partial)
+    assert dFdu == Action(dFdN1, dN1du) + Action(dFdN3, dN3du) + Action(
+        dFdN4_partial, Action(dN4dN1_partial, dN1du)) + Action(dFdN4_partial, dN4du_partial)
 
     dFdm = expand_derivatives(derivative(F, m))
     assert dFdm == Action(dFdN1, dN1dm) + Action(dFdN4_partial, Action(dN4dN1_partial, dN1dm))
@@ -440,7 +438,8 @@ def test_multiple_external_operators(V1, V2):
     dFdN5_partial = (inner(w, v) + inner(u * w, v)) * dx
     dN5dN4_partial = N5._ufl_expr_reconstruct_(N4, u, derivatives=(1, 0), argument_slots=N4.arguments() + (w,))
     dN5du_partial = N5._ufl_expr_reconstruct_(N4, u, derivatives=(0, 1), argument_slots=N4.arguments() + (w,))
-    dN5du = Action(dN5dN4_partial, Action(dN4dN1_partial, dN1du)) + Action(dN5dN4_partial, dN4du_partial) + dN5du_partial
+    dN5du = Action(dN5dN4_partial, Action(dN4dN1_partial, dN1du)) + Action(
+        dN5dN4_partial, dN4du_partial) + dN5du_partial
 
     dFdu = expand_derivatives(derivative(F, u))
     assert dFdu == dFdu_partial + Action(dFdN1_partial, dN1du) + Action(dFdN5_partial, dN5du)
diff --git a/test/test_ffcforms.py b/test/test_ffcforms.py
index 16fbcc5ba..ea01e45c3 100755
--- a/test/test_ffcforms.py
+++ b/test/test_ffcforms.py
@@ -1,8 +1,9 @@
-#!/usr/bin/env py.test
-# -*- coding: utf-8 -*-
-"""Unit tests including all demo forms from FFC 0.5.0. The forms are
+"""Test FFC forms.
+
+Unit tests including all demo forms from FFC 0.5.0. The forms are
 modified (with comments) to work with the UFL notation which differs
-from the FFC notation in some places."""
+from the FFC notation in some places.
+"""
 
 __author__ = "Anders Logg (logg@simula.no) et al."
 __date__ = "2008-04-09 -- 2008-09-26"
@@ -12,29 +13,27 @@
 # Examples copied from the FFC demo directory, examples contributed
 # by Johan Jansson, Kristian Oelgaard, Marie Rognes, and Garth Wells.
 
-import pytest
-from ufl import *
+from ufl import (Coefficient, Constant, Dx, FacetNormal, FiniteElement, TensorElement, TestFunction, TestFunctions,
+                 TrialFunction, TrialFunctions, VectorConstant, VectorElement, avg, curl, div, dot, ds, dS, dx, grad, i,
+                 inner, j, jump, lhs, rhs, sqrt, tetrahedron, triangle)
 
 
 def testConstant():
-
     element = FiniteElement("Lagrange", "triangle", 1)
 
     v = TestFunction(element)
     u = TrialFunction(element)
-    f = Coefficient(element)
 
     c = Constant("triangle")
     d = VectorConstant("triangle")
 
-    a = c * dot(grad(v), grad(u)) * dx
+    a = c * dot(grad(v), grad(u)) * dx  # noqa: F841
 
     # FFC notation: L = dot(d, grad(v))*dx
-    L = inner(d, grad(v)) * dx
+    L = inner(d, grad(v)) * dx  # noqa: F841
 
 
 def testElasticity():
-
     element = VectorElement("Lagrange", "tetrahedron", 1)
 
     v = TestFunction(element)
@@ -45,19 +44,17 @@ def eps(v):
         return grad(v) + (grad(v)).T
 
     # FFC notation: a = 0.25*dot(eps(v), eps(u))*dx
-    a = 0.25 * inner(eps(v), eps(u)) * dx
+    a = 0.25 * inner(eps(v), eps(u)) * dx  # noqa: F841
 
 
 def testEnergyNorm():
-
     element = FiniteElement("Lagrange", "tetrahedron", 1)
 
     v = Coefficient(element)
-    a = (v * v + dot(grad(v), grad(v))) * dx
+    a = (v * v + dot(grad(v), grad(v))) * dx  # noqa: F841
 
 
 def testEquation():
-
     element = FiniteElement("Lagrange", "triangle", 1)
 
     k = 0.1
@@ -68,12 +65,11 @@ def testEquation():
 
     F = v * (u - u0) * dx + k * dot(grad(v), grad(0.5 * (u0 + u))) * dx
 
-    a = lhs(F)
-    L = rhs(F)
+    a = lhs(F)  # noqa: F841
+    L = rhs(F)  # noqa: F841
 
 
 def testFunctionOperators():
-
     element = FiniteElement("Lagrange", "triangle", 1)
 
     v = TestFunction(element)
@@ -83,12 +79,10 @@ def testFunctionOperators():
 
     # FFC notation: a = sqrt(1/modulus(1/f))*sqrt(g)*dot(grad(v), grad(u))*dx
     # + v*u*sqrt(f*g)*g*dx
-    a = sqrt(1 / abs(1 / f)) * sqrt(g) * \
-        dot(grad(v), grad(u)) * dx + v * u * sqrt(f * g) * g * dx
+    a = sqrt(1 / abs(1 / f)) * sqrt(g) * dot(grad(v), grad(u)) * dx + v * u * sqrt(f * g) * g * dx  # noqa: F841
 
 
 def testHeat():
-
     element = FiniteElement("Lagrange", "triangle", 1)
 
     v = TestFunction(element)
@@ -98,29 +92,26 @@ def testHeat():
     f = Coefficient(element)
     k = Constant("triangle")
 
-    a = v * u1 * dx + k * c * dot(grad(v), grad(u1)) * dx
-    L = v * u0 * dx + k * v * f * dx
+    a = v * u1 * dx + k * c * dot(grad(v), grad(u1)) * dx  # noqa: F841
+    L = v * u0 * dx + k * v * f * dx  # noqa: F841
 
 
 def testMass():
-
     element = FiniteElement("Lagrange", "tetrahedron", 3)
 
     v = TestFunction(element)
     u = TrialFunction(element)
 
-    a = v * u * dx
+    a = v * u * dx  # noqa: F841
 
 
 def testMixedMixedElement():
-
     P3 = FiniteElement("Lagrange", "triangle", 3)
 
-    element = (P3 * P3) * (P3 * P3)
+    element = (P3 * P3) * (P3 * P3)  # noqa: F841
 
 
 def testMixedPoisson():
-
     q = 1
 
     BDM = FiniteElement("Brezzi-Douglas-Marini", "triangle", q)
@@ -133,12 +124,11 @@ def testMixedPoisson():
 
     f = Coefficient(DG)
 
-    a = (dot(tau, sigma) - div(tau) * u + w * div(sigma)) * dx
-    L = w * f * dx
+    a = (dot(tau, sigma) - div(tau) * u + w * div(sigma)) * dx  # noqa: F841
+    L = w * f * dx  # noqa: F841
 
 
 def testNavierStokes():
-
     element = VectorElement("Lagrange", "tetrahedron", 1)
 
     v = TestFunction(element)
@@ -147,11 +137,10 @@ def testNavierStokes():
     w = Coefficient(element)
 
     # FFC notation: a = v[i]*w[j]*D(u[i], j)*dx
-    a = v[i] * w[j] * Dx(u[i], j) * dx
+    a = v[i] * w[j] * Dx(u[i], j) * dx  # noqa: F841
 
 
 def testNeumannProblem():
-
     element = VectorElement("Lagrange", "triangle", 1)
 
     v = TestFunction(element)
@@ -160,36 +149,32 @@ def testNeumannProblem():
     g = Coefficient(element)
 
     # FFC notation: a = dot(grad(v), grad(u))*dx
-    a = inner(grad(v), grad(u)) * dx
+    a = inner(grad(v), grad(u)) * dx  # noqa: F841
 
     # FFC notation: L = dot(v, f)*dx + dot(v, g)*ds
-    L = inner(v, f) * dx + inner(v, g) * ds
+    L = inner(v, f) * dx + inner(v, g) * ds  # noqa: F841
 
 
 def testOptimization():
-
     element = FiniteElement("Lagrange", "triangle", 3)
 
     v = TestFunction(element)
     u = TrialFunction(element)
     f = Coefficient(element)
 
-    a = dot(grad(v), grad(u)) * dx
-    L = v * f * dx
+    a = dot(grad(v), grad(u)) * dx  # noqa: F841
+    L = v * f * dx  # noqa: F841
 
 
 def testP5tet():
-
-    element = FiniteElement("Lagrange", tetrahedron, 5)
+    element = FiniteElement("Lagrange", tetrahedron, 5)  # noqa: F841
 
 
 def testP5tri():
-
-    element = FiniteElement("Lagrange", triangle, 5)
+    element = FiniteElement("Lagrange", triangle, 5)  # noqa: F841
 
 
 def testPoissonDG():
-
     element = FiniteElement("Discontinuous Lagrange", triangle, 1)
 
     v = TestFunction(element)
@@ -215,19 +200,18 @@ def testPoissonDG():
     #    - dot(mult(v,n), grad(u))*ds \
     #    + gamma/h*v*u*ds
 
-    a = inner(grad(v), grad(u)) * dx \
-        - inner(avg(grad(v)), jump(u, n)) * dS \
-        - inner(jump(v, n), avg(grad(u))) * dS \
-        + alpha / h('+') * dot(jump(v, n), jump(u, n)) * dS \
-        - inner(grad(v), u * n) * ds \
-        - inner(u * n, grad(u)) * ds \
-        + gamma / h * v * u * ds
+    a = inner(grad(v), grad(u)) * dx
+    a -= inner(avg(grad(v)), jump(u, n)) * dS
+    a -= inner(jump(v, n), avg(grad(u))) * dS
+    a += alpha / h('+') * dot(jump(v, n), jump(u, n)) * dS
+    a -= inner(grad(v), u * n) * ds
+    a -= inner(u * n, grad(u)) * ds
+    a += gamma / h * v * u * ds
 
-    L = v * f * dx + v * gN * ds
+    L = v * f * dx + v * gN * ds  # noqa: F841
 
 
 def testPoisson():
-
     element = FiniteElement("Lagrange", "triangle", 1)
 
     v = TestFunction(element)
@@ -235,12 +219,11 @@ def testPoisson():
     f = Coefficient(element)
 
     # Note: inner() also works
-    a = dot(grad(v), grad(u)) * dx
-    L = v * f * dx
+    a = dot(grad(v), grad(u)) * dx  # noqa: F841
+    L = v * f * dx  # noqa: F841
 
 
 def testPoissonSystem():
-
     element = VectorElement("Lagrange", "triangle", 1)
 
     v = TestFunction(element)
@@ -248,24 +231,21 @@ def testPoissonSystem():
     f = Coefficient(element)
 
     # FFC notation: a = dot(grad(v), grad(u))*dx
-    a = inner(grad(v), grad(u)) * dx
+    a = inner(grad(v), grad(u)) * dx  # noqa: F841
 
     # FFC notation: L = dot(v, f)*dx
-    L = inner(v, f) * dx
+    L = inner(v, f) * dx  # noqa: F841
 
 
 def testProjection():
-
     # Projections are not supported by UFL and have been broken
     # in FFC for a while. For DOLFIN, the current (global) L^2
     # projection can be extended to handle also local projections.
 
-    P0 = FiniteElement("Discontinuous Lagrange", "triangle", 0)
     P1 = FiniteElement("Lagrange", "triangle", 1)
-    P2 = FiniteElement("Lagrange", "triangle", 2)
 
-    v = TestFunction(P1)
-    f = Coefficient(P1)
+    v = TestFunction(P1)  # noqa: F841
+    f = Coefficient(P1)  # noqa: F841
 
     # pi0 = Projection(P0)
     # pi1 = Projection(P1)
@@ -275,7 +255,6 @@ def testProjection():
 
 
 def testQuadratureElement():
-
     element = FiniteElement("Lagrange", "triangle", 2)
 
     # FFC notation:
@@ -292,12 +271,11 @@ def testQuadratureElement():
     sig0 = Coefficient(sig)
     f = Coefficient(element)
 
-    a = v.dx(i) * C * u.dx(i) * dx + v.dx(i) * 2 * u0 * u * u0.dx(i) * dx
-    L = v * f * dx - dot(grad(v), sig0) * dx
+    a = v.dx(i) * C * u.dx(i) * dx + v.dx(i) * 2 * u0 * u * u0.dx(i) * dx  # noqa: F841
+    L = v * f * dx - dot(grad(v), sig0) * dx  # noqa: F841
 
 
 def testStokes():
-
     # UFLException: Shape mismatch in sum.
 
     P2 = VectorElement("Lagrange", "triangle", 2)
@@ -311,35 +289,30 @@ def testStokes():
 
     # FFC notation:
     # a = (dot(grad(v), grad(u)) - div(v)*p + q*div(u))*dx
-    a = (inner(grad(v), grad(u)) - div(v) * p + q * div(u)) * dx
+    a = (inner(grad(v), grad(u)) - div(v) * p + q * div(u)) * dx  # noqa: F841
 
-    L = dot(v, f) * dx
+    L = dot(v, f) * dx  # noqa: F841
 
 
 def testSubDomain():
-
     element = FiniteElement("CG", "tetrahedron", 1)
 
-    v = TestFunction(element)
-    u = TrialFunction(element)
     f = Coefficient(element)
 
-    M = f * dx(2) + f * ds(5)
+    M = f * dx(2) + f * ds(5)  # noqa: F841
 
 
 def testSubDomains():
-
     element = FiniteElement("CG", "tetrahedron", 1)
 
     v = TestFunction(element)
     u = TrialFunction(element)
 
-    a = v * u * dx(0) + 10.0 * v * u * dx(1) + v * u * ds(0) + 2.0 * v * u * \
-        ds(1) + v('+') * u('+') * dS(0) + 4.3 * v('+') * u('+') * dS(1)
+    a = v * u * dx(0) + 10.0 * v * u * dx(1) + v * u * ds(0) + 2.0 * v * u * ds(1)
+    a += v('+') * u('+') * dS(0) + 4.3 * v('+') * u('+') * dS(1)
 
 
 def testTensorWeightedPoisson():
-
     # FFC notation:
     # P1 = FiniteElement("Lagrange", "triangle", 1)
     # P0 = FiniteElement("Discontinuous Lagrange", "triangle", 0)
@@ -364,11 +337,10 @@ def testTensorWeightedPoisson():
     u = TrialFunction(P1)
     C = Coefficient(P0)
 
-    a = inner(grad(v), C * grad(u)) * dx
+    a = inner(grad(v), C * grad(u)) * dx  # noqa: F841
 
 
 def testVectorLaplaceGradCurl():
-
     def HodgeLaplaceGradCurl(element, felement):
         (tau, v) = TestFunctions(element)
         (sigma, u) = TrialFunctions(element)
diff --git a/test/test_form.py b/test/test_form.py
index 71f4a2a20..057e89319 100755
--- a/test/test_form.py
+++ b/test/test_form.py
@@ -1,8 +1,7 @@
-#!/usr/bin/env py.test
-# -*- coding: utf-8 -*-
 import pytest
 
-from ufl import *
+from ufl import (Coefficient, Cofunction, FiniteElement, Form, FormSum, FunctionSpace, Mesh, SpatialCoordinate,
+                 TestFunction, TrialFunction, VectorElement, dot, ds, dx, grad, inner, nabla_grad, triangle)
 from ufl.form import BaseForm
 
 
@@ -127,7 +126,7 @@ def test_form_call():
     f = Coefficient(V)
     g = Coefficient(V)
     a = g*inner(grad(v), grad(u))*dx
-    M = a(f, f, coefficients={ g: 1 })
+    M = a(f, f, coefficients={g: 1})
     assert M == grad(f)**2*dx
 
     import sys
@@ -136,27 +135,27 @@ def test_form_call():
         M = eval("(a @ f) @ g")
         assert M == g*f*dx
 
+
 def test_formsum(mass):
     V = FiniteElement("CG", triangle, 1)
     v = Cofunction(V)
 
-    assert(v + mass)
-    assert(mass + v)
-    assert(isinstance((mass+v), FormSum))
+    assert v + mass
+    assert mass + v
+    assert isinstance((mass+v), FormSum)
 
-    assert(len((mass + v + v).components()) == 3)
+    assert len((mass + v + v).components()) == 3
     # Variational forms are summed appropriately
-    assert(len((mass + v + mass).components()) == 2)
-
-    assert(v - mass)
-    assert(mass - v)
-    assert(isinstance((mass+v), FormSum))
+    assert len((mass + v + mass).components()) == 2
 
-    assert(-v)
-    assert(isinstance(-v, BaseForm))
-    assert((-v).weights()[0] == -1)
+    assert v - mass
+    assert mass - v
+    assert isinstance((mass+v), FormSum)
 
-    assert(2 * v)
-    assert(isinstance(2 * v, BaseForm))
-    assert((2 * v).weights()[0] == 2) 
+    assert -v
+    assert isinstance(-v, BaseForm)
+    assert (-v).weights()[0] == -1
 
+    assert 2 * v
+    assert isinstance(2 * v, BaseForm)
+    assert (2 * v).weights()[0] == 2
diff --git a/test/test_grad.py b/test/test_grad.py
index a8d5eebdb..4b5d9a996 100755
--- a/test/test_grad.py
+++ b/test/test_grad.py
@@ -1,16 +1,7 @@
-#!/usr/bin/env py.test
-# -*- coding: utf-8 -*-
+"""Test use of grad in various situations."""
 
-"""
-Test use of grad in various situations.
-"""
-
-import pytest
-
-# This imports everything external code will see from ufl
-from ufl import *
-
-# from ufl.classes import ...
+from ufl import (Coefficient, Constant, FiniteElement, TensorConstant, TensorElement, VectorConstant, VectorElement,
+                 div, dx, grad, indices, inner, interval, tetrahedron, triangle)
 from ufl.algorithms import compute_form_data
 
 
@@ -125,17 +116,15 @@ def eval_t(x, derivatives=()):
     a8 = inner(div(grad(v)), v)*dx
     a9 = inner(div(grad(t)), t)*dx
 
-    fd0 = compute_form_data(a0)
-    fd1 = compute_form_data(a1)
-    fd2 = compute_form_data(a2)
-    fd3 = compute_form_data(a3)
-
-    fd4 = compute_form_data(a4)
-    fd5 = compute_form_data(a5)
-    fd6 = compute_form_data(a6)
+    compute_form_data(a0)
+    compute_form_data(a1)
+    compute_form_data(a2)
+    compute_form_data(a3)
 
-    fd7 = compute_form_data(a7)
-    fd8 = compute_form_data(a8)
-    fd9 = compute_form_data(a9)
+    compute_form_data(a4)
+    compute_form_data(a5)
+    compute_form_data(a6)
 
-    # self.assertTrue(False) # Just to show it runs
+    compute_form_data(a7)
+    compute_form_data(a8)
+    compute_form_data(a9)
diff --git a/test/test_illegal.py b/test/test_illegal.py
index ba59c1475..f5c8d06a0 100755
--- a/test/test_illegal.py
+++ b/test/test_illegal.py
@@ -1,10 +1,6 @@
-#!/usr/bin/env py.test
-# -*- coding: utf-8 -*-
-
 import pytest
 
-from ufl import *
-from ufl.algorithms import *
+from ufl import Argument, Coefficient, FiniteElement, VectorElement
 
 # TODO: Add more illegal expressions to check!
 
diff --git a/test/test_indexing.py b/test/test_indexing.py
index 95d1029c7..bb618e8f3 100755
--- a/test/test_indexing.py
+++ b/test/test_indexing.py
@@ -1,8 +1,7 @@
-#!/usr/bin/env py.test
-# -*- coding: utf-8 -*-
 import pytest
-from ufl import *
-from ufl.classes import *
+
+from ufl import Index, SpatialCoordinate, outer, triangle
+from ufl.classes import FixedIndex, Indexed, MultiIndex, Outer, Zero
 
 
 @pytest.fixture
@@ -28,23 +27,16 @@ def test_annotated_literals():
     assert z.ufl_shape == ()
     assert z.ufl_free_indices == ()
     assert z.ufl_index_dimensions == ()
-    #assert z.free_indices() == ()  # Deprecated interface
-    #assert z.index_dimensions() == {}  # Deprecated interface
 
     z = Zero((3,))
     assert z.ufl_shape == (3,)
     assert z.ufl_free_indices == ()
     assert z.ufl_index_dimensions == ()
-    #assert z.free_indices() == ()  # Deprecated interface
-    #assert z.index_dimensions() == {}  # Deprecated interface
 
     i = Index(count=2)
     j = Index(count=4)
-    # z = Zero((), (2, 4), (3, 5))
     z = Zero((), (j, i), {i: 3, j: 5})
     assert z.ufl_shape == ()
-    #assert z.free_indices() == (i, j)  # Deprecated interface
-    #assert z.index_dimensions() == {i: 3, j: 5}  # Deprecated interface
     assert z.ufl_free_indices == (2, 4)
     assert z.ufl_index_dimensions == (3, 5)
 
@@ -66,19 +58,3 @@ def test_fixed_indexing_of_expression(x1, x2, x3):
     mi = x000.ufl_operands[1]
     assert len(mi) == 3
     assert mi.indices() == (FixedIndex(0),) * 3
-
-
-def test_indexed():
-    pass
-
-
-def test_indexsum():
-    pass
-
-
-def test_componenttensor():
-    pass
-
-
-def test_tensoralgebra():
-    pass
diff --git a/test/test_indices.py b/test/test_indices.py
index a4b296dcb..564d356be 100755
--- a/test/test_indices.py
+++ b/test/test_indices.py
@@ -1,50 +1,29 @@
-#!/usr/bin/env py.test
-# -*- coding: utf-8 -*-
-
 import pytest
 
-from ufl import *
-# from ufl.indexutils import *
-from ufl.algorithms import *
+from ufl import (Argument, Coefficient, TensorElement, TestFunction, TrialFunction, VectorElement, as_matrix, as_tensor,
+                 as_vector, cos, dx, exp, i, indices, j, k, l, outer, sin, triangle)
 from ufl.classes import IndexSum
 
 # TODO: add more expressions to test as many possible combinations of index notation as feasible...
 
 
-def xtest_index_utils(self):
-    ii = indices(3)
-    assert ii == unique_indices(ii)
-    assert ii == unique_indices(ii+ii)
-
-    assert () == repeated_indices(ii)
-    assert ii == repeated_indices(ii+ii)
-
-    assert ii == shared_indices(ii, ii)
-    assert ii == shared_indices(ii, ii+ii)
-    assert ii == shared_indices(ii+ii, ii)
-    assert ii == shared_indices(ii+ii, ii+ii)
-
-    assert ii == single_indices(ii)
-    assert () == single_indices(ii+ii)
-
-
 def test_vector_indices(self):
     element = VectorElement("CG", "triangle", 1)
     u = Argument(element, 2)
     f = Coefficient(element)
-    a = u[i]*f[i]*dx
-    b = u[j]*f[j]*dx
+    u[i]*f[i]*dx
+    u[j]*f[j]*dx
 
 
 def test_tensor_indices(self):
     element = TensorElement("CG", "triangle", 1)
     u = Argument(element, 2)
     f = Coefficient(element)
-    a = u[i, j]*f[i, j]*dx
-    b = u[j, i]*f[i, j]*dx
-    c = u[j, i]*f[j, i]*dx
+    u[i, j]*f[i, j]*dx
+    u[j, i]*f[i, j]*dx
+    u[j, i]*f[j, i]*dx
     with pytest.raises(BaseException):
-        d = (u[i, i]+f[j, i])*dx
+        (u[i, i]+f[j, i])*dx
 
 
 def test_indexed_sum1(self):
@@ -71,7 +50,7 @@ def test_indexed_sum3(self):
     u = Argument(element, 2)
     f = Coefficient(element)
     with pytest.raises(BaseException):
-        a = u[i]+f[j]
+        u[i]+f[j]
 
 
 def test_indexed_function1(self):
@@ -80,7 +59,7 @@ def test_indexed_function1(self):
     u = Argument(element, 3)
     f = Coefficient(element)
     aarg = (u[i]+f[i])*v[i]
-    a = exp(aarg)*dx
+    exp(aarg)*dx
 
 
 def test_indexed_function2(self):
@@ -88,34 +67,34 @@ def test_indexed_function2(self):
     v = Argument(element, 2)
     u = Argument(element, 3)
     f = Coefficient(element)
-    bfun  = cos(f[0])
-    left  = u[i] + f[i]
+    bfun = cos(f[0])
+    left = u[i] + f[i]
     right = v[i] * bfun
     assert len(left.ufl_free_indices) == 1
     assert left.ufl_free_indices[0] == i.count()
     assert len(right.ufl_free_indices) == 1
     assert right.ufl_free_indices[0] == i.count()
-    b = left * right * dx
+    left * right * dx
 
 
 def test_indexed_function3(self):
     element = VectorElement("CG", "triangle", 1)
-    v = Argument(element, 2)
+    Argument(element, 2)
     u = Argument(element, 3)
     f = Coefficient(element)
     with pytest.raises(BaseException):
-        c = sin(u[i] + f[i])*dx
+        sin(u[i] + f[i])*dx
 
 
 def test_vector_from_indices(self):
     element = VectorElement("CG", "triangle", 1)
-    v  = TestFunction(element)
-    u  = TrialFunction(element)
+    v = TestFunction(element)
+    u = TrialFunction(element)
 
     # legal
     vv = as_vector(u[i], i)
     uu = as_vector(v[j], j)
-    w  = v + u
+    w = v + u
     ww = vv + uu
     assert len(vv.ufl_shape) == 1
     assert len(uu.ufl_shape) == 1
@@ -125,14 +104,14 @@ def test_vector_from_indices(self):
 
 def test_matrix_from_indices(self):
     element = VectorElement("CG", "triangle", 1)
-    v  = TestFunction(element)
-    u  = TrialFunction(element)
-
-    A  = as_matrix(u[i]*v[j], (i, j))
-    B  = as_matrix(v[k]*v[k]*u[i]*v[j], (j, i))
-    C  = A + A
-    C  = B + B
-    D  = A + B
+    v = TestFunction(element)
+    u = TrialFunction(element)
+
+    A = as_matrix(u[i]*v[j], (i, j))
+    B = as_matrix(v[k]*v[k]*u[i]*v[j], (j, i))
+    C = A + A
+    C = B + B
+    D = A + B
     assert len(A.ufl_shape) == 2
     assert len(B.ufl_shape) == 2
     assert len(C.ufl_shape) == 2
@@ -141,8 +120,8 @@ def test_matrix_from_indices(self):
 
 def test_vector_from_list(self):
     element = VectorElement("CG", "triangle", 1)
-    v  = TestFunction(element)
-    u  = TrialFunction(element)
+    v = TestFunction(element)
+    u = TrialFunction(element)
 
     # create vector from list
     vv = as_vector([u[0], v[0]])
@@ -153,17 +132,17 @@ def test_vector_from_list(self):
 
 def test_matrix_from_list(self):
     element = VectorElement("CG", "triangle", 1)
-    v  = TestFunction(element)
-    u  = TrialFunction(element)
+    v = TestFunction(element)
+    u = TrialFunction(element)
 
     # create matrix from list
-    A  = as_matrix([[u[0], u[1]], [v[0], v[1]]])
+    A = as_matrix([[u[0], u[1]], [v[0], v[1]]])
     # create matrix from indices
-    B  = as_matrix((v[k]*v[k]) * u[i]*v[j], (j, i))
+    B = as_matrix((v[k]*v[k]) * u[i]*v[j], (j, i))
     # Test addition
-    C  = A + A
-    C  = B + B
-    D  = A + B
+    C = A + A
+    C = B + B
+    D = A + B
     assert len(A.ufl_shape) == 2
     assert len(B.ufl_shape) == 2
     assert len(C.ufl_shape) == 2
@@ -172,10 +151,10 @@ def test_matrix_from_list(self):
 
 def test_tensor(self):
     element = VectorElement("CG", "triangle", 1)
-    v  = TestFunction(element)
-    u  = TrialFunction(element)
-    f  = Coefficient(element)
-    g  = Coefficient(element)
+    v = TestFunction(element)
+    u = TrialFunction(element)
+    f = Coefficient(element)
+    g = Coefficient(element)
 
     # define the components of a fourth order tensor
     Cijkl = u[i]*v[j]*f[k]*g[l]
@@ -188,34 +167,32 @@ def test_tensor(self):
     self.assertSameIndices(C, ())
 
     # get sub-matrix
-    A = C[:,:, 0, 0]
+    A = C[:, :, 0, 0]
     assert len(A.ufl_shape) == 2
     self.assertSameIndices(A, ())
-    A = C[:,:, i, j]
+    A = C[:, :, i, j]
     assert len(A.ufl_shape) == 2
     assert set(A.ufl_free_indices) == {i.count(), j.count()}
 
     # legal?
     vv = as_vector([u[i], v[i]])
-    ww = f[i]*vv # this is well defined: ww = sum_i <f_i*u_i, f_i*v_i>
+    f[i]*vv  # this is well defined: ww = sum_i <f_i*u_i, f_i*v_i>
 
     # illegal
     with pytest.raises(BaseException):
-        vv = as_vector([u[i], v[j]])
+        as_vector([u[i], v[j]])
 
     # illegal
     with pytest.raises(BaseException):
-        A = as_matrix([[u[0], u[1]], [v[0],]])
-
-    # ...
+        as_matrix([[u[0], u[1]], [v[0]]])
 
 
 def test_indexed(self):
     element = VectorElement("CG", "triangle", 1)
-    v  = TestFunction(element)
-    u  = TrialFunction(element)
-    f  = Coefficient(element)
-    i, j, k, l = indices(4)
+    v = TestFunction(element)
+    u = TrialFunction(element)
+    Coefficient(element)
+    i, j, k, l = indices(4)  # noqa: E741
 
     a = v[i]
     self.assertSameIndices(a, (i,))
@@ -231,9 +208,9 @@ def test_indexed(self):
 def test_spatial_derivative(self):
     cell = triangle
     element = VectorElement("CG", cell, 1)
-    v  = TestFunction(element)
-    u  = TrialFunction(element)
-    i, j, k, l = indices(4)
+    v = TestFunction(element)
+    u = TrialFunction(element)
+    i, j, k, l = indices(4)  # noqa: E741
     d = cell.geometric_dimension()
 
     a = v[i].dx(i)
diff --git a/test/test_interpolate.py b/test/test_interpolate.py
index d7e79dff1..245830f74 100644
--- a/test/test_interpolate.py
+++ b/test/test_interpolate.py
@@ -1,24 +1,17 @@
-#!/usr/bin/env py.test
-# -*- coding: utf-8 -*-
-
-import pytest
-from ufl import *
-
+"""Test Interpolate object."""
 
 __authors__ = "Nacime Bouziani"
 __date__ = "2021-11-19"
 
-"""
-Test Interpolate object
-"""
+import pytest
 
-from ufl.core.interpolate import Interpolate
+from ufl import (Action, Adjoint, Argument, Coefficient, FiniteElement, FunctionSpace, TestFunction, TrialFunction,
+                 action, adjoint, derivative, dx, grad, inner, replace, triangle)
 from ufl.algorithms.ad import expand_derivatives
-from ufl.algorithms.analysis import (extract_coefficients, extract_arguments,
-                                     extract_arguments_and_coefficients,
-                                     extract_base_form_operators)
-
+from ufl.algorithms.analysis import (extract_arguments, extract_arguments_and_coefficients, extract_base_form_operators,
+                                     extract_coefficients)
 from ufl.algorithms.expand_indices import expand_indices
+from ufl.core.interpolate import Interpolate
 from ufl.domain import default_domain
 
 
diff --git a/test/test_lhs_rhs.py b/test/test_lhs_rhs.py
index d73f956f6..a34851b33 100755
--- a/test/test_lhs_rhs.py
+++ b/test/test_lhs_rhs.py
@@ -1,13 +1,10 @@
-#!/usr/bin/env py.test
-# -*- coding: utf-8 -*-
-
 __authors__ = "Marie E. Rognes"
 
 # First added: 2011-11-09
 # Last changed: 2011-11-09
 
-import pytest
-from ufl import *
+from ufl import (Argument, Coefficient, Constant, FiniteElement, TestFunction, TrialFunction, action, derivative, ds,
+                 dS, dx, exp, interval, system)
 
 
 def test_lhs_rhs_simple():
@@ -19,22 +16,22 @@ def test_lhs_rhs_simple():
 
     F0 = f * u * v * w * dx
     a, L = system(F0)
-    assert(len(a.integrals()) == 0)
-    assert(len(L.integrals()) == 0)
+    assert len(a.integrals()) == 0
+    assert len(L.integrals()) == 0
 
     F1 = derivative(F0, f)
     a, L = system(F1)
-    assert(len(a.integrals()) == 0)
-    assert(len(L.integrals()) == 0)
+    assert len(a.integrals()) == 0
+    assert len(L.integrals()) == 0
 
     F2 = action(F0, f)
     a, L = system(F2)
-    assert(len(a.integrals()) == 1)
-    assert(len(L.integrals()) == 0)
+    assert len(a.integrals()) == 1
+    assert len(L.integrals()) == 0
 
     F3 = action(F2, f)
     a, L = system(F3)
-    assert(len(L.integrals()) == 1)
+    assert len(L.integrals()) == 1
 
 
 def test_lhs_rhs_derivatives():
@@ -45,10 +42,10 @@ def test_lhs_rhs_derivatives():
 
     F0 = exp(f) * u * v * dx + v * dx + f * v * ds + exp(f)('+') * v * dS
     a, L = system(F0)
-    assert(len(a.integrals()) == 1)
-    assert(len(L.integrals()) == 3)
+    assert len(a.integrals()) == 1
+    assert len(L.integrals()) == 3
 
-    F1 = derivative(F0, f)
+    derivative(F0, f)
     a, L = system(F0)
 
 
@@ -65,9 +62,9 @@ def test_lhs_rhs_slightly_obscure():
     # F = f*u*w*dx + f*w*dx
     F = f * u * w * dx
     a, L = system(F)
-    assert(len(a.integrals()) == 1)
-    assert(len(L.integrals()) == 0)
+    assert len(a.integrals()) == 1
+    assert len(L.integrals()) == 0
 
     F = f * w * dx
     a, L = system(F)
-    assert(len(L.integrals()) == 1)
+    assert len(L.integrals()) == 1
diff --git a/test/test_literals.py b/test/test_literals.py
index ef8217a4f..aed180b24 100755
--- a/test/test_literals.py
+++ b/test/test_literals.py
@@ -1,29 +1,14 @@
-#!/usr/bin/env py.test
-# -*- coding: utf-8 -*-
-
 __authors__ = "Martin Sandve Alnæs"
-__date__ = "2011-04-14 -- 2011-04-14"
-
-import pytest
+__date__ = "2011-04-14"
 
-from ufl import *
+from ufl import PermutationSymbol, as_matrix, as_vector, indices, product
 from ufl.classes import Indexed
-from ufl.constantvalue import Zero, FloatValue, IntValue, ComplexValue, as_ufl
+from ufl.constantvalue import ComplexValue, FloatValue, IntValue, Zero, as_ufl
 
 
 def test_zero(self):
     z1 = Zero(())
-    z2 = Zero(())
-    z3 = as_ufl(0)
-    z4 = as_ufl(0.0)
-    z5 = FloatValue(0)
-    z6 = FloatValue(0.0)
-
-    # self.assertTrue(z1 is z2)
-    # self.assertTrue(z1 is z3)
-    # self.assertTrue(z1 is z4)
-    # self.assertTrue(z1 is z5)
-    # self.assertTrue(z1 is z6)
+
     assert z1 == z1
     assert int(z1) == 0
     assert float(z1) == 0.0
@@ -150,7 +135,7 @@ def test_permutation_symbol_n(self):
 
 
 def test_unit_dyads(self):
-    from ufl.tensors import unit_vectors, unit_matrices
+    from ufl.tensors import unit_matrices, unit_vectors
     ei, ej = unit_vectors(2)
     self.assertEqual(as_vector((1, 0)), ei)
     self.assertEqual(as_vector((0, 1)), ej)
diff --git a/test/test_measures.py b/test/test_measures.py
index 28852b4a4..86a8ea68c 100755
--- a/test/test_measures.py
+++ b/test/test_measures.py
@@ -1,21 +1,9 @@
-#!/usr/bin/env py.test
-# -*- coding: utf-8 -*-
-
-"""
-Tests of the various ways Measure objects can be created and used.
-"""
-
-import pytest
-
-# This imports everything external code will see from ufl
-from ufl import *
-from ufl.algorithms import compute_form_data
-
-# all_cells = (interval, triangle, tetrahedron,
-#             quadrilateral, hexahedron)
+"""Tests of the various ways Measure objects can be created and used."""
 
 from mockobjects import MockMesh, MockMeshFunction
 
+from ufl import Cell, Coefficient, FiniteElement, FunctionSpace, Measure, Mesh, as_ufl, dC, dI, dO, triangle
+
 
 def test_construct_forms_from_default_measures():
     # Create defaults:
@@ -64,12 +52,12 @@ def test_construct_forms_from_default_measures():
     assert dS_v.integral_type() == "interior_facet_vert"
 
     # Check that defaults are set properly
-    assert dx.ufl_domain() == None
+    assert dx.ufl_domain() is None
     assert dx.metadata() == {}
 
     # Check that we can create a basic form with default measure
     one = as_ufl(1)
-    a = one * dx(Mesh(triangle))
+    one * dx(Mesh(triangle))
 
 
 def test_foo():
@@ -147,8 +135,6 @@ def test_foo():
     assert dxm.ufl_domain() is None
     assert dxm.subdomain_id() == "everywhere"
 
-    dxi = dx(metadata={"quadrature_degree": 3})
-
     # Mock some dolfin data structures
     dx = Measure("dx")
     ds = Measure("ds")
diff --git a/test/test_mixed_function_space.py b/test/test_mixed_function_space.py
index 4cb5abb3a..28c01f35f 100644
--- a/test/test_mixed_function_space.py
+++ b/test/test_mixed_function_space.py
@@ -1,17 +1,10 @@
-#!/usr/bin/env py.test
-# -*- coding: utf-8 -*-
-
-from ufl import *
-
 __authors__ = "Cecile Daversin Catty"
 __date__ = "2019-03-26 -- 2019-03-26"
 
-import pytest
-
-from ufl import *
+from ufl import (FiniteElement, FunctionSpace, Measure, MixedFunctionSpace, TestFunctions, TrialFunctions, interval,
+                 tetrahedron, triangle)
+from ufl.algorithms.formsplitter import extract_blocks
 from ufl.domain import default_domain
-from ufl.algorithms.formsplitter import extract_blocks 
-
 
 
 def test_mixed_functionspace(self):
@@ -31,20 +24,20 @@ def test_mixed_functionspace(self):
     # MixedFunctionSpace = V_3d x V_2d x V_1d
     V = MixedFunctionSpace(V_3d, V_2d, V_1d)
     # Check sub spaces
-    assert( V.num_sub_spaces() == 3 )
-    assert( V.ufl_sub_space(0) == V_3d )
-    assert( V.ufl_sub_space(1) == V_2d )
-    assert( V.ufl_sub_space(2) == V_1d )
+    assert V.num_sub_spaces() == 3
+    assert V.ufl_sub_space(0) == V_3d
+    assert V.ufl_sub_space(1) == V_2d
+    assert V.ufl_sub_space(2) == V_1d
 
     # Arguments from MixedFunctionSpace
     (u_3d, u_2d, u_1d) = TrialFunctions(V)
     (v_3d, v_2d, v_1d) = TestFunctions(V)
-    
+
     # Measures
     dx3 = Measure("dx", domain=V_3d)
     dx2 = Measure("dx", domain=V_2d)
     dx1 = Measure("dx", domain=V_1d)
-    
+
     # Mixed variational form
     # LHS
     a_11 = u_1d*v_1d*dx1
@@ -65,30 +58,29 @@ def test_mixed_functionspace(self):
 
     # Check extract_block algorithm
     # LHS
-    assert ( extract_blocks(a,0,0) == a_33 )
-    assert ( extract_blocks(a,0,1) == a_23 )
-    assert ( extract_blocks(a,0,2) == a_13 )
-    assert ( extract_blocks(a,1,0) == a_32 )
-    assert ( extract_blocks(a,1,1) == a_22 )
-    assert ( extract_blocks(a,1,2) == a_12 )
-    assert ( extract_blocks(a,2,0) == a_31 )
-    assert ( extract_blocks(a,2,1) == a_21 )
-    assert ( extract_blocks(a,2,2) == a_11 )
+    assert extract_blocks(a, 0, 0) == a_33
+    assert extract_blocks(a, 0, 1) == a_23
+    assert extract_blocks(a, 0, 2) == a_13
+    assert extract_blocks(a, 1, 0) == a_32
+    assert extract_blocks(a, 1, 1) == a_22
+    assert extract_blocks(a, 1, 2) == a_12
+    assert extract_blocks(a, 2, 0) == a_31
+    assert extract_blocks(a, 2, 1) == a_21
+    assert extract_blocks(a, 2, 2) == a_11
     # RHS
-    assert ( extract_blocks(f,0) == f_3 )
-    assert ( extract_blocks(f,1) == f_2 )
-    assert ( extract_blocks(f,2) == f_1 )
+    assert extract_blocks(f, 0) == f_3
+    assert extract_blocks(f, 1) == f_2
+    assert extract_blocks(f, 2) == f_1
 
     # Test dual space method
     V_dual = V.dual()
-    assert( V_dual.num_sub_spaces() == 3 )
-    assert( V_dual.ufl_sub_space(0) == V_3d.dual() )
-    assert( V_dual.ufl_sub_space(1) == V_2d.dual() )
-    assert( V_dual.ufl_sub_space(2) == V_1d.dual() )
-
-    V_dual = V.dual(*[0,2])
-    assert( V_dual.num_sub_spaces() == 3 )
-    assert( V_dual.ufl_sub_space(0) == V_3d.dual() )
-    assert( V_dual.ufl_sub_space(1) == V_2d )
-    assert( V_dual.ufl_sub_space(2) == V_1d.dual() )
+    assert V_dual.num_sub_spaces() == 3
+    assert V_dual.ufl_sub_space(0) == V_3d.dual()
+    assert V_dual.ufl_sub_space(1) == V_2d.dual()
+    assert V_dual.ufl_sub_space(2) == V_1d.dual()
 
+    V_dual = V.dual(0, 2)
+    assert V_dual.num_sub_spaces() == 3
+    assert V_dual.ufl_sub_space(0) == V_3d.dual()
+    assert V_dual.ufl_sub_space(1) == V_2d
+    assert V_dual.ufl_sub_space(2) == V_1d.dual()
diff --git a/test/test_new_ad.py b/test/test_new_ad.py
index 65b3dd158..173a39486 100755
--- a/test/test_new_ad.py
+++ b/test/test_new_ad.py
@@ -1,17 +1,8 @@
-#!/usr/bin/env py.test
-# -*- coding: utf-8 -*-
-import pytest
-
-from ufl import *
-
-from ufl.tensors import as_tensor
-from ufl.classes import Grad
-from ufl.algorithms import tree_format
+from ufl import (CellVolume, Coefficient, Constant, FacetNormal, FiniteElement, Identity, SpatialCoordinate,
+                 TestFunction, VectorConstant, VectorElement, as_ufl, cos, derivative, diff, exp, grad, ln, sin, tan,
+                 triangle, variable, zero)
+from ufl.algorithms.apply_derivatives import GenericDerivativeRuleset, GradRuleset, apply_derivatives
 from ufl.algorithms.renumbering import renumber_indices
-from ufl.algorithms.apply_derivatives import (
-    apply_derivatives, GenericDerivativeRuleset,
-    GradRuleset, VariableRuleset, GateauxDerivativeRuleset)
-
 
 # Note: the old tests in test_automatic_differentiation.py are a bit messy
 #       but still cover many things that are not in here yet.
@@ -31,8 +22,8 @@ def test_apply_derivatives_doesnt_change_expression_without_derivatives():
     z = zero((3, 2))
     one = as_ufl(1)
     two = as_ufl(2.0)
-    I = Identity(d)
-    literals = [z, one, two, I]
+    ident = Identity(d)
+    literals = [z, one, two, ident]
 
     # Geometry
     x = SpatialCoordinate(cell)
@@ -70,25 +61,24 @@ def test_literal_derivatives_are_zero():
     # Literals
     one = as_ufl(1)
     two = as_ufl(2.0)
-    I = Identity(d)
-    E = PermutationSymbol(d)
-    literals = [one, two, I]
+    ident = Identity(d)
+    literals = [one, two, ident]
 
     # Generic ruleset handles literals directly:
-    for l in literals:
+    for lit in literals:
         for sh in [(), (d,), (d, d+1)]:
-            assert GenericDerivativeRuleset(sh)(l) == zero(l.ufl_shape + sh)
+            assert GenericDerivativeRuleset(sh)(lit) == zero(lit.ufl_shape + sh)
 
     # Variables
     v0 = variable(one)
     v1 = variable(zero((d,)))
-    v2 = variable(I)
+    v2 = variable(ident)
     variables = [v0, v1, v2]
 
     # Test literals via apply_derivatives and variable ruleset:
-    for l in literals:
+    for lit in literals:
         for v in variables:
-            assert apply_derivatives(diff(l, v)) == zero(l.ufl_shape + v.ufl_shape)
+            assert apply_derivatives(diff(lit, v)) == zero(lit.ufl_shape + v.ufl_shape)
 
     V0 = FiniteElement("DG", cell, 0)
     V1 = FiniteElement("Lagrange", cell, 1)
@@ -99,9 +89,9 @@ def test_literal_derivatives_are_zero():
     args = [(u0, v0), (u1, v1)]
 
     # Test literals via apply_derivatives and variable ruleset:
-    for l in literals:
+    for lit in literals:
         for u, v in args:
-            assert apply_derivatives(derivative(l, u, v)) == zero(l.ufl_shape + v.ufl_shape)
+            assert apply_derivatives(derivative(lit, u, v)) == zero(lit.ufl_shape + v.ufl_shape)
 
     # Test grad ruleset directly since grad(literal) is invalid:
     assert GradRuleset(d)(one) == zero((d,))
@@ -122,14 +112,12 @@ def test_grad_ruleset():
     # Literals
     one = as_ufl(1)
     two = as_ufl(2.0)
-    I = Identity(d)
-    literals = [one, two, I]
+    ident = Identity(d)
 
     # Geometry
     x = SpatialCoordinate(cell)
     n = FacetNormal(cell)
     volume = CellVolume(cell)
-    geometry = [x, n, volume]
 
     # Arguments
     u0 = TestFunction(V0)
@@ -145,33 +133,20 @@ def test_grad_ruleset():
     vf0 = Coefficient(W0)
     vf1 = Coefficient(W1)
     vf2 = Coefficient(W2)
-    coefficients = [f0, f1, vf0, vf1]
-
-    # Expressions
-    e0 = f0 + f1
-    e1 = u0 * (f1/3 - f0**2)
-    e2 = exp(sin(cos(tan(ln(x[0])))))
-    expressions = [e0, e1, e2]
-
-    # Variables
-    v0 = variable(one)
-    v1 = variable(f1)
-    v2 = variable(f0*f1)
-    variables = [v0, v1, v2]
 
     rules = GradRuleset(d)
 
     # Literals
     assert rules(one) == zero((d,))
     assert rules(two) == zero((d,))
-    assert rules(I) == zero((d, d, d))
+    assert rules(ident) == zero((d, d, d))
 
     # Assumed piecewise constant geometry
     for g in [n, volume]:
         assert rules(g) == zero(g.ufl_shape + (d,))
 
     # Non-constant geometry
-    assert rules(x) == I
+    assert rules(x) == ident
 
     # Arguments
     for u in arguments:
diff --git a/test/test_pickle.py b/test/test_pickle.py
index 145df65b8..6e4633ff7 100755
--- a/test/test_pickle.py
+++ b/test/test_pickle.py
@@ -1,5 +1,3 @@
-#!/usr/bin/env py.test
-# -*- coding: utf-8 -*-
 """Pickle all the unit test forms from FFC 0.5.0"""
 
 __author__ = "Anders Logg (logg@simula.no) et al."
@@ -10,11 +8,13 @@
 # Examples copied from the FFC demo directory, examples contributed
 # by Johan Jansson, Kristian Oelgaard, Marie Rognes, and Garth Wells.
 
-import pytest
-from ufl import *
+import pickle
+
+from ufl import (Coefficient, Constant, Dx, FacetNormal, FiniteElement, Identity, TensorElement, TestFunction,
+                 TestFunctions, TrialFunction, TrialFunctions, VectorConstant, VectorElement, avg, curl, div, dot, dS,
+                 ds, dx, grad, i, inner, j, jump, lhs, rhs, sqrt, tetrahedron, triangle)
 from ufl.algorithms import compute_form_data
 
-import pickle
 p = pickle.HIGHEST_PROTOCOL
 
 
@@ -24,7 +24,6 @@ def testConstant():
 
     v = TestFunction(element)
     u = TrialFunction(element)
-    f = Coefficient(element)
 
     c = Constant("triangle")
     d = VectorConstant("triangle")
@@ -39,8 +38,8 @@ def testConstant():
     L_pickle = pickle.dumps(L, p)
     L_restore = pickle.loads(L_pickle)
 
-    assert(a.signature() == a_restore.signature())
-    assert(L.signature() == L_restore.signature())
+    assert a.signature() == a_restore.signature()
+    assert L.signature() == L_restore.signature()
 
 
 def testElasticity():
@@ -60,7 +59,7 @@ def eps(v):
     a_pickle = pickle.dumps(a, p)
     a_restore = pickle.loads(a_pickle)
 
-    assert(a.signature() == a_restore.signature())
+    assert a.signature() == a_restore.signature()
 
 
 def testEnergyNorm():
@@ -73,7 +72,7 @@ def testEnergyNorm():
     a_pickle = pickle.dumps(a, p)
     a_restore = pickle.loads(a_pickle)
 
-    assert(a.signature() == a_restore.signature())
+    assert a.signature() == a_restore.signature()
 
 
 def testEquation():
@@ -96,8 +95,8 @@ def testEquation():
     L_pickle = pickle.dumps(L, p)
     L_restore = pickle.loads(L_pickle)
 
-    assert(a.signature() == a_restore.signature())
-    assert(L.signature() == L_restore.signature())
+    assert a.signature() == a_restore.signature()
+    assert L.signature() == L_restore.signature()
 
 
 def testFunctionOperators():
@@ -117,7 +116,7 @@ def testFunctionOperators():
     a_pickle = pickle.dumps(a, p)
     a_restore = pickle.loads(a_pickle)
 
-    assert(a.signature() == a_restore.signature())
+    assert a.signature() == a_restore.signature()
 
 
 def testHeat():
@@ -139,8 +138,8 @@ def testHeat():
     L_pickle = pickle.dumps(L, p)
     L_restore = pickle.loads(L_pickle)
 
-    assert(a.signature() == a_restore.signature())
-    assert(L.signature() == L_restore.signature())
+    assert a.signature() == a_restore.signature()
+    assert L.signature() == L_restore.signature()
 
 
 def testMass():
@@ -155,7 +154,7 @@ def testMass():
     a_pickle = pickle.dumps(a, p)
     a_restore = pickle.loads(a_pickle)
 
-    assert(a.signature() == a_restore.signature())
+    assert a.signature() == a_restore.signature()
 
 
 def testMixedMixedElement():
@@ -167,7 +166,7 @@ def testMixedMixedElement():
     element_pickle = pickle.dumps(element, p)
     element_restore = pickle.loads(element_pickle)
 
-    assert(element == element_restore)
+    assert element == element_restore
 
 
 def testMixedPoisson():
@@ -192,8 +191,8 @@ def testMixedPoisson():
     L_pickle = pickle.dumps(L, p)
     L_restore = pickle.loads(L_pickle)
 
-    assert(a.signature() == a_restore.signature())
-    assert(L.signature() == L_restore.signature())
+    assert a.signature() == a_restore.signature()
+    assert L.signature() == L_restore.signature()
 
 
 def testNavierStokes():
@@ -211,7 +210,7 @@ def testNavierStokes():
     a_pickle = pickle.dumps(a, p)
     a_restore = pickle.loads(a_pickle)
 
-    assert(a.signature() == a_restore.signature())
+    assert a.signature() == a_restore.signature()
 
 
 def testNeumannProblem():
@@ -234,8 +233,8 @@ def testNeumannProblem():
     L_pickle = pickle.dumps(L, p)
     L_restore = pickle.loads(L_pickle)
 
-    assert(a.signature() == a_restore.signature())
-    assert(L.signature() == L_restore.signature())
+    assert a.signature() == a_restore.signature()
+    assert L.signature() == L_restore.signature()
 
 
 def testOptimization():
@@ -254,8 +253,8 @@ def testOptimization():
     L_pickle = pickle.dumps(L, p)
     L_restore = pickle.loads(L_pickle)
 
-    assert(a.signature() == a_restore.signature())
-    assert(L.signature() == L_restore.signature())
+    assert a.signature() == a_restore.signature()
+    assert L.signature() == L_restore.signature()
 
 
 def testP5tet():
@@ -265,7 +264,7 @@ def testP5tet():
     element_pickle = pickle.dumps(element, p)
     element_restore = pickle.loads(element_pickle)
 
-    assert(element == element_restore)
+    assert element == element_restore
 
 
 def testP5tri():
@@ -273,7 +272,7 @@ def testP5tri():
     element = FiniteElement("Lagrange", triangle, 5)
 
     element_pickle = pickle.dumps(element, p)
-    element_restore = pickle.loads(element_pickle)
+    pickle.loads(element_pickle)
 
 
 def testPoissonDG():
@@ -318,8 +317,8 @@ def testPoissonDG():
     L_pickle = pickle.dumps(L, p)
     L_restore = pickle.loads(L_pickle)
 
-    assert(a.signature() == a_restore.signature())
-    assert(L.signature() == L_restore.signature())
+    assert a.signature() == a_restore.signature()
+    assert L.signature() == L_restore.signature()
 
 
 def testPoisson():
@@ -339,8 +338,8 @@ def testPoisson():
     L_pickle = pickle.dumps(L, p)
     L_restore = pickle.loads(L_pickle)
 
-    assert(a.signature() == a_restore.signature())
-    assert(L.signature() == L_restore.signature())
+    assert a.signature() == a_restore.signature()
+    assert L.signature() == L_restore.signature()
 
 
 def testPoissonSystem():
@@ -362,8 +361,8 @@ def testPoissonSystem():
     L_pickle = pickle.dumps(L, p)
     L_restore = pickle.loads(L_pickle)
 
-    assert(a.signature() == a_restore.signature())
-    assert(L.signature() == L_restore.signature())
+    assert a.signature() == a_restore.signature()
+    assert L.signature() == L_restore.signature()
 
 
 def testQuadratureElement():
@@ -392,8 +391,8 @@ def testQuadratureElement():
     L_pickle = pickle.dumps(L, p)
     L_restore = pickle.loads(L_pickle)
 
-    assert(a.signature() == a_restore.signature())
-    assert(L.signature() == L_restore.signature())
+    assert a.signature() == a_restore.signature()
+    assert L.signature() == L_restore.signature()
 
 
 def testStokes():
@@ -420,16 +419,14 @@ def testStokes():
     L_pickle = pickle.dumps(L, p)
     L_restore = pickle.loads(L_pickle)
 
-    assert(a.signature() == a_restore.signature())
-    assert(L.signature() == L_restore.signature())
+    assert a.signature() == a_restore.signature()
+    assert L.signature() == L_restore.signature()
 
 
 def testSubDomain():
 
     element = FiniteElement("CG", "tetrahedron", 1)
 
-    v = TestFunction(element)
-    u = TrialFunction(element)
     f = Coefficient(element)
 
     M = f * dx(2) + f * ds(5)
@@ -437,7 +434,7 @@ def testSubDomain():
     M_pickle = pickle.dumps(M, p)
     M_restore = pickle.loads(M_pickle)
 
-    assert(M.signature() == M_restore.signature())
+    assert M.signature() == M_restore.signature()
 
 
 def testSubDomains():
@@ -453,7 +450,7 @@ def testSubDomains():
     a_pickle = pickle.dumps(a, p)
     a_restore = pickle.loads(a_pickle)
 
-    assert(a.signature() == a_restore.signature())
+    assert a.signature() == a_restore.signature()
 
 
 def testTensorWeightedPoisson():
@@ -487,7 +484,7 @@ def testTensorWeightedPoisson():
     a_pickle = pickle.dumps(a, p)
     a_restore = pickle.loads(a_pickle)
 
-    assert(a.signature() == a_restore.signature())
+    assert a.signature() == a_restore.signature()
 
 
 def testVectorLaplaceGradCurl():
@@ -524,8 +521,8 @@ def HodgeLaplaceGradCurl(element, felement):
     L_pickle = pickle.dumps(L, p)
     L_restore = pickle.loads(L_pickle)
 
-    assert(a.signature() == a_restore.signature())
-    assert(L.signature() == L_restore.signature())
+    assert a.signature() == a_restore.signature()
+    assert L.signature() == L_restore.signature()
 
 
 def testIdentity():
@@ -533,7 +530,7 @@ def testIdentity():
     i = Identity(2)
     i_pickle = pickle.dumps(i, p)
     i_restore = pickle.loads(i_pickle)
-    assert(i == i_restore)
+    assert i == i_restore
 
 
 def testFormData():
@@ -550,4 +547,4 @@ def testFormData():
     form_data_pickle = pickle.dumps(form_data, p)
     form_data_restore = pickle.loads(form_data_pickle)
 
-    assert(str(form_data) == str(form_data_restore))
+    assert str(form_data) == str(form_data_restore)
diff --git a/test/test_piecewise_checks.py b/test/test_piecewise_checks.py
index 1db8ec6c2..ba4beb28a 100755
--- a/test/test_piecewise_checks.py
+++ b/test/test_piecewise_checks.py
@@ -1,14 +1,13 @@
-#!/usr/bin/env py.test
-# -*- coding: utf-8 -*-
-
-"""
-Test the is_cellwise_constant function on all relevant terminal types.
-"""
+"""Test the is_cellwise_constant function on all relevant terminal types."""
 
 import pytest
-from ufl import *
-from ufl.classes import *
+
+from ufl import (Cell, CellDiameter, CellVolume, Circumradius, Coefficient, Constant, FacetArea, FacetNormal,
+                 FiniteElement, Jacobian, JacobianDeterminant, JacobianInverse, MaxFacetEdgeLength, Mesh,
+                 MinFacetEdgeLength, SpatialCoordinate, TestFunction, VectorElement, hexahedron, interval,
+                 quadrilateral, tetrahedron, triangle)
 from ufl.checks import is_cellwise_constant
+from ufl.classes import CellCoordinate, FacetJacobian, FacetJacobianDeterminant, FacetJacobianInverse
 
 
 def get_domains():
diff --git a/test/test_reference_shapes.py b/test/test_reference_shapes.py
index b5813560c..db4ac3313 100755
--- a/test/test_reference_shapes.py
+++ b/test/test_reference_shapes.py
@@ -1,9 +1,4 @@
-#!/usr/bin/env py.test
-# -*- coding: utf-8 -*-
-
-import pytest
-
-from ufl import *
+from ufl import Cell, FiniteElement, MixedElement, TensorElement, VectorElement
 
 
 def test_reference_shapes():
diff --git a/test/test_scratch.py b/test/test_scratch.py
index 81056f568..bcf0bd347 100755
--- a/test/test_scratch.py
+++ b/test/test_scratch.py
@@ -1,22 +1,18 @@
-#!/usr/bin/env py.test
-# -*- coding: utf-8 -*-
-"""
+"""Test scratch.
+
 This is a template file you can copy when making a new test case.
 Begin by copying this file to a filename matching test_*.py.
 The tests in the file will then automatically be run by ./test.py.
 Next look at the TODO markers below for places to edit.
 """
 
-import pytest
 import warnings
 
-# This imports everything external code will see from ufl
-from ufl import *
+from ufl import (Coefficient, FiniteElement, Identity, TensorElement, TestFunction, VectorElement, as_matrix, as_tensor,
+                 as_vector, dx, grad, indices, inner, outer, triangle)
+from ufl.classes import FixedIndex, FormArgument, Grad, Indexed, ListTensor, Zero
 from ufl.tensors import as_scalar, unit_indexed_tensor, unwrap_list_tensor
 
-# TODO: Import only what you need from classes and algorithms:
-from ufl.classes import Grad, FormArgument, Zero, Indexed, FixedIndex, ListTensor
-
 
 class MockForwardAD:
 
diff --git a/test/test_signature.py b/test/test_signature.py
index 96d6754e2..95e655262 100755
--- a/test/test_signature.py
+++ b/test/test_signature.py
@@ -1,17 +1,11 @@
-#!/usr/bin/env py.test
-# -*- coding: utf-8 -*-
-"""
-Test the computation of form signatures.
-"""
+"""Test the computation of form signatures."""
 
-import pytest
-
-from ufl import *
-
-from ufl.classes import MultiIndex, FixedIndex
+from ufl import (Argument, CellDiameter, CellVolume, Circumradius, Coefficient, FacetArea, FacetNormal, FiniteElement,
+                 FunctionSpace, Identity, Mesh, SpatialCoordinate, TensorElement, TestFunction, VectorElement,
+                 as_domain, as_vector, diff, dot, ds, dx, hexahedron, indices, inner, interval, quadrilateral,
+                 tetrahedron, triangle, variable)
 from ufl.algorithms.signature import compute_multiindex_hashdata, compute_terminal_hashdata
-
-from itertools import chain
+from ufl.classes import FixedIndex, MultiIndex
 
 # TODO: Test compute_terminal_hashdata
 #   TODO: Check that form argument counts only affect the sig by their relative ordering
@@ -79,10 +73,10 @@ def forms():
         for d in (2, 3):
             domain = as_domain({2: triangle, 3: tetrahedron}[d])
             x = SpatialCoordinate(domain)
-            I = Identity(d)
+            ident = Identity(d)
             for fv in (1.1, 2.2):
                 for iv in (5, 7):
-                    expr = (I[0, j]*(fv*x[j]))**iv
+                    expr = (ident[0, j]*(fv*x[j]))**iv
 
                     reprs.add(repr(expr))
                     hashes.add(hash(expr))
@@ -114,13 +108,13 @@ def forms():
             a = FacetArea(cell)
             # s = CellSurfaceArea(cell)
             v = CellVolume(cell)
-            I = Identity(d)
+            ident = Identity(d)
 
             ws = (x, n)
             qs = (h, r, a, v)  # , s)
             for w in ws:
                 for q in qs:
-                    expr = (I[0, j]*(q*w[j]))
+                    expr = (ident[0, j]*(q*w[j]))
 
                     reprs.add(repr(expr))
                     hashes.add(hash(expr))
@@ -386,7 +380,7 @@ def hashdatas():
             # each repetition but repr and hashes changing
             # because new indices are created each repetition.
             index_numbering = {}
-            i, j, k, l = indices(4)
+            i, j, k, l = indices(4)  # noqa: E741
             for expr in (MultiIndex((i,)),
                          MultiIndex((i,)),  # r
                          MultiIndex((i, j)),
diff --git a/test/test_simplify.py b/test/test_simplify.py
index 4bc9bd444..89afa3690 100755
--- a/test/test_simplify.py
+++ b/test/test_simplify.py
@@ -1,10 +1,8 @@
-#!/usr/bin/env py.test
-# -*- coding: utf-8 -*-
-
-import pytest
-from ufl.classes import Sum, Product
 import math
-from ufl import *
+
+from ufl import (Coefficient, FiniteElement, TestFunction, TrialFunction, VectorConstant, acos, as_tensor, as_ufl, asin,
+                 atan, cos, cosh, dx, exp, i, j, ln, max_value, min_value, outer, sin, sinh, tan, tanh, triangle)
+from ufl.algorithms import compute_form_data
 
 
 def xtest_zero_times_argument(self):
@@ -23,7 +21,6 @@ def xtest_zero_times_argument(self):
 def test_divisions(self):
     element = FiniteElement("CG", triangle, 1)
     f = Coefficient(element)
-    g = Coefficient(element)
 
     # Test simplification of division by 1
     a = f
@@ -97,22 +94,22 @@ def test_sums(self):
 
 
 def test_mathfunctions(self):
-    for i in (0.1, 0.3, 0.9):
-        assert math.sin(i) == sin(i)
-        assert math.cos(i) == cos(i)
-        assert math.tan(i) == tan(i)
-        assert math.sinh(i) == sinh(i)
-        assert math.cosh(i) == cosh(i)
-        assert math.tanh(i) == tanh(i)
-        assert math.asin(i) == asin(i)
-        assert math.acos(i) == acos(i)
-        assert math.atan(i) == atan(i)
-        assert math.exp(i) == exp(i)
-        assert math.log(i) == ln(i)
+    for a in (0.1, 0.3, 0.9):
+        assert math.sin(a) == sin(a)
+        assert math.cos(a) == cos(a)
+        assert math.tan(a) == tan(a)
+        assert math.sinh(a) == sinh(a)
+        assert math.cosh(a) == cosh(a)
+        assert math.tanh(a) == tanh(a)
+        assert math.asin(a) == asin(a)
+        assert math.acos(a) == acos(a)
+        assert math.atan(a) == atan(a)
+        assert math.exp(a) == exp(a)
+        assert math.log(a) == ln(a)
         # TODO: Implement automatic simplification of conditionals?
-        assert i == float(max_value(i, i-1))
+        assert a == float(max_value(a, a-1))
         # TODO: Implement automatic simplification of conditionals?
-        assert i == float(min_value(i, i+1))
+        assert a == float(min_value(a, a+1))
 
 
 def test_indexing(self):
@@ -125,5 +122,5 @@ def test_indexing(self):
 
     Bij = u[i]*v[j]
     Bij2 = as_tensor(Bij, (i, j))[i, j]
-    Bij3 = as_tensor(Bij, (i, j))
+    as_tensor(Bij, (i, j))
     assert Bij2 == Bij
diff --git a/test/test_sobolevspace.py b/test/test_sobolevspace.py
index fb579a2f7..ba4eee118 100755
--- a/test/test_sobolevspace.py
+++ b/test/test_sobolevspace.py
@@ -1,17 +1,12 @@
-#!/usr/bin/env py.test
-# -*- coding: utf-8 -*-
-
 __authors__ = "David Ham"
 __date__ = "2014-03-04"
 
-import pytest
-from ufl import (EnrichedElement, TensorProductElement,
-                 FiniteElement, triangle, interval,
-                 quadrilateral, HDiv, HCurl)
-from ufl.sobolevspace import SobolevSpace, DirectionalSobolevSpace
-from ufl import H2, H1, HDiv, HCurl, L2, HInf
 from math import inf
 
+from ufl import (H1, H2, L2, EnrichedElement, FiniteElement, HCurl, HDiv, HInf, TensorProductElement, interval,
+                 quadrilateral, triangle)
+from ufl.sobolevspace import SobolevSpace  # noqa: F401
+from ufl.sobolevspace import DirectionalSobolevSpace
 
 # Construct directional Sobolev spaces, with varying smoothness in
 # spatial coordinates
diff --git a/test/test_split.py b/test/test_split.py
index 1b7b4bd10..597c81f26 100755
--- a/test/test_split.py
+++ b/test/test_split.py
@@ -1,14 +1,8 @@
-#!/usr/bin/env py.test
-# -*- coding: utf-8 -*-
-
-from ufl import *
-
 __authors__ = "Martin Sandve Alnæs"
 __date__ = "2009-03-14 -- 2009-03-14"
 
-import pytest
-
-from ufl import *
+from ufl import (Coefficient, FiniteElement, MixedElement, TensorElement, TestFunction, VectorElement, as_vector,
+                 product, split, triangle)
 
 
 def test_split(self):
diff --git a/test/test_str.py b/test/test_str.py
index ffab81ea2..25d036369 100755
--- a/test/test_str.py
+++ b/test/test_str.py
@@ -1,7 +1,6 @@
-# -*- coding: utf-8 -*-
-
-from ufl import *
-from ufl.classes import *
+from ufl import (CellDiameter, CellVolume, Circumradius, FacetArea, FacetNormal, FiniteElement, Index,
+                 SpatialCoordinate, TestFunction, TrialFunction, as_matrix, as_ufl, as_vector, quadrilateral,
+                 tetrahedron, triangle)
 
 
 def test_str_int_value(self):
diff --git a/test/test_strip_forms.py b/test/test_strip_forms.py
index 83eaa7ca7..3e8a77608 100644
--- a/test/test_strip_forms.py
+++ b/test/test_strip_forms.py
@@ -1,14 +1,12 @@
 import gc
 import sys
 
-import pytest
-
-from ufl import *
-from ufl.algorithms import strip_terminal_data, replace_terminal_data
+from ufl import (Coefficient, Constant, FiniteElement, FunctionSpace, Mesh, TestFunction, TrialFunction, dx, grad,
+                 inner, triangle)
+from ufl.algorithms import replace_terminal_data, strip_terminal_data
 from ufl.core.ufl_id import attach_ufl_id
 from ufl.core.ufl_type import attach_operators_from_hash_data
 
-
 MIN_REF_COUNT = 2
 """The minimum value returned by sys.getrefcount."""
 
diff --git a/test/test_tensoralgebra.py b/test/test_tensoralgebra.py
index e8831a1d8..01b69d413 100755
--- a/test/test_tensoralgebra.py
+++ b/test/test_tensoralgebra.py
@@ -1,10 +1,9 @@
-# -*- coding: utf-8 -*-
-"""
-Test tensor algebra operators.
-"""
+"""Test tensor algebra operators."""
 
 import pytest
-from ufl import *
+
+from ufl import (FacetNormal, as_matrix, as_tensor, as_vector, cofac, cross, det, dev, diag, diag_vector, dot, inner,
+                 inv, outer, perp, skew, sym, tr, transpose, triangle, zero)
 from ufl.algorithms.remove_complex_nodes import remove_complex_nodes
 
 
@@ -182,18 +181,19 @@ def test_tr(self, A):
 def test_det(self, A):
     dims = (0, 1)
     C = det(A)
-    D = sum((-A[i, 0]*A[0, i] if i !=0 else A[i-1, -1]*A[i, 0]) for i in dims)
+    D = sum((-A[i, 0]*A[0, i] if i != 0 else A[i-1, -1]*A[i, 0]) for i in dims)
     self.assertEqualValues(C, D)
 
 
 def test_cofac(self, A):
     C = cofac(A)
-    D = as_matrix([[(-A[i,j] if i != j else A[i,j]) for j in (-1,0)] for i in (-1,0)])
+    D = as_matrix([[(-A[i, j] if i != j else A[i, j]) for j in (-1, 0)] for i in (-1, 0)])
     self.assertEqualValues(C, D)
 
 
 def xtest_inv(self, A):
+    # FIXME: Test fails probably due to integer division
     C = inv(A)
-    detA = sum((-A[i, 0]*A[0, i] if i !=0 else A[i-1, -1]*A[i, 0]) for i in (0,1))
-    D = as_matrix([[(-A[i,j] if i != j else A[i,j]) for j in (-1,0)] for i in (-1,0)]) / detA  # FIXME: Test fails probably due to integer division
+    detA = sum((-A[i, 0]*A[0, i] if i != 0 else A[i-1, -1]*A[i, 0]) for i in (0, 1))
+    D = as_matrix([[(-A[i, j] if i != j else A[i, j]) for j in (-1, 0)] for i in (-1, 0)]) / detA
     self.assertEqualValues(C, D)
diff --git a/test/test_utilities.py b/test/test_utilities.py
index 5cdcc46e4..4fdf660d6 100755
--- a/test/test_utilities.py
+++ b/test/test_utilities.py
@@ -1,12 +1,6 @@
-#!/usr/bin/env py.test
-# -*- coding: utf-8 -*-
+"""Test internal utility functions."""
 
-"""
-Test internal utility functions.
-"""
-
-from ufl.utils.indexflattening import (shape_to_strides, flatten_multiindex,
-                                       unflatten_index)
+from ufl.utils.indexflattening import flatten_multiindex, shape_to_strides, unflatten_index
 
 
 def test_shape_to_strides():
@@ -57,9 +51,8 @@ def test_component_numbering():
 
 
 def test_index_flattening():
-    from ufl.utils.indexflattening import (shape_to_strides,
-                                           flatten_multiindex,
-                                           unflatten_index)
+    from ufl.utils.indexflattening import flatten_multiindex, shape_to_strides, unflatten_index
+
     # Scalar shape
     s = ()
     st = shape_to_strides(s)