bpo-40375: Implement imaplib.IMAP4.unselect (GH-19712)

diff --git a/Lib/imaplib.py b/Lib/imaplib.py
index abfdd73..d9720f2 100644
--- a/Lib/imaplib.py
+++ b/Lib/imaplib.py
@@ -98,6 +98,7 @@
         'THREAD':       ('SELECTED',),
         'UID':          ('SELECTED',),
         'UNSUBSCRIBE':  ('AUTH', 'SELECTED'),
+        'UNSELECT':     ('SELECTED',),
         }
 
 #       Patterns to match server responses
@@ -902,6 +903,22 @@
         return self._simple_command('UNSUBSCRIBE', mailbox)
 
 
+    def unselect(self):
+        """Free server's resources associated with the selected mailbox
+        and returns the server to the authenticated state.
+        This command performs the same actions as CLOSE, except
+        that no messages are permanently removed from the currently
+        selected mailbox.
+
+        (typ, [data]) = <instance>.unselect()
+        """
+        try:
+            typ, data = self._simple_command('UNSELECT')
+        finally:
+            self.state = 'AUTH'
+        return typ, data
+
+
     def xatom(self, name, *args):
         """Allow simple extension commands
                 notified by server in CAPABILITY response.
diff --git a/Lib/test/test_imaplib.py b/Lib/test/test_imaplib.py
index 7645666..69ee63b 100644
--- a/Lib/test/test_imaplib.py
+++ b/Lib/test/test_imaplib.py
@@ -116,6 +116,7 @@
 
     def setup(self):
         super().setup()
+        self.server.is_selected = False
         self.server.logged = None
 
     def _send(self, message):
@@ -190,6 +191,18 @@
         self.server.logged = args[0]
         self._send_tagged(tag, 'OK', 'LOGIN completed')
 
+    def cmd_SELECT(self, tag, args):
+        self.server.is_selected = True
+        self._send_line(b'* 2 EXISTS')
+        self._send_tagged(tag, 'OK', '[READ-WRITE] SELECT completed.')
+
+    def cmd_UNSELECT(self, tag, args):
+        if self.server.is_selected:
+            self.server.is_selected = False
+            self._send_tagged(tag, 'OK', 'Returned to authenticated state. (Success)')
+        else:
+            self._send_tagged(tag, 'BAD', 'No mailbox selected')
+
 
 class NewIMAPTestsMixin():
     client = None
@@ -511,6 +524,18 @@
         self.assertEqual(typ, 'OK')
         self.assertEqual(data[0], b'() "." directoryA')
 
+    def test_unselect(self):
+        client, _ = self._setup(SimpleIMAPHandler)
+        client.login('user', 'pass')
+        typ, data = client.select()
+        self.assertEqual(typ, 'OK')
+        self.assertEqual(data[0], b'2')
+
+        typ, data = client.unselect()
+        self.assertEqual(typ, 'OK')
+        self.assertEqual(data[0], b'Returned to authenticated state. (Success)')
+        self.assertEqual(client.state, 'AUTH')
+
 
 class NewIMAPTests(NewIMAPTestsMixin, unittest.TestCase):
     imap_class = imaplib.IMAP4