diff --git a/lib/bb/tests/utils.py b/lib/bb/tests/utils.py
index 0c3360505..796f8398d 100644
--- a/lib/bb/tests/utils.py
+++ b/lib/bb/tests/utils.py
@@ -729,3 +729,25 @@ class SplitFileChecksums(unittest.TestCase):
         self.check("/a:Truex /b:False", ["/a:Truex /b:False"])
         self.check(":True :False", [":True", ":False"])
         self.check("/a:True:False /b:False", ["/a:True:False", "/b:False"])
+
+class ContextTests(unittest.TestCase):
+    def setUp(self):
+        self.d = bb.data.init()
+        self.context = bb.utils.get_context().copy()
+
+    def tearDown(self):
+        # Not set_context(), so a broken setter cannot leak into other tests.
+        bb.utils._context = self.context
+
+    def test_set_context(self):
+        context = bb.utils.clean_context()
+        bb.utils.set_context(context)
+        self.assertIs(bb.utils.get_context(), context)
+
+    def test_set_context_drops_methods(self):
+        bb.methodpool.insert_method("testfunc", "def testfunc(d):\n    return 'testvalue'\n", "test.bb", 1)
+        self.assertEqual(self.d.expand("${@testfunc(d)}"), "testvalue")
+
+        bb.utils.set_context(self.context.copy())
+        self.assertNotIn("testfunc", bb.utils.get_context())
+        self.assertRaises(bb.data_smart.ExpansionError, self.d.expand, "${@testfunc(d)}")
diff --git a/lib/bb/utils.py b/lib/bb/utils.py
index 0e2677f8e..78cb683b1 100644
--- a/lib/bb/utils.py
+++ b/lib/bb/utils.py
@@ -52,6 +52,7 @@ def get_context():
 
 
 def set_context(ctx):
+    global _context
     _context = ctx
 
 # Context used in better_exec, eval
