tests for futures py import concurrent futures import gc import re import sys import threading import unittest from unittest import mock from types import genericalias import asyncio from asyncio import futures import warnings from test testasyncio import utils as testutils from test import support def teardownmodule asyncio seteventlooppolicynone def fakefuncf return f def firstcb pass def lastcb pass class duckfuture class that does not inherit from future but aims to be ducktype compatible with it asynciofutureblocking false cancelled false result none exception none def cancelself if self done return false self cancelled true return true def cancelledself return self cancelled def doneself return self cancelled or self result is not none or self exception is not none def resultself self assertfalseself cancelled if self exception is not none raise self exception return self result def exceptionself self assertfalseself cancelled return self exception def setresultself result self assertfalseself done self assertisnotnoneresult self result result def setexceptionself exception self assertfalseself done self assertisnotnoneexception self exception exception def iterself if not self done self asynciofutureblocking true yield self self asserttrueself done return self result class duckteststestutils testcase def setupself super setup self loop self newtestloop self addcleanupself loop close def testwrapfutureself f duckfuture g asyncio wrapfuturef self assertisg f def testensurefutureself f duckfuture g asyncio ensurefuturef self assertisg f class basefuturetests def newfutureself args kwargs return self clsargs kwargs def setupself super setup self loop self newtestloop self addcleanupself loop close def testgenericaliasself future self clsstr self assertequalfuture args str self assertisinstancefuture genericalias def testisfutureself class myfuture asynciofutureblocking none def initself self asynciofutureblocking false self assertfalseasyncio isfuturemyfuture self asserttrueasyncio isfuturemyfuture self assertfalseasyncio isfuture1 as isinstancemock future returns false self assertfalseasyncio isfuturemock mock f self newfutureloopself loop self asserttrueasyncio isfuturef self assertfalseasyncio isfuturetypef as isinstancemockfuture future returns true self asserttrueasyncio isfuturemock mocktypef f cancel def testinitialstateself f self newfutureloopself loop self assertfalsef cancelled self assertfalsef done f cancel self asserttruef cancelled def testconstructorwithoutloopself with self assertraisesregexruntimeerror no current event loop self newfuture def testconstructoruserunningloopself async def test return self newfuture f self loop rununtilcompletetest self assertisf loop self loop self assertisf getloop self loop def testconstructorusegloballoopself deprecated in 3 10 undeprecated in 3 12 asyncio seteventloopself loop self addcleanupasyncio seteventloop none f self newfuture self assertisf loop self loop self assertisf getloop self loop def testconstructorpositionalself make sure future doesn t accept a positional argument self assertraisestypeerror self newfuture 42 def testuninitializedself test that c future doesn t crash when future init call was skipped fut self cls newself cls loopself loop self assertraisesasyncio invalidstateerror fut result fut self cls newself cls loopself loop self assertraisesasyncio invalidstateerror fut exception fut self cls newself cls loopself loop with self assertraisesruntimeerror attributeerror fut setresultnone fut self cls newself cls loopself loop with self assertraisesruntimeerror attributeerror fut setexceptionexception fut self cls newself cls loopself loop with self assertraisesruntimeerror attributeerror fut cancel fut self cls newself cls loopself loop with self assertraisesruntimeerror attributeerror fut adddonecallbacklambda f none fut self cls newself cls loopself loop with self assertraisesruntimeerror attributeerror fut removedonecallbacklambda f none fut self cls newself cls loopself loop try reprfut except runtimeerror attributeerror pass fut self cls newself cls loopself loop try fut await except runtimeerror pass fut self cls newself cls loopself loop try iterfut except runtimeerror pass fut self cls newself cls loopself loop self assertfalsefut cancelled self assertfalsefut done def testfuturecancelmessagegetterself f self newfutureloopself loop self asserttruehasattrf cancelmessage self assertequalf cancelmessage none f cancel my message with self assertraisesasyncio cancellederror self loop rununtilcompletef self assertequalf cancelmessage my message def testfuturecancelmessagesetterself f self newfutureloopself loop f cancel my message f cancelmessage my new message self assertequalf cancelmessage my new message also check that the value is used for cancel with self assertraisesasyncio cancellederror self loop rununtilcompletef self assertequalf cancelmessage my new message def testcancelself f self newfutureloopself loop self asserttruef cancel self asserttruef cancelled self asserttruef done self assertraisesasyncio cancellederror f result self assertraisesasyncio cancellederror f exception self assertraisesasyncio invalidstateerror f setresult none self assertraisesasyncio invalidstateerror f setexception none self assertfalsef cancel def testresultself f self newfutureloopself loop self assertraisesasyncio invalidstateerror f result f setresult42 self assertfalsef cancelled self asserttruef done self assertequalf result 42 self assertequalf exception none self assertraisesasyncio invalidstateerror f setresult none self assertraisesasyncio invalidstateerror f setexception none self assertfalsef cancel def testexceptionself exc runtimeerror f self newfutureloopself loop self assertraisesasyncio invalidstateerror f exception stopiteration cannot be raised into a future cpython issue26221 self assertraisesregextypeerror stopiteration cannot be raised f setexception stopiteration f setexceptionexc self assertfalsef cancelled self asserttruef done self assertraisesruntimeerror f result self assertequalf exception exc self assertraisesasyncio invalidstateerror f setresult none self assertraisesasyncio invalidstateerror f setexception none self assertfalsef cancel def testexceptionclassself f self newfutureloopself loop f setexceptionruntimeerror self assertisinstancef exception runtimeerror def testyieldfromtwiceself f self newfutureloopself loop def fixture yield a x yield from f yield b x y yield from f yield c y g fixture self assertequalnextg a yield a self assertequalnextg f first yield from f f setresult42 self assertequalnextg b 42 yield b x the second yield from f does not yield f self assertequalnextg c 42 yield c y def testfuturereprself self loop setdebugtrue fpendingdebug self newfutureloopself loop frame fpendingdebug sourcetraceback1 self assertequal reprfpendingdebug f self cls name pending created at frame0 frame1 fpendingdebug cancel self loop setdebugfalse fpending self newfutureloopself loop self assertequalreprfpending f self cls name pending fpending cancel fcancelled self newfutureloopself loop fcancelled cancel self assertequalreprfcancelled f self cls name cancelled fresult self newfutureloopself loop fresult setresult4 self assertequal reprfresult f self cls name finished result4 self assertequalfresult result 4 exc runtimeerror fexception self newfutureloopself loop fexception setexceptionexc self assertequal reprfexception f self cls name finished exceptionruntimeerror self assertisfexception exception exc def funcreprfunc filename lineno testutils getfunctionsourcefunc text s at s s func qualname filename lineno return re escapetext fonecallbacks self newfutureloopself loop fonecallbacks adddonecallbackfakefunc fakerepr funcreprfakefunc self assertregex reprfonecallbacks r self cls name r pending cbs fakerepr fonecallbacks cancel self assertequalreprfonecallbacks f self cls name cancelled ftwocallbacks self newfutureloopself loop ftwocallbacks adddonecallbackfirstcb ftwocallbacks adddonecallbacklastcb firstrepr funcreprfirstcb lastrepr funcreprlastcb self assertregexreprftwocallbacks r self cls name r pending cbs s firstrepr lastrepr fmanycallbacks self newfutureloopself loop fmanycallbacks adddonecallbackfirstcb for i in range8 fmanycallbacks adddonecallbackfakefunc fmanycallbacks adddonecallbacklastcb cbregex r s 8 more s firstrepr lastrepr self assertregex reprfmanycallbacks r self cls name r pending cbs cbregex fmanycallbacks cancel self assertequalreprfmanycallbacks f self cls name cancelled def testcopystateself from asyncio futures import copyfuturestate f self newfutureloopself loop f setresult10 newf self newfutureloopself loop copyfuturestatef newf self asserttruenewf done self assertequalnewf result 10 fexception self newfutureloopself loop fexception setexceptionruntimeerror newfexception self newfutureloopself loop copyfuturestatefexception newfexception self asserttruenewfexception done self assertraisesruntimeerror newfexception result fcancelled self newfutureloopself loop fcancelled cancel newfcancelled self newfutureloopself loop copyfuturestatefcancelled newfcancelled self asserttruenewfcancelled cancelled def testiterself fut self newfutureloopself loop def coro yield from fut def test arg1 arg2 coro with self assertraisesregexruntimeerror await wasn t used test fut cancel def testlogtracebackself fut self newfutureloopself loop with self assertraisesregexvalueerror can only be set to false fut logtraceback true mock patch asyncio baseevents logger def testtbloggerabandonedself mlog fut self newfutureloopself loop del fut self assertfalsemlog error called mock patch asyncio baseevents logger def testtbloggernotcalledaftercancelself mlog fut self newfutureloopself loop fut setexceptionexception fut cancel del fut self assertfalsemlog error called mock patch asyncio baseevents logger def testtbloggerresultunretrievedself mlog fut self newfutureloopself loop fut setresult42 del fut self assertfalsemlog error called mock patch asyncio baseevents logger def testtbloggerresultretrievedself mlog fut self newfutureloopself loop fut setresult42 fut result del fut self assertfalsemlog error called mock patch asyncio baseevents logger def testtbloggerexceptionunretrievedself mlog fut self newfutureloopself loop fut setexceptionruntimeerror boom del fut testutils runbrieflyself loop support gccollect self asserttruemlog error called mock patch asyncio baseevents logger def testtbloggerexceptionretrievedself mlog fut self newfutureloopself loop fut setexceptionruntimeerror boom fut exception del fut self assertfalsemlog error called mock patch asyncio baseevents logger def testtbloggerexceptionresultretrievedself mlog fut self newfutureloopself loop fut setexceptionruntimeerror boom self assertraisesruntimeerror fut result del fut self assertfalsemlog error called def testwrapfutureself def runarg return arg threading getident ex concurrent futures threadpoolexecutor1 f1 ex submitrun oi f2 asyncio wrapfuturef1 loopself loop res ident self loop rununtilcompletef2 self asserttrueasyncio isfuturef2 self assertequalres oi self assertnotequalident threading getident ex shutdownwaittrue def testwrapfuturefutureself f1 self newfutureloopself loop f2 asyncio wrapfuturef1 self assertisf1 f2 def testwrapfuturewithoutloopself def runarg return arg threading getident ex concurrent futures threadpoolexecutor1 f1 ex submitrun oi with self assertraisesregexruntimeerror no current event loop asyncio wrapfuturef1 ex shutdownwaittrue def testwrapfutureuserunningloopself def runarg return arg threading getident ex concurrent futures threadpoolexecutor1 f1 ex submitrun oi async def test return asyncio wrapfuturef1 f2 self loop rununtilcompletetest self assertisself loop f2 loop ex shutdownwaittrue def testwrapfutureusegloballoopself deprecated in 3 10 undeprecated in 3 12 asyncio seteventloopself loop self addcleanupasyncio seteventloop none def runarg return arg threading getident ex concurrent futures threadpoolexecutor1 f1 ex submitrun oi f2 asyncio wrapfuturef1 self assertisself loop f2 loop ex shutdownwaittrue def testwrapfuturecancelself f1 concurrent futures future f2 asyncio wrapfuturef1 loopself loop f2 cancel testutils runbrieflyself loop self asserttruef1 cancelled self asserttruef2 cancelled def testwrapfuturecancel2self f1 concurrent futures future f2 asyncio wrapfuturef1 loopself loop f1 setresult42 f2 cancel testutils runbrieflyself loop self assertfalsef1 cancelled self assertequalf1 result 42 self asserttruef2 cancelled def testfuturesourcetracebackself self loop setdebugtrue future self newfutureloopself loop lineno sys getframe flineno 1 self assertisinstancefuture sourcetraceback list self assertequalfuture sourcetraceback2 3 file lineno testfuturesourcetraceback mock patch asyncio baseevents logger def checkfutureexceptionneverretrievedself debug mlog self loop setdebugdebug def memoryerror try raise memoryerror except baseexception as exc return exc exc memoryerror future self newfutureloopself loop future setexceptionexc future none testutils runbrieflyself loop support gccollect regex f self cls name exception was never retrievedn excinfo typeexc exc exc traceback mlog error assertcalledoncewithmock any excinfoexcinfo message mlog error callargs00 self assertregexmessage re compileregex re dotall def testfutureexceptionneverretrievedself self checkfutureexceptionneverretrievedfalse def testfutureexceptionneverretrieveddebugself self checkfutureexceptionneverretrievedtrue def testsetresultunlesscancelledself fut self newfutureloopself loop fut cancel futures setresultunlesscancelledfut 2 self asserttruefut cancelled def testfuturestopiterationargsself fut self newfutureloopself loop fut setresult1 2 fi fut iter result none try fi sendnone except stopiteration as ex result ex args0 else self fail stopiteration was expected self assertequalresult 1 2 def testfutureiterthrowself fut self newfutureloopself loop fi iterfut with self assertwarnsdeprecationwarning self assertraisesexception fi throw exception exceptionzebra none with warnings catchwarnings warnings filterwarningsignore categorydeprecationwarning self assertraisestypeerror fi throw exception exceptionelephant 32 self assertraisestypeerror fi throw exceptionelephant exceptionelephant https github compythoncpythonissues101326 self assertraisesvalueerror fi throw valueerror none none self assertraisestypeerror fi throw list def testfuturedelcollectself class evil def delself gc collect for i in range100 fut self newfutureloopself loop fut setresultevil unittest skipunlesshasattrfutures cfuture requires the c asyncio module class cfuturetestsbasefuturetests testutils testcase try cls futures cfuture except attributeerror cls none def testfuturedelsegfaultself fut self newfutureloopself loop with self assertraisesattributeerror del fut asynciofutureblocking with self assertraisesattributeerror del fut logtraceback unittest skipunlesshasattrfutures cfuture requires the c asyncio module class csubfuturetestsbasefuturetests testutils testcase try class csubfuturefutures cfuture pass cls csubfuture except attributeerror cls none class pyfuturetestsbasefuturetests testutils testcase cls futures pyfuture class basefuturedonecallbacktests def setupself super setup self loop self newtestloop def runbrieflyself testutils runbrieflyself loop def makecallbackself bag thing create a callback function that appends thing to bag def bagappenderfuture bag appendthing return bagappender def newfutureself raise notimplementederror def testcallbacksremovefirstcallbackself bag f self newfuture cb1 self makecallbackbag 42 cb2 self makecallbackbag 17 cb3 self makecallbackbag 100 f adddonecallbackcb1 f adddonecallbackcb2 f adddonecallbackcb3 f removedonecallbackcb1 f removedonecallbackcb1 self assertequalbag f setresult foo self runbriefly self assertequalbag 17 100 self assertequalf result foo def testcallbacksremovefirstandsecondcallbackself bag f self newfuture cb1 self makecallbackbag 42 cb2 self makecallbackbag 17 cb3 self makecallbackbag 100 f adddonecallbackcb1 f adddonecallbackcb2 f adddonecallbackcb3 f removedonecallbackcb1 f removedonecallbackcb2 f removedonecallbackcb1 self assertequalbag f setresult foo self runbriefly self assertequalbag 100 self assertequalf result foo def testcallbacksremovethirdcallbackself bag f self newfuture cb1 self makecallbackbag 42 cb2 self makecallbackbag 17 cb3 self makecallbackbag 100 f adddonecallbackcb1 f adddonecallbackcb2 f adddonecallbackcb3 f removedonecallbackcb3 f removedonecallbackcb3 self assertequalbag f setresult foo self runbriefly self assertequalbag 42 17 self assertequalf result foo def testcallbacksinvokedonsetresultself bag f self newfuture f adddonecallbackself makecallbackbag 42 f adddonecallbackself makecallbackbag 17 self assertequalbag f setresult foo self runbriefly self assertequalbag 42 17 self assertequalf result foo def testcallbacksinvokedonsetexceptionself bag f self newfuture f adddonecallbackself makecallbackbag 100 self assertequalbag exc runtimeerror f setexceptionexc self runbriefly self assertequalbag 100 self assertequalf exception exc def testremovedonecallbackself bag f self newfuture cb1 self makecallbackbag 1 cb2 self makecallbackbag 2 cb3 self makecallbackbag 3 add one cb1 and one cb2 f adddonecallbackcb1 f adddonecallbackcb2 one instance of cb2 removed now there s only one cb1 self assertequalf removedonecallbackcb2 1 never had any cb3 in there self assertequalf removedonecallbackcb3 0 after this there will be 6 instances of cb1 and one of cb2 f adddonecallbackcb2 for i in range5 f adddonecallbackcb1 remove all instances of cb1 one cb2 remains self assertequalf removedonecallbackcb1 6 self assertequalbag f setresult foo self runbriefly self assertequalbag 2 self assertequalf result foo def testremovedonecallbackslistmutationself see http bugs python orgissue28963 for details fut self newfuture fut adddonecallbackstr for in range63 fut adddonecallbackid class evil def eqself other fut removedonecallbackid return false fut removedonecallbackevil def testremovedonecallbackslistclearself see https github compythoncpythonissues97592 for details fut self newfuture fut adddonecallbackstr for in range63 fut adddonecallbackid class evil def eqself other fut removedonecallbackother fut removedonecallbackevil def testschedulecallbackslistmutation1self see http bugs python orgissue28963 for details def mutf f removedonecallbackstr fut self newfuture fut adddonecallbackmut fut adddonecallbackstr fut adddonecallbackstr fut setresult1 testutils runbrieflyself loop def testschedulecallbackslistmutation2self see http bugs python orgissue30828 for details fut self newfuture fut adddonecallbackstr for in range63 fut adddonecallbackid maxextracbs 100 extracbs 0 class evil def eqself other nonlocal extracbs extracbs 1 if extracbs maxextracbs fut adddonecallbackid return false fut removedonecallbackevil unittest skipunlesshasattrfutures cfuture requires the c asyncio module class cfuturedonecallbacktestsbasefuturedonecallbacktests testutils testcase def newfutureself return futures cfutureloopself loop unittest skipunlesshasattrfutures cfuture requires the c asyncio module class csubfuturedonecallbacktestsbasefuturedonecallbacktests testutils testcase def newfutureself class csubfuturefutures cfuture pass return csubfutureloopself loop class pyfuturedonecallbacktestsbasefuturedonecallbacktests testutils testcase def newfutureself return futures pyfutureloopself loop class basefutureinheritancetests def getfutureclsself raise notimplementederror def setupself super setup self loop self newtestloop self addcleanupself loop close def testinheritwithoutcallingsuperinitself see https bugs python orgissue38785 for the context cls self getfuturecls class myfutcls def initself args kwargs don t call super init pass fut myfutloopself loop with self assertraisesregex runtimeerror future object is not initialized fut getloop class pyfutureinheritancetestsbasefutureinheritancetests testutils testcase def getfutureclsself return futures pyfuture unittest skipunlesshasattrfutures cfuture requires the c asyncio module class cfutureinheritancetestsbasefutureinheritancetests testutils testcase def getfutureclsself return futures cfuture if name main unittest main class that does not inherit from future but aims to be duck type compatible with it as isinstance mock future returns false as isinstance mock future future returns true deprecated in 3 10 undeprecated in 3 12 make sure future doesn t accept a positional argument test that c future doesn t crash when future __init__ call was skipped also check that the value is used for cancel stopiteration cannot be raised into a future cpython issue26221 yield a first yield from f yield b x the second yield from f does not yield f yield c y deprecated in 3 10 undeprecated in 3 12 https github com python cpython issues 101326 create a callback function that appends thing to bag add one cb1 and one cb2 one instance of cb2 removed now there s only one cb1 never had any cb3 in there after this there will be 6 instances of cb1 and one of cb2 remove all instances of cb1 one cb2 remains see http bugs python org issue28963 for details see https github com python cpython issues 97592 for details see http bugs python org issue28963 for details see http bugs python org issue30828 for details see https bugs python org issue38785 for the context don t call super __init__
import concurrent.futures
import gc
import re
import sys
import threading
import unittest
from unittest import mock
from types import GenericAlias
import asyncio
from asyncio import futures
import warnings
from test.test_asyncio import utils as test_utils
from test import support


def tearDownModule():
    asyncio.set_event_loop_policy(None)


def _fakefunc(f):
    return f


def first_cb():
    pass


def last_cb():
    pass


class DuckFuture:
    
    

    _asyncio_future_blocking = False
    __cancelled = False
    __result = None
    __exception = None

    def cancel(self):
        if self.done():
            return False
        self.__cancelled = True
        return True

    def cancelled(self):
        return self.__cancelled

    def done(self):
        return (self.__cancelled
                or self.__result is not None
                or self.__exception is not None)

    def result(self):
        self.assertFalse(self.cancelled())
        if self.__exception is not None:
            raise self.__exception
        return self.__result

    def exception(self):
        self.assertFalse(self.cancelled())
        return self.__exception

    def set_result(self, result):
        self.assertFalse(self.done())
        self.assertIsNotNone(result)
        self.__result = result

    def set_exception(self, exception):
        self.assertFalse(self.done())
        self.assertIsNotNone(exception)
        self.__exception = exception

    def __iter__(self):
        if not self.done():
            self._asyncio_future_blocking = True
            yield self
        self.assertTrue(self.done())
        return self.result()


class DuckTests(test_utils.TestCase):

    def setUp(self):
        super().setUp()
        self.loop = self.new_test_loop()
        self.addCleanup(self.loop.close)

    def test_wrap_future(self):
        f = DuckFuture()
        g = asyncio.wrap_future(f)
        self.assertIs(g, f)

    def test_ensure_future(self):
        f = DuckFuture()
        g = asyncio.ensure_future(f)
        self.assertIs(g, f)


class BaseFutureTests:

    def _new_future(self,  *args, **kwargs):
        return self.cls(*args, **kwargs)

    def setUp(self):
        super().setUp()
        self.loop = self.new_test_loop()
        self.addCleanup(self.loop.close)

    def test_generic_alias(self):
        future = self.cls[str]
        self.assertEqual(future.__args__, (str,))
        self.assertIsInstance(future, GenericAlias)

    def test_isfuture(self):
        class MyFuture:
            _asyncio_future_blocking = None

            def __init__(self):
                self._asyncio_future_blocking = False

        self.assertFalse(asyncio.isfuture(MyFuture))
        self.assertTrue(asyncio.isfuture(MyFuture()))
        self.assertFalse(asyncio.isfuture(1))

        
        self.assertFalse(asyncio.isfuture(mock.Mock()))

        f = self._new_future(loop=self.loop)
        self.assertTrue(asyncio.isfuture(f))
        self.assertFalse(asyncio.isfuture(type(f)))

        
        self.assertTrue(asyncio.isfuture(mock.Mock(type(f))))

        f.cancel()

    def test_initial_state(self):
        f = self._new_future(loop=self.loop)
        self.assertFalse(f.cancelled())
        self.assertFalse(f.done())
        f.cancel()
        self.assertTrue(f.cancelled())

    def test_constructor_without_loop(self):
        with self.assertRaisesRegex(RuntimeError, 'no current event loop'):
            self._new_future()

    def test_constructor_use_running_loop(self):
        async def test():
            return self._new_future()
        f = self.loop.run_until_complete(test())
        self.assertIs(f._loop, self.loop)
        self.assertIs(f.get_loop(), self.loop)

    def test_constructor_use_global_loop(self):
        
        asyncio.set_event_loop(self.loop)
        self.addCleanup(asyncio.set_event_loop, None)
        f = self._new_future()
        self.assertIs(f._loop, self.loop)
        self.assertIs(f.get_loop(), self.loop)

    def test_constructor_positional(self):
        
        self.assertRaises(TypeError, self._new_future, 42)

    def test_uninitialized(self):
        
        

        fut = self.cls.__new__(self.cls, loop=self.loop)
        self.assertRaises(asyncio.InvalidStateError, fut.result)

        fut = self.cls.__new__(self.cls, loop=self.loop)
        self.assertRaises(asyncio.InvalidStateError, fut.exception)

        fut = self.cls.__new__(self.cls, loop=self.loop)
        with self.assertRaises((RuntimeError, AttributeError)):
            fut.set_result(None)

        fut = self.cls.__new__(self.cls, loop=self.loop)
        with self.assertRaises((RuntimeError, AttributeError)):
            fut.set_exception(Exception)

        fut = self.cls.__new__(self.cls, loop=self.loop)
        with self.assertRaises((RuntimeError, AttributeError)):
            fut.cancel()

        fut = self.cls.__new__(self.cls, loop=self.loop)
        with self.assertRaises((RuntimeError, AttributeError)):
            fut.add_done_callback(lambda f: None)

        fut = self.cls.__new__(self.cls, loop=self.loop)
        with self.assertRaises((RuntimeError, AttributeError)):
            fut.remove_done_callback(lambda f: None)

        fut = self.cls.__new__(self.cls, loop=self.loop)
        try:
            repr(fut)
        except (RuntimeError, AttributeError):
            pass

        fut = self.cls.__new__(self.cls, loop=self.loop)
        try:
            fut.__await__()
        except RuntimeError:
            pass

        fut = self.cls.__new__(self.cls, loop=self.loop)
        try:
            iter(fut)
        except RuntimeError:
            pass

        fut = self.cls.__new__(self.cls, loop=self.loop)
        self.assertFalse(fut.cancelled())
        self.assertFalse(fut.done())

    def test_future_cancel_message_getter(self):
        f = self._new_future(loop=self.loop)
        self.assertTrue(hasattr(f, '_cancel_message'))
        self.assertEqual(f._cancel_message, None)

        f.cancel('my message')
        with self.assertRaises(asyncio.CancelledError):
            self.loop.run_until_complete(f)
        self.assertEqual(f._cancel_message, 'my message')

    def test_future_cancel_message_setter(self):
        f = self._new_future(loop=self.loop)
        f.cancel('my message')
        f._cancel_message = 'my new message'
        self.assertEqual(f._cancel_message, 'my new message')

        
        with self.assertRaises(asyncio.CancelledError):
            self.loop.run_until_complete(f)
        self.assertEqual(f._cancel_message, 'my new message')

    def test_cancel(self):
        f = self._new_future(loop=self.loop)
        self.assertTrue(f.cancel())
        self.assertTrue(f.cancelled())
        self.assertTrue(f.done())
        self.assertRaises(asyncio.CancelledError, f.result)
        self.assertRaises(asyncio.CancelledError, f.exception)
        self.assertRaises(asyncio.InvalidStateError, f.set_result, None)
        self.assertRaises(asyncio.InvalidStateError, f.set_exception, None)
        self.assertFalse(f.cancel())

    def test_result(self):
        f = self._new_future(loop=self.loop)
        self.assertRaises(asyncio.InvalidStateError, f.result)

        f.set_result(42)
        self.assertFalse(f.cancelled())
        self.assertTrue(f.done())
        self.assertEqual(f.result(), 42)
        self.assertEqual(f.exception(), None)
        self.assertRaises(asyncio.InvalidStateError, f.set_result, None)
        self.assertRaises(asyncio.InvalidStateError, f.set_exception, None)
        self.assertFalse(f.cancel())

    def test_exception(self):
        exc = RuntimeError()
        f = self._new_future(loop=self.loop)
        self.assertRaises(asyncio.InvalidStateError, f.exception)

        
        self.assertRaisesRegex(TypeError, "StopIteration .* cannot be raised",
                               f.set_exception, StopIteration)

        f.set_exception(exc)
        self.assertFalse(f.cancelled())
        self.assertTrue(f.done())
        self.assertRaises(RuntimeError, f.result)
        self.assertEqual(f.exception(), exc)
        self.assertRaises(asyncio.InvalidStateError, f.set_result, None)
        self.assertRaises(asyncio.InvalidStateError, f.set_exception, None)
        self.assertFalse(f.cancel())

    def test_exception_class(self):
        f = self._new_future(loop=self.loop)
        f.set_exception(RuntimeError)
        self.assertIsInstance(f.exception(), RuntimeError)

    def test_yield_from_twice(self):
        f = self._new_future(loop=self.loop)

        def fixture():
            yield 'A'
            x = yield from f
            yield 'B', x
            y = yield from f
            yield 'C', y

        g = fixture()
        self.assertEqual(next(g), 'A')  
        self.assertEqual(next(g), f)  
        f.set_result(42)
        self.assertEqual(next(g), ('B', 42))  
        
        self.assertEqual(next(g), ('C', 42))  

    def test_future_repr(self):
        self.loop.set_debug(True)
        f_pending_debug = self._new_future(loop=self.loop)
        frame = f_pending_debug._source_traceback[-1]
        self.assertEqual(
            repr(f_pending_debug),
            f'<{self.cls.__name__} pending created at {frame[0]}:{frame[1]}>')
        f_pending_debug.cancel()

        self.loop.set_debug(False)
        f_pending = self._new_future(loop=self.loop)
        self.assertEqual(repr(f_pending), f'<{self.cls.__name__} pending>')
        f_pending.cancel()

        f_cancelled = self._new_future(loop=self.loop)
        f_cancelled.cancel()
        self.assertEqual(repr(f_cancelled), f'<{self.cls.__name__} cancelled>')

        f_result = self._new_future(loop=self.loop)
        f_result.set_result(4)
        self.assertEqual(
            repr(f_result), f'<{self.cls.__name__} finished result=4>')
        self.assertEqual(f_result.result(), 4)

        exc = RuntimeError()
        f_exception = self._new_future(loop=self.loop)
        f_exception.set_exception(exc)
        self.assertEqual(
            repr(f_exception),
            f'<{self.cls.__name__} finished exception=RuntimeError()>')
        self.assertIs(f_exception.exception(), exc)

        def func_repr(func):
            filename, lineno = test_utils.get_function_source(func)
            text = '%s() at %s:%s' % (func.__qualname__, filename, lineno)
            return re.escape(text)

        f_one_callbacks = self._new_future(loop=self.loop)
        f_one_callbacks.add_done_callback(_fakefunc)
        fake_repr = func_repr(_fakefunc)
        self.assertRegex(
            repr(f_one_callbacks),
            r'<' + self.cls.__name__ + r' pending cb=\[%s\]>' % fake_repr)
        f_one_callbacks.cancel()
        self.assertEqual(repr(f_one_callbacks),
                         f'<{self.cls.__name__} cancelled>')

        f_two_callbacks = self._new_future(loop=self.loop)
        f_two_callbacks.add_done_callback(first_cb)
        f_two_callbacks.add_done_callback(last_cb)
        first_repr = func_repr(first_cb)
        last_repr = func_repr(last_cb)
        self.assertRegex(repr(f_two_callbacks),
                         r'<' + self.cls.__name__ + r' pending cb=\[%s, %s\]>'
                         % (first_repr, last_repr))

        f_many_callbacks = self._new_future(loop=self.loop)
        f_many_callbacks.add_done_callback(first_cb)
        for i in range(8):
            f_many_callbacks.add_done_callback(_fakefunc)
        f_many_callbacks.add_done_callback(last_cb)
        cb_regex = r'%s, <8 more>, %s' % (first_repr, last_repr)
        self.assertRegex(
            repr(f_many_callbacks),
            r'<' + self.cls.__name__ + r' pending cb=\[%s\]>' % cb_regex)
        f_many_callbacks.cancel()
        self.assertEqual(repr(f_many_callbacks),
                         f'<{self.cls.__name__} cancelled>')

    def test_copy_state(self):
        from asyncio.futures import _copy_future_state

        f = self._new_future(loop=self.loop)
        f.set_result(10)

        newf = self._new_future(loop=self.loop)
        _copy_future_state(f, newf)
        self.assertTrue(newf.done())
        self.assertEqual(newf.result(), 10)

        f_exception = self._new_future(loop=self.loop)
        f_exception.set_exception(RuntimeError())

        newf_exception = self._new_future(loop=self.loop)
        _copy_future_state(f_exception, newf_exception)
        self.assertTrue(newf_exception.done())
        self.assertRaises(RuntimeError, newf_exception.result)

        f_cancelled = self._new_future(loop=self.loop)
        f_cancelled.cancel()

        newf_cancelled = self._new_future(loop=self.loop)
        _copy_future_state(f_cancelled, newf_cancelled)
        self.assertTrue(newf_cancelled.cancelled())

    def test_iter(self):
        fut = self._new_future(loop=self.loop)

        def coro():
            yield from fut

        def test():
            arg1, arg2 = coro()

        with self.assertRaisesRegex(RuntimeError, "await wasn't used"):
            test()
        fut.cancel()

    def test_log_traceback(self):
        fut = self._new_future(loop=self.loop)
        with self.assertRaisesRegex(ValueError, 'can only be set to False'):
            fut._log_traceback = True

    @mock.patch('asyncio.base_events.logger')
    def test_tb_logger_abandoned(self, m_log):
        fut = self._new_future(loop=self.loop)
        del fut
        self.assertFalse(m_log.error.called)

    @mock.patch('asyncio.base_events.logger')
    def test_tb_logger_not_called_after_cancel(self, m_log):
        fut = self._new_future(loop=self.loop)
        fut.set_exception(Exception())
        fut.cancel()
        del fut
        self.assertFalse(m_log.error.called)

    @mock.patch('asyncio.base_events.logger')
    def test_tb_logger_result_unretrieved(self, m_log):
        fut = self._new_future(loop=self.loop)
        fut.set_result(42)
        del fut
        self.assertFalse(m_log.error.called)

    @mock.patch('asyncio.base_events.logger')
    def test_tb_logger_result_retrieved(self, m_log):
        fut = self._new_future(loop=self.loop)
        fut.set_result(42)
        fut.result()
        del fut
        self.assertFalse(m_log.error.called)

    @mock.patch('asyncio.base_events.logger')
    def test_tb_logger_exception_unretrieved(self, m_log):
        fut = self._new_future(loop=self.loop)
        fut.set_exception(RuntimeError('boom'))
        del fut
        test_utils.run_briefly(self.loop)
        support.gc_collect()
        self.assertTrue(m_log.error.called)

    @mock.patch('asyncio.base_events.logger')
    def test_tb_logger_exception_retrieved(self, m_log):
        fut = self._new_future(loop=self.loop)
        fut.set_exception(RuntimeError('boom'))
        fut.exception()
        del fut
        self.assertFalse(m_log.error.called)

    @mock.patch('asyncio.base_events.logger')
    def test_tb_logger_exception_result_retrieved(self, m_log):
        fut = self._new_future(loop=self.loop)
        fut.set_exception(RuntimeError('boom'))
        self.assertRaises(RuntimeError, fut.result)
        del fut
        self.assertFalse(m_log.error.called)

    def test_wrap_future(self):

        def run(arg):
            return (arg, threading.get_ident())
        ex = concurrent.futures.ThreadPoolExecutor(1)
        f1 = ex.submit(run, 'oi')
        f2 = asyncio.wrap_future(f1, loop=self.loop)
        res, ident = self.loop.run_until_complete(f2)
        self.assertTrue(asyncio.isfuture(f2))
        self.assertEqual(res, 'oi')
        self.assertNotEqual(ident, threading.get_ident())
        ex.shutdown(wait=True)

    def test_wrap_future_future(self):
        f1 = self._new_future(loop=self.loop)
        f2 = asyncio.wrap_future(f1)
        self.assertIs(f1, f2)

    def test_wrap_future_without_loop(self):
        def run(arg):
            return (arg, threading.get_ident())
        ex = concurrent.futures.ThreadPoolExecutor(1)
        f1 = ex.submit(run, 'oi')
        with self.assertRaisesRegex(RuntimeError, 'no current event loop'):
            asyncio.wrap_future(f1)
        ex.shutdown(wait=True)

    def test_wrap_future_use_running_loop(self):
        def run(arg):
            return (arg, threading.get_ident())
        ex = concurrent.futures.ThreadPoolExecutor(1)
        f1 = ex.submit(run, 'oi')
        async def test():
            return asyncio.wrap_future(f1)
        f2 = self.loop.run_until_complete(test())
        self.assertIs(self.loop, f2._loop)
        ex.shutdown(wait=True)

    def test_wrap_future_use_global_loop(self):
        
        asyncio.set_event_loop(self.loop)
        self.addCleanup(asyncio.set_event_loop, None)
        def run(arg):
            return (arg, threading.get_ident())
        ex = concurrent.futures.ThreadPoolExecutor(1)
        f1 = ex.submit(run, 'oi')
        f2 = asyncio.wrap_future(f1)
        self.assertIs(self.loop, f2._loop)
        ex.shutdown(wait=True)

    def test_wrap_future_cancel(self):
        f1 = concurrent.futures.Future()
        f2 = asyncio.wrap_future(f1, loop=self.loop)
        f2.cancel()
        test_utils.run_briefly(self.loop)
        self.assertTrue(f1.cancelled())
        self.assertTrue(f2.cancelled())

    def test_wrap_future_cancel2(self):
        f1 = concurrent.futures.Future()
        f2 = asyncio.wrap_future(f1, loop=self.loop)
        f1.set_result(42)
        f2.cancel()
        test_utils.run_briefly(self.loop)
        self.assertFalse(f1.cancelled())
        self.assertEqual(f1.result(), 42)
        self.assertTrue(f2.cancelled())

    def test_future_source_traceback(self):
        self.loop.set_debug(True)

        future = self._new_future(loop=self.loop)
        lineno = sys._getframe().f_lineno - 1
        self.assertIsInstance(future._source_traceback, list)
        self.assertEqual(future._source_traceback[-2][:3],
                         (__file__,
                          lineno,
                          'test_future_source_traceback'))

    @mock.patch('asyncio.base_events.logger')
    def check_future_exception_never_retrieved(self, debug, m_log):
        self.loop.set_debug(debug)

        def memory_error():
            try:
                raise MemoryError()
            except BaseException as exc:
                return exc
        exc = memory_error()

        future = self._new_future(loop=self.loop)
        future.set_exception(exc)
        future = None
        test_utils.run_briefly(self.loop)
        support.gc_collect()

        regex = f'^{self.cls.__name__} exception was never retrieved\n'
        exc_info = (type(exc), exc, exc.__traceback__)
        m_log.error.assert_called_once_with(mock.ANY, exc_info=exc_info)

        message = m_log.error.call_args[0][0]
        self.assertRegex(message, re.compile(regex, re.DOTALL))

    def test_future_exception_never_retrieved(self):
        self.check_future_exception_never_retrieved(False)

    def test_future_exception_never_retrieved_debug(self):
        self.check_future_exception_never_retrieved(True)

    def test_set_result_unless_cancelled(self):
        fut = self._new_future(loop=self.loop)
        fut.cancel()
        futures._set_result_unless_cancelled(fut, 2)
        self.assertTrue(fut.cancelled())

    def test_future_stop_iteration_args(self):
        fut = self._new_future(loop=self.loop)
        fut.set_result((1, 2))
        fi = fut.__iter__()
        result = None
        try:
            fi.send(None)
        except StopIteration as ex:
            result = ex.args[0]
        else:
            self.fail('StopIteration was expected')
        self.assertEqual(result, (1, 2))

    def test_future_iter_throw(self):
        fut = self._new_future(loop=self.loop)
        fi = iter(fut)
        with self.assertWarns(DeprecationWarning):
            self.assertRaises(Exception, fi.throw, Exception, Exception("zebra"), None)
        with warnings.catch_warnings():
            warnings.filterwarnings("ignore", category=DeprecationWarning)
            self.assertRaises(TypeError, fi.throw,
                            Exception, Exception("elephant"), 32)
            self.assertRaises(TypeError, fi.throw,
                            Exception("elephant"), Exception("elephant"))
            
            self.assertRaises(ValueError, fi.throw, ValueError, None, None)
        self.assertRaises(TypeError, fi.throw, list)

    def test_future_del_collect(self):
        class Evil:
            def __del__(self):
                gc.collect()

        for i in range(100):
            fut = self._new_future(loop=self.loop)
            fut.set_result(Evil())


@unittest.skipUnless(hasattr(futures, '_CFuture'),
                     'requires the C _asyncio module')
class CFutureTests(BaseFutureTests, test_utils.TestCase):
    try:
        cls = futures._CFuture
    except AttributeError:
        cls = None

    def test_future_del_segfault(self):
        fut = self._new_future(loop=self.loop)
        with self.assertRaises(AttributeError):
            del fut._asyncio_future_blocking
        with self.assertRaises(AttributeError):
            del fut._log_traceback


@unittest.skipUnless(hasattr(futures, '_CFuture'),
                     'requires the C _asyncio module')
class CSubFutureTests(BaseFutureTests, test_utils.TestCase):
    try:
        class CSubFuture(futures._CFuture):
            pass

        cls = CSubFuture
    except AttributeError:
        cls = None


class PyFutureTests(BaseFutureTests, test_utils.TestCase):
    cls = futures._PyFuture


class BaseFutureDoneCallbackTests():

    def setUp(self):
        super().setUp()
        self.loop = self.new_test_loop()

    def run_briefly(self):
        test_utils.run_briefly(self.loop)

    def _make_callback(self, bag, thing):
        
        def bag_appender(future):
            bag.append(thing)
        return bag_appender

    def _new_future(self):
        raise NotImplementedError

    def test_callbacks_remove_first_callback(self):
        bag = []
        f = self._new_future()

        cb1 = self._make_callback(bag, 42)
        cb2 = self._make_callback(bag, 17)
        cb3 = self._make_callback(bag, 100)

        f.add_done_callback(cb1)
        f.add_done_callback(cb2)
        f.add_done_callback(cb3)

        f.remove_done_callback(cb1)
        f.remove_done_callback(cb1)

        self.assertEqual(bag, [])
        f.set_result('foo')

        self.run_briefly()

        self.assertEqual(bag, [17, 100])
        self.assertEqual(f.result(), 'foo')

    def test_callbacks_remove_first_and_second_callback(self):
        bag = []
        f = self._new_future()

        cb1 = self._make_callback(bag, 42)
        cb2 = self._make_callback(bag, 17)
        cb3 = self._make_callback(bag, 100)

        f.add_done_callback(cb1)
        f.add_done_callback(cb2)
        f.add_done_callback(cb3)

        f.remove_done_callback(cb1)
        f.remove_done_callback(cb2)
        f.remove_done_callback(cb1)

        self.assertEqual(bag, [])
        f.set_result('foo')

        self.run_briefly()

        self.assertEqual(bag, [100])
        self.assertEqual(f.result(), 'foo')

    def test_callbacks_remove_third_callback(self):
        bag = []
        f = self._new_future()

        cb1 = self._make_callback(bag, 42)
        cb2 = self._make_callback(bag, 17)
        cb3 = self._make_callback(bag, 100)

        f.add_done_callback(cb1)
        f.add_done_callback(cb2)
        f.add_done_callback(cb3)

        f.remove_done_callback(cb3)
        f.remove_done_callback(cb3)

        self.assertEqual(bag, [])
        f.set_result('foo')

        self.run_briefly()

        self.assertEqual(bag, [42, 17])
        self.assertEqual(f.result(), 'foo')

    def test_callbacks_invoked_on_set_result(self):
        bag = []
        f = self._new_future()
        f.add_done_callback(self._make_callback(bag, 42))
        f.add_done_callback(self._make_callback(bag, 17))

        self.assertEqual(bag, [])
        f.set_result('foo')

        self.run_briefly()

        self.assertEqual(bag, [42, 17])
        self.assertEqual(f.result(), 'foo')

    def test_callbacks_invoked_on_set_exception(self):
        bag = []
        f = self._new_future()
        f.add_done_callback(self._make_callback(bag, 100))

        self.assertEqual(bag, [])
        exc = RuntimeError()
        f.set_exception(exc)

        self.run_briefly()

        self.assertEqual(bag, [100])
        self.assertEqual(f.exception(), exc)

    def test_remove_done_callback(self):
        bag = []
        f = self._new_future()
        cb1 = self._make_callback(bag, 1)
        cb2 = self._make_callback(bag, 2)
        cb3 = self._make_callback(bag, 3)

        
        f.add_done_callback(cb1)
        f.add_done_callback(cb2)

        
        self.assertEqual(f.remove_done_callback(cb2), 1)

        
        self.assertEqual(f.remove_done_callback(cb3), 0)

        
        f.add_done_callback(cb2)
        for i in range(5):
            f.add_done_callback(cb1)

        
        self.assertEqual(f.remove_done_callback(cb1), 6)

        self.assertEqual(bag, [])
        f.set_result('foo')

        self.run_briefly()

        self.assertEqual(bag, [2])
        self.assertEqual(f.result(), 'foo')

    def test_remove_done_callbacks_list_mutation(self):
        

        fut = self._new_future()
        fut.add_done_callback(str)

        for _ in range(63):
            fut.add_done_callback(id)

        class evil:
            def __eq__(self, other):
                fut.remove_done_callback(id)
                return False

        fut.remove_done_callback(evil())

    def test_remove_done_callbacks_list_clear(self):
        

        fut = self._new_future()
        fut.add_done_callback(str)

        for _ in range(63):
            fut.add_done_callback(id)

        class evil:
            def __eq__(self, other):
                fut.remove_done_callback(other)

        fut.remove_done_callback(evil())

    def test_schedule_callbacks_list_mutation_1(self):
        

        def mut(f):
            f.remove_done_callback(str)

        fut = self._new_future()
        fut.add_done_callback(mut)
        fut.add_done_callback(str)
        fut.add_done_callback(str)
        fut.set_result(1)
        test_utils.run_briefly(self.loop)

    def test_schedule_callbacks_list_mutation_2(self):
        

        fut = self._new_future()
        fut.add_done_callback(str)

        for _ in range(63):
            fut.add_done_callback(id)

        max_extra_cbs = 100
        extra_cbs = 0

        class evil:
            def __eq__(self, other):
                nonlocal extra_cbs
                extra_cbs += 1
                if extra_cbs < max_extra_cbs:
                    fut.add_done_callback(id)
                return False

        fut.remove_done_callback(evil())


@unittest.skipUnless(hasattr(futures, '_CFuture'),
                     'requires the C _asyncio module')
class CFutureDoneCallbackTests(BaseFutureDoneCallbackTests,
                               test_utils.TestCase):

    def _new_future(self):
        return futures._CFuture(loop=self.loop)


@unittest.skipUnless(hasattr(futures, '_CFuture'),
                     'requires the C _asyncio module')
class CSubFutureDoneCallbackTests(BaseFutureDoneCallbackTests,
                                  test_utils.TestCase):

    def _new_future(self):
        class CSubFuture(futures._CFuture):
            pass
        return CSubFuture(loop=self.loop)


class PyFutureDoneCallbackTests(BaseFutureDoneCallbackTests,
                                test_utils.TestCase):

    def _new_future(self):
        return futures._PyFuture(loop=self.loop)


class BaseFutureInheritanceTests:

    def _get_future_cls(self):
        raise NotImplementedError

    def setUp(self):
        super().setUp()
        self.loop = self.new_test_loop()
        self.addCleanup(self.loop.close)

    def test_inherit_without_calling_super_init(self):
        
        cls = self._get_future_cls()

        class MyFut(cls):
            def __init__(self, *args, **kwargs):
                
                pass

        fut = MyFut(loop=self.loop)
        with self.assertRaisesRegex(
            RuntimeError,
            "Future object is not initialized."
        ):
            fut.get_loop()


class PyFutureInheritanceTests(BaseFutureInheritanceTests,
                               test_utils.TestCase):
    def _get_future_cls(self):
        return futures._PyFuture


@unittest.skipUnless(hasattr(futures, '_CFuture'),
                     'requires the C _asyncio module')
class CFutureInheritanceTests(BaseFutureInheritanceTests,
                              test_utils.TestCase):
    def _get_future_cls(self):
        return futures._CFuture


if __name__ == '__main__':
    unittest.main()