diff --git a/imapclient/imapclient.py b/imapclient/imapclient.py index 45ece113..39c5ca0a 100644 --- a/imapclient/imapclient.py +++ b/imapclient/imapclient.py @@ -830,7 +830,11 @@ def unselect_folder(self): """ logger.debug("< UNSELECT") # IMAP4 class has no `unselect` method so we can't use `_command_and_check` there - _typ, data = self._imap._simple_command("UNSELECT") + typ, data = self._imap._simple_command("UNSELECT") + # Mirror imaplib.IMAP4.unselect: return the connection to the + # authenticated state so subsequent commands (e.g. ENABLE) are legal. + if typ == "OK": + self._imap.state = "AUTH" return data[0] def _process_select_response(self, resp): diff --git a/tests/test_imapclient.py b/tests/test_imapclient.py index 0819eb72..b6065b4d 100644 --- a/tests/test_imapclient.py +++ b/tests/test_imapclient.py @@ -337,6 +337,18 @@ def test_unselect(self): self.assertEqual(result, "Unselect completed.") self.client._imap._simple_command.assert_called_with("UNSELECT") + def test_unselect_resets_state_to_auth(self): + # A successful UNSELECT should return the connection to the + # authenticated state (mirroring imaplib.IMAP4.unselect) so that + # subsequent commands such as ENABLE are legal again. See #639. + self.client._cached_capabilities = [b"UNSELECT"] + self.client._imap.state = "SELECTED" + self.client._imap._simple_command.return_value = ("OK", ["Unselect completed."]) + + self.client.unselect_folder() + + self.assertEqual(self.client._imap.state, "AUTH") + class TestAppend(IMAPClientTest): def test_without_msg_time(self):