profile
viewpoint

Bttstrp/bootstrap-switch 5115

Turn checkboxes and radio buttons in toggle switches.

6si/shipwright 111

Shipwright | The right way to build, tag and ship Docker containers.

binarymatt/redshift_sqlalchemy 50

Amazon Redshift SQLAlchemy Dialect

denji/cpulimit 11

CPU usage limiter for Linux, Solaris, *BSD, macOS

bcoe/imaplib2 9

Fork of Piers Lauder's imaplib2 library for Python.

chrissorchard/malucrawl 5

GDP 23: Trending Terms Malware Crawler

danpalmer/mondo-bills 2

A service to monitor subscriptions and bills coming out of your Mondo account automatically.

issue commentsamuelcolvin/pydantic

Required optional field has a default value of None after v1.7.0

@PrettyWood It's 11PM where I live, so please go ahead :)

leovp

comment created time in 13 minutes

Pull request review commenttwisted/twisted

Make twisted.mail.pop3client a private module

-# -*- test-case-name: twisted.mail.test.test_pop3client -*--# Copyright (c) 2001-2004 Divmod Inc.-# Copyright (c) Twisted Matrix Laboratories.-# See LICENSE for details.- """-A POP3 client protocol implementation.+Deprecated POP3 client protocol implementation.  Don't use this module directly.  Use twisted.mail.pop3 instead.--@author: Jp Calderone """+import warnings -import re-from hashlib import md5-from typing import List -from twisted.python import log-from twisted.internet import defer-from twisted.protocols import basic-from twisted.protocols import policies-from twisted.internet import error-from twisted.internet import interfaces-from twisted.mail._except import (-    InsecureAuthenticationDisallowed,-    TLSError,-    TLSNotSupportedError,-    ServerErrorResponse,-    LineTooLong,+from twisted.mail._pop3client import (+    OK,+    ERR,+    POP3Client, ) -OK = b"+OK"-ERR = b"-ERR"---class _ListSetter:-    """-    A utility class to construct a list from a multi-line response accounting-    for deleted messages.--    POP3 responses sometimes occur in the form of a list of lines containing-    two pieces of data, a message index and a value of some sort.  When a-    message is deleted, it is omitted from these responses.  The L{setitem}-    method of this class is meant to be called with these two values.  In the-    cases where indices are skipped, it takes care of padding out the missing-    values with L{None}.--    @ivar L: See L{__init__}-    """--    def __init__(self, L):-        """-        @type L: L{list} of L{object}-        @param L: The list being constructed.  An empty list should be-            passed in.-        """-        self.L = L--    def setitem(self, itemAndValue):-        """-        Add the value at the specified position, padding out missing entries.--        @type itemAndValue: C{tuple}-        @param itemAndValue: A tuple of (item, value).  The I{item} is the 0-based-        index in the list at which the value should be placed.  The value is-        is an L{object} to put in the list.-        """-        (item, value) = itemAndValue-        diff = item - len(self.L) + 1-        if diff > 0:-            self.L.extend([None] * diff)-        self.L[item] = value---def _statXform(line):-    """-    Parse the response to a STAT command.--    @type line: L{bytes}-    @param line: The response from the server to a STAT command minus the-        status indicator.--    @rtype: 2-L{tuple} of (0) L{int}, (1) L{int}-    @return: The number of messages in the mailbox and the size of the mailbox.-    """-    numMsgs, totalSize = line.split(None, 1)-    return int(numMsgs), int(totalSize)---def _listXform(line):-    """-    Parse a line of the response to a LIST command.--    The line from the LIST response consists of a 1-based message number-    followed by a size.--    @type line: L{bytes}-    @param line: A non-initial line from the multi-line response to a LIST-        command.--    @rtype: 2-L{tuple} of (0) L{int}, (1) L{int}-    @return: The 0-based index of the message and the size of the message.-    """-    index, size = line.split(None, 1)-    return int(index) - 1, int(size)---def _uidXform(line):-    """-    Parse a line of the response to a UIDL command.--    The line from the UIDL response consists of a 1-based message number-    followed by a unique id.--    @type line: L{bytes}-    @param line: A non-initial line from the multi-line response to a UIDL-        command.--    @rtype: 2-L{tuple} of (0) L{int}, (1) L{bytes}-    @return: The 0-based index of the message and the unique identifier-        for the message.-    """-    index, uid = line.split(None, 1)-    return int(index) - 1, uid---def _codeStatusSplit(line):-    """-    Parse the first line of a multi-line server response.--    @type line: L{bytes}-    @param line: The first line of a multi-line server response.--    @rtype: 2-tuple of (0) L{bytes}, (1) L{bytes}-    @return: The status indicator and the rest of the server response.-    """-    parts = line.split(b" ", 1)-    if len(parts) == 1:-        return parts[0], b""-    return parts---def _dotUnquoter(line):-    """-    Remove a byte-stuffed termination character at the beginning of a line if-    present.--    When the termination character (C{'.'}) appears at the beginning of a line,-    the server byte-stuffs it by adding another termination character to-    avoid confusion with the terminating sequence (C{'.\\r\\n'}).--    @type line: L{bytes}-    @param line: A received line.--    @rtype: L{bytes}-    @return: The line without the byte-stuffed termination character at the-        beginning if it was present. Otherwise, the line unchanged.-    """-    if line.startswith(b".."):-        return line[1:]-    return line---class POP3Client(basic.LineOnlyReceiver, policies.TimeoutMixin):-    """-    A POP3 client protocol.--    Instances of this class provide a convenient, efficient API for-    retrieving and deleting messages from a POP3 server.--    This API provides a pipelining interface but POP3 pipelining-    on the network is not yet supported.--    @type startedTLS: L{bool}-    @ivar startedTLS: An indication of whether TLS has been negotiated-        successfully.--    @type allowInsecureLogin: L{bool}-    @ivar allowInsecureLogin: An indication of whether plaintext login should-        be allowed when the server offers no authentication challenge and the-        transport does not offer any protection via encryption.--    @type serverChallenge: L{bytes} or L{None}-    @ivar serverChallenge: The challenge received in the server greeting.--    @type timeout: L{int}-    @ivar timeout: The number of seconds to wait on a response from the server-        before timing out a connection.  If the number is <= 0, no timeout-        checking will be performed.--    @type _capCache: L{None} or L{dict} mapping L{bytes}-        to L{list} of L{bytes} and/or L{bytes} to L{None}-    @ivar _capCache: The cached server capabilities.  Capabilities are not-        allowed to change during the session (except when TLS is negotiated),-        so the first response to a capabilities command can be used for-        later lookups.--    @type _challengeMagicRe: L{Pattern <re.Pattern.search>}-    @ivar _challengeMagicRe: A regular expression which matches the-        challenge in the server greeting.--    @type _blockedQueue: L{None} or L{list} of 3-L{tuple}-        of (0) L{Deferred <defer.Deferred>}, (1) callable which results-        in a L{Deferred <defer.Deferred>}, (2) L{tuple}-    @ivar _blockedQueue: A list of blocked commands.  While a command is-        awaiting a response from the server, other commands are blocked.  When-        no command is outstanding, C{_blockedQueue} is set to L{None}.-        Otherwise, it contains a list of information about blocked commands.-        Each list entry provides the following information about a blocked-        command: the deferred that should be called when the response to the-        command is received, the function that sends the command, and the-        arguments to the function.--    @type _waiting: L{Deferred <defer.Deferred>} or-        L{None}-    @ivar _waiting: A deferred which fires when the response to the-        outstanding command is received from the server.--    @type _timedOut: L{bool}-    @ivar _timedOut: An indication of whether the connection was dropped-        because of a timeout.--    @type _greetingError: L{bytes} or L{None}-    @ivar _greetingError: The server greeting minus the status indicator, when-        the connection was dropped because of an error in the server greeting.-        Otherwise, L{None}.--    @type state: L{bytes}-    @ivar state: The state which indicates what type of response is expected-        from the server.  Valid states are: 'WELCOME', 'WAITING', 'SHORT',-        'LONG_INITIAL', 'LONG'.--    @type _xform: L{None} or callable that takes L{bytes}-        and returns L{object}-    @ivar _xform: The transform function which is used to convert each-        line of a multi-line response into usable values for use by the-        consumer function.  If L{None}, each line of the multi-line response-        is sent directly to the consumer function.--    @type _consumer: callable that takes L{object}-    @ivar _consumer: The consumer function which is used to store the-        values derived by the transform function from each line of a-        multi-line response into a list.-    """--    startedTLS = False-    allowInsecureLogin = False-    timeout = 0-    serverChallenge = None--    _capCache = None-    _challengeMagicRe = re.compile(b"(<[^>]+>)")-    _blockedQueue = None-    _waiting = None-    _timedOut = False-    _greetingError = None--    def _blocked(self, f, *a):-        """-        Block a command, if necessary.--        If commands are being blocked, append information about the function-        which sends the command to a list and return a deferred that will be-        chained with the return value of the function when it eventually runs.-        Otherwise, set up for subsequent commands to be blocked and return-        L{None}.--        @type f: callable-        @param f: A function which sends a command.--        @type a: L{tuple}-        @param a: Arguments to the function.--        @rtype: L{None} or L{Deferred <defer.Deferred>}-        @return: L{None} if the command can run immediately.  Otherwise,-            a deferred that will eventually trigger with the return value of-            the function.-        """-        if self._blockedQueue is not None:-            d = defer.Deferred()-            self._blockedQueue.append((d, f, a))-            return d-        self._blockedQueue = []-        return None--    def _unblock(self):-        """-        Send the next blocked command.--        If there are no more commands in the blocked queue, set up for the next-        command to be sent immediately.-        """-        if self._blockedQueue == []:-            self._blockedQueue = None-        elif self._blockedQueue is not None:-            _blockedQueue = self._blockedQueue-            self._blockedQueue = None--            d, f, a = _blockedQueue.pop(0)-            d2 = f(*a)-            d2.chainDeferred(d)-            # f is a function which uses _blocked (otherwise it wouldn't-            # have gotten into the blocked queue), which means it will have-            # re-set _blockedQueue to an empty list, so we can put the rest-            # of the blocked queue back into it now.-            self._blockedQueue.extend(_blockedQueue)--    def sendShort(self, cmd, args):-        """-        Send a POP3 command to which a short response is expected.--        Block all further commands from being sent until the response is-        received.  Transition the state to SHORT.--        @type cmd: L{bytes}-        @param cmd: A POP3 command.--        @type args: L{bytes}-        @param args: The command arguments.--        @rtype: L{Deferred <defer.Deferred>} which successfully fires with-            L{bytes} or fails with L{ServerErrorResponse}-        @return: A deferred which fires when the entire response is received.-            On an OK response, it returns the response from the server minus-            the status indicator.  On an ERR response, it issues a server-            error response failure with the response from the server minus the-            status indicator.-        """-        d = self._blocked(self.sendShort, cmd, args)-        if d is not None:-            return d--        if args:-            self.sendLine(cmd + b" " + args)-        else:-            self.sendLine(cmd)-        self.state = "SHORT"-        self._waiting = defer.Deferred()-        return self._waiting--    def sendLong(self, cmd, args, consumer, xform):-        """-        Send a POP3 command to which a multi-line response is expected.--        Block all further commands from being sent until the entire response is-        received.  Transition the state to LONG_INITIAL.--        @type cmd: L{bytes}-        @param cmd: A POP3 command.--        @type args: L{bytes}-        @param args: The command arguments.--        @type consumer: callable that takes L{object}-        @param consumer: A consumer function which should be used to put-            the values derived by a transform function from each line of the-            multi-line response into a list.--        @type xform: L{None} or callable that takes-            L{bytes} and returns L{object}-        @param xform: A transform function which should be used to transform-            each line of the multi-line response into usable values for use by-            a consumer function.  If L{None}, each line of the multi-line-            response should be sent directly to the consumer function.--        @rtype: L{Deferred <defer.Deferred>} which successfully fires with-            callable that takes L{object} and fails with L{ServerErrorResponse}-        @return: A deferred which fires when the entire response is received.-            On an OK response, it returns the consumer function.  On an ERR-            response, it issues a server error response failure with the-            response from the server minus the status indicator and the-            consumer function.-        """-        d = self._blocked(self.sendLong, cmd, args, consumer, xform)-        if d is not None:-            return d--        if args:-            self.sendLine(cmd + b" " + args)-        else:-            self.sendLine(cmd)-        self.state = "LONG_INITIAL"-        self._xform = xform-        self._consumer = consumer-        self._waiting = defer.Deferred()-        return self._waiting--    # Twisted protocol callback-    def connectionMade(self):-        """-        Wait for a greeting from the server after the connection has been made.--        Start the connection in the WELCOME state.-        """-        if self.timeout > 0:-            self.setTimeout(self.timeout)--        self.state = "WELCOME"-        self._blockedQueue = []--    def timeoutConnection(self):-        """-        Drop the connection when the server does not respond in time.-        """-        self._timedOut = True-        self.transport.loseConnection()--    def connectionLost(self, reason):-        """-        Clean up when the connection has been lost.--        When the loss of connection was initiated by the client due to a-        timeout, the L{_timedOut} flag will be set.  When it was initiated by-        the client due to an error in the server greeting, L{_greetingError}-        will be set to the server response minus the status indicator.--        @type reason: L{Failure <twisted.python.failure.Failure>}-        @param reason: The reason the connection was terminated.-        """-        if self.timeout > 0:-            self.setTimeout(None)--        if self._timedOut:-            reason = error.TimeoutError()-        elif self._greetingError:-            reason = ServerErrorResponse(self._greetingError)--        d = []-        if self._waiting is not None:-            d.append(self._waiting)-            self._waiting = None-        if self._blockedQueue is not None:-            d.extend([deferred for (deferred, f, a) in self._blockedQueue])-            self._blockedQueue = None-        for w in d:-            w.errback(reason)--    def lineReceived(self, line):-        """-        Pass a received line to a state machine function and-        transition to the next state.--        @type line: L{bytes}-        @param line: A received line.-        """-        if self.timeout > 0:-            self.resetTimeout()--        state = self.state-        self.state = None-        state = getattr(self, "state_" + state)(line) or state-        if self.state is None:-            self.state = state--    def lineLengthExceeded(self, buffer):-        """-        Drop the connection when a server response exceeds the maximum line-        length (L{LineOnlyReceiver.MAX_LENGTH}).--        @type buffer: L{bytes}-        @param buffer: A received line which exceeds the maximum line length.-        """-        # XXX - We need to be smarter about this-        if self._waiting is not None:-            waiting, self._waiting = self._waiting, None-            waiting.errback(LineTooLong())-        self.transport.loseConnection()--    # POP3 Client state logic - don't touch this.-    def state_WELCOME(self, line):-        """-        Handle server responses for the WELCOME state in which the server-        greeting is expected.--        WELCOME is the first state.  The server should send one line of text-        with a greeting and possibly an APOP challenge.  Transition the state-        to WAITING.--        @type line: L{bytes}-        @param line: A line received from the server.--        @rtype: L{bytes}-        @return: The next state.-        """-        code, status = _codeStatusSplit(line)-        if code != OK:-            self._greetingError = status-            self.transport.loseConnection()-        else:-            m = self._challengeMagicRe.search(status)--            if m is not None:-                self.serverChallenge = m.group(1)--            self.serverGreeting(status)--        self._unblock()-        return "WAITING"--    def state_WAITING(self, line):-        """-        Log an error for server responses received in the WAITING state during-        which the server is not expected to send anything.--        @type line: L{bytes}-        @param line: A line received from the server.-        """-        log.msg("Illegal line from server: " + repr(line))--    def state_SHORT(self, line):-        """-        Handle server responses for the SHORT state in which the server is-        expected to send a single line response.--        Parse the response and fire the deferred which is waiting on receipt of-        a complete response.  Transition the state back to WAITING.--        @type line: L{bytes}-        @param line: A line received from the server.--        @rtype: L{bytes}-        @return: The next state.-        """-        deferred, self._waiting = self._waiting, None-        self._unblock()-        code, status = _codeStatusSplit(line)-        if code == OK:-            deferred.callback(status)-        else:-            deferred.errback(ServerErrorResponse(status))-        return "WAITING"--    def state_LONG_INITIAL(self, line):-        """-        Handle server responses for the LONG_INITIAL state in which the server-        is expected to send the first line of a multi-line response.--        Parse the response.  On an OK response, transition the state to-        LONG.  On an ERR response, cleanup and transition the state to-        WAITING.--        @type line: L{bytes}-        @param line: A line received from the server.--        @rtype: L{bytes}-        @return: The next state.-        """-        code, status = _codeStatusSplit(line)-        if code == OK:-            return "LONG"-        consumer = self._consumer-        deferred = self._waiting-        self._consumer = self._waiting = self._xform = None-        self._unblock()-        deferred.errback(ServerErrorResponse(status, consumer))-        return "WAITING"--    def state_LONG(self, line):-        """-        Handle server responses for the LONG state in which the server is-        expected to send a non-initial line of a multi-line response.--        On receipt of the last line of the response, clean up, fire the-        deferred which is waiting on receipt of a complete response, and-        transition the state to WAITING. Otherwise, pass the line to the-        transform function, if provided, and then the consumer function.--        @type line: L{bytes}-        @param line: A line received from the server.--        @rtype: L{bytes}-        @return: The next state.-        """-        # This is the state for each line of a long response.-        if line == b".":-            consumer = self._consumer-            deferred = self._waiting-            self._consumer = self._waiting = self._xform = None-            self._unblock()-            deferred.callback(consumer)-            return "WAITING"-        else:-            if self._xform is not None:-                self._consumer(self._xform(line))-            else:-                self._consumer(line)-            return "LONG"--    # Callbacks - override these-    def serverGreeting(self, greeting):-        """-        Handle the server greeting.--        @type greeting: L{bytes}-        @param greeting: The server greeting minus the status indicator.-            For servers implementing APOP authentication, this will contain a-            challenge string.-        """--    # External API - call these (most of 'em anyway)-    def startTLS(self, contextFactory=None):-        """-        Switch to encrypted communication using TLS.--        The first step of switching to encrypted communication is obtaining-        the server's capabilities.  When that is complete, the L{_startTLS}-        callback function continues the switching process.--        @type contextFactory: L{None} or-            L{ClientContextFactory <twisted.internet.ssl.ClientContextFactory>}-        @param contextFactory: The context factory with which to negotiate TLS.-            If not provided, try to create a new one.--        @rtype: L{Deferred <defer.Deferred>} which successfully results in-            L{dict} mapping L{bytes} to L{list} of L{bytes} and/or L{bytes} to-            L{None} or fails with L{TLSError}-        @return: A deferred which fires when the transport has been-            secured according to the given context factory with the server-            capabilities, or which fails with a TLS error if the transport-            cannot be secured.-        """-        tls = interfaces.ITLSTransport(self.transport, None)-        if tls is None:-            return defer.fail(-                TLSError(-                    "POP3Client transport does not implement "-                    "interfaces.ITLSTransport"-                )-            )--        if contextFactory is None:-            contextFactory = self._getContextFactory()--        if contextFactory is None:-            return defer.fail(-                TLSError(-                    "POP3Client requires a TLS context to "-                    "initiate the STLS handshake"-                )-            )--        d = self.capabilities()-        d.addCallback(self._startTLS, contextFactory, tls)-        return d--    def _startTLS(self, caps, contextFactory, tls):-        """-        Continue the process of switching to encrypted communication.--        This callback function runs after the server capabilities are received.--        The next step is sending the server an STLS command to request a-        switch to encrypted communication.  When an OK response is received,-        the L{_startedTLS} callback function completes the switch to encrypted-        communication. Then, the new server capabilities are requested.--        @type caps: L{dict} mapping L{bytes} to L{list} of L{bytes} and/or-            L{bytes} to L{None}-        @param caps: The server capabilities.--        @type contextFactory: L{ClientContextFactory-            <twisted.internet.ssl.ClientContextFactory>}-        @param contextFactory: A context factory with which to negotiate TLS.--        @type tls: L{ITLSTransport <interfaces.ITLSTransport>}-        @param tls: A TCP transport that supports switching to TLS midstream.--        @rtype: L{Deferred <defer.Deferred>} which successfully triggers with-            L{dict} mapping L{bytes} to L{list} of L{bytes} and/or L{bytes} to-            L{None} or fails with L{TLSNotSupportedError}-        @return: A deferred which successfully fires when the response from-            the server to the request to start TLS has been received and the-            new server capabilities have been received or fails when the server-            does not support TLS.-        """-        assert (-            not self.startedTLS-        ), "Client and Server are currently communicating via TLS"--        if b"STLS" not in caps:-            return defer.fail(-                TLSNotSupportedError(-                    "Server does not support secure communication " "via TLS / SSL"-                )-            )--        d = self.sendShort(b"STLS", None)-        d.addCallback(self._startedTLS, contextFactory, tls)-        d.addCallback(lambda _: self.capabilities())-        return d--    def _startedTLS(self, result, context, tls):-        """-        Complete the process of switching to encrypted communication.--        This callback function runs after the response to the STLS command has-        been received.--        The final steps are discarding the cached capabilities and initiating-        TLS negotiation on the transport.--        @type result: L{dict} mapping L{bytes} to L{list} of L{bytes} and/or-            L{bytes} to L{None}-        @param result: The server capabilities.--        @type context: L{ClientContextFactory-            <twisted.internet.ssl.ClientContextFactory>}-        @param context: A context factory with which to negotiate TLS.--        @type tls: L{ITLSTransport <interfaces.ITLSTransport>}-        @param tls: A TCP transport that supports switching to TLS midstream.--        @rtype: L{dict} mapping L{bytes} to L{list} of L{bytes} and/or L{bytes}-            to L{None}-        @return: The server capabilities.-        """-        self.transport = tls-        self.transport.startTLS(context)-        self._capCache = None-        self.startedTLS = True-        return result--    def _getContextFactory(self):-        """-        Get a context factory with which to negotiate TLS.--        @rtype: L{None} or-            L{ClientContextFactory <twisted.internet.ssl.ClientContextFactory>}-        @return: A context factory or L{None} if TLS is not supported on the-            client.-        """-        try:-            from twisted.internet import ssl-        except ImportError:-            return None-        else:-            context = ssl.ClientContextFactory()-            context.method = ssl.SSL.TLSv1_METHOD-            return context--    def login(self, username, password):-        """-        Log in to the server.--        If APOP is available it will be used.  Otherwise, if TLS is-        available, an encrypted session will be started and plaintext-        login will proceed.  Otherwise, if L{allowInsecureLogin} is set,-        insecure plaintext login will proceed.  Otherwise,-        L{InsecureAuthenticationDisallowed} will be raised.--        The first step of logging into the server is obtaining the server's-        capabilities.  When that is complete, the L{_login} callback function-        continues the login process.--        @type username: L{bytes}-        @param username: The username with which to log in.--        @type password: L{bytes}-        @param password: The password with which to log in.--        @rtype: L{Deferred <defer.Deferred>} which successfully fires with-            L{bytes}-        @return: A deferred which fires when the login process is complete.-            On a successful login, it returns the server's response minus the-            status indicator.-        """-        d = self.capabilities()-        d.addCallback(self._login, username, password)-        return d--    def _login(self, caps, username, password):-        """-        Continue the process of logging in to the server.--        This callback function runs after the server capabilities are received.--        If the server provided a challenge in the greeting, proceed with an-        APOP login.  Otherwise, if the server and the transport support-        encrypted communication, try to switch to TLS and then complete-        the login process with the L{_loginTLS} callback function.  Otherwise,-        if insecure authentication is allowed, do a plaintext login.-        Otherwise, fail with an L{InsecureAuthenticationDisallowed} error.--        @type caps: L{dict} mapping L{bytes} to L{list} of L{bytes} and/or-            L{bytes} to L{None}-        @param caps: The server capabilities.--        @type username: L{bytes}-        @param username: The username with which to log in.--        @type password: L{bytes}-        @param password: The password with which to log in.--        @rtype: L{Deferred <defer.Deferred>} which successfully fires with-            L{bytes}-        @return: A deferred which fires when the login process is complete.-            On a successful login, it returns the server's response minus the-            status indicator.-        """-        if self.serverChallenge is not None:-            return self._apop(username, password, self.serverChallenge)--        tryTLS = b"STLS" in caps--        # If our transport supports switching to TLS, we might want to-        # try to switch to TLS.-        tlsableTransport = interfaces.ITLSTransport(self.transport, None) is not None--        # If our transport is not already using TLS, we might want to-        # try to switch to TLS.-        nontlsTransport = interfaces.ISSLTransport(self.transport, None) is None--        if not self.startedTLS and tryTLS and tlsableTransport and nontlsTransport:-            d = self.startTLS()--            d.addCallback(self._loginTLS, username, password)-            return d--        elif self.startedTLS or not nontlsTransport or self.allowInsecureLogin:-            return self._plaintext(username, password)-        else:-            return defer.fail(InsecureAuthenticationDisallowed())--    def _loginTLS(self, res, username, password):-        """-        Do a plaintext login over an encrypted transport.--        This callback function runs after the transport switches to encrypted-        communication.--        @type res: L{dict} mapping L{bytes} to L{list} of L{bytes} and/or-            L{bytes} to L{None}-        @param res: The server capabilities.--        @type username: L{bytes}-        @param username: The username with which to log in.--        @type password: L{bytes}-        @param password: The password with which to log in.--        @rtype: L{Deferred <defer.Deferred>} which successfully fires with-            L{bytes} or fails with L{ServerErrorResponse}-        @return: A deferred which fires when the server accepts the username-            and password or fails when the server rejects either.  On a-            successful login, it returns the server's response minus the-            status indicator.-        """-        return self._plaintext(username, password)--    def _plaintext(self, username, password):-        """-        Perform a plaintext login.--        @type username: L{bytes}-        @param username: The username with which to log in.--        @type password: L{bytes}-        @param password: The password with which to log in.--        @rtype: L{Deferred <defer.Deferred>} which successfully fires with-            L{bytes} or fails with L{ServerErrorResponse}-        @return: A deferred which fires when the server accepts the username-            and password or fails when the server rejects either.  On a-            successful login, it returns the server's response minus the-            status indicator.-        """-        return self.user(username).addCallback(lambda r: self.password(password))--    def _apop(self, username, password, challenge):-        """-        Perform an APOP login.--        @type username: L{bytes}-        @param username: The username with which to log in.--        @type password: L{bytes}-        @param password: The password with which to log in.--        @type challenge: L{bytes}-        @param challenge: A challenge string.--        @rtype: L{Deferred <defer.Deferred>} which successfully fires with-            L{bytes} or fails with L{ServerErrorResponse}-        @return: A deferred which fires when the server response is received.-            On a successful login, it returns the server response minus-            the status indicator.-        """-        digest = md5(challenge + password).hexdigest().encode("ascii")-        return self.apop(username, digest)--    def apop(self, username, digest):-        """-        Send an APOP command to perform authenticated login.--        This should be used in special circumstances only, when it is-        known that the server supports APOP authentication, and APOP-        authentication is absolutely required.  For the common case,-        use L{login} instead.--        @type username: L{bytes}-        @param username: The username with which to log in.--        @type digest: L{bytes}-        @param digest: The challenge response to authenticate with.--        @rtype: L{Deferred <defer.Deferred>} which successfully fires with-            L{bytes} or fails with L{ServerErrorResponse}-        @return: A deferred which fires when the server response is received.-            On an OK response, the deferred succeeds with the server-            response minus the status indicator.  On an ERR response, the-            deferred fails with a server error response failure.-        """-        return self.sendShort(b"APOP", username + b" " + digest)--    def user(self, username):-        """-        Send a USER command to perform the first half of plaintext login.--        Unless this is absolutely required, use the L{login} method instead.--        @type username: L{bytes}-        @param username: The username with which to log in.--        @rtype: L{Deferred <defer.Deferred>} which successfully fires with-            L{bytes} or fails with L{ServerErrorResponse}-        @return: A deferred which fires when the server response is received.-            On an OK response, the deferred succeeds with the server-            response minus the status indicator.  On an ERR response, the-            deferred fails with a server error response failure.-        """-        return self.sendShort(b"USER", username)--    def password(self, password):-        """-        Send a PASS command to perform the second half of plaintext login.--        Unless this is absolutely required, use the L{login} method instead.--        @type password: L{bytes}-        @param password: The plaintext password with which to authenticate.--        @rtype: L{Deferred <defer.Deferred>} which successfully fires with-            L{bytes} or fails with L{ServerErrorResponse}-        @return: A deferred which fires when the server response is received.-            On an OK response, the deferred succeeds with the server-            response minus the status indicator.  On an ERR response, the-            deferred fails with a server error response failure.-        """-        return self.sendShort(b"PASS", password)--    def delete(self, index):-        """-        Send a DELE command to delete a message from the server.--        @type index: L{int}-        @param index: The 0-based index of the message to delete.--        @rtype: L{Deferred <defer.Deferred>} which successfully fires with-            L{bytes} or fails with L{ServerErrorResponse}-        @return: A deferred which fires when the server response is received.-            On an OK response, the deferred succeeds with the server-            response minus the status indicator.  On an ERR response, the-            deferred fails with a server error response failure.-        """-        return self.sendShort(b"DELE", b"%d" % (index + 1,))--    def _consumeOrSetItem(self, cmd, args, consumer, xform):-        """-        Send a command to which a long response is expected and process the-        multi-line response into a list accounting for deleted messages.--        @type cmd: L{bytes}-        @param cmd: A POP3 command to which a long response is expected.--        @type args: L{bytes}-        @param args: The command arguments.--        @type consumer: L{None} or callable that takes-            L{object}-        @param consumer: L{None} or a function that consumes the output from-            the transform function.--        @type xform: L{None}, callable that takes-            L{bytes} and returns 2-L{tuple} of (0) L{int}, (1) L{object},-            or callable that takes L{bytes} and returns L{object}-        @param xform: A function that parses a line from a multi-line response-            and transforms the values into usable form for input to the-            consumer function.  If no consumer function is specified, the-            output must be a message index and corresponding value.  If no-            transform function is specified, the line is used as is.--        @rtype: L{Deferred <defer.Deferred>} which fires with L{list} of-            L{object} or callable that takes L{list} of L{object}-        @return: A deferred which fires when the entire response has been-            received.  When a consumer is not provided, the return value is a-            list of the value for each message or L{None} for deleted messages.-            Otherwise, it returns the consumer itself.-        """-        if consumer is None:-            L = []-            consumer = _ListSetter(L).setitem-            return self.sendLong(cmd, args, consumer, xform).addCallback(lambda r: L)-        return self.sendLong(cmd, args, consumer, xform)--    def _consumeOrAppend(self, cmd, args, consumer, xform):-        """-        Send a command to which a long response is expected and process the-        multi-line response into a list.--        @type cmd: L{bytes}-        @param cmd: A POP3 command which expects a long response.--        @type args: L{bytes}-        @param args: The command arguments.--        @type consumer: L{None} or callable that takes-            L{object}-        @param consumer: L{None} or a function that consumes the output from the-            transform function.--        @type xform: L{None} or callable that takes-            L{bytes} and returns L{object}-        @param xform: A function that transforms a line from a multi-line-            response into usable form for input to the consumer function.  If-            no transform function is specified, the line is used as is.--        @rtype: L{Deferred <defer.Deferred>} which fires with L{list} of-            2-L{tuple} of (0) L{int}, (1) L{object} or callable that-            takes 2-L{tuple} of (0) L{int}, (1) L{object}-        @return: A deferred which fires when the entire response has been-            received.  When a consumer is not provided, the return value is a-            list of the transformed lines.  Otherwise, it returns the consumer-            itself.-        """-        if consumer is None:-            L = []-            consumer = L.append-            return self.sendLong(cmd, args, consumer, xform).addCallback(lambda r: L)-        return self.sendLong(cmd, args, consumer, xform)--    def capabilities(self, useCache=True):-        """-        Send a CAPA command to retrieve the capabilities supported by-        the server.--        Not all servers support this command.  If the server does not-        support this, it is treated as though it returned a successful-        response listing no capabilities.  At some future time, this may be-        changed to instead seek out information about a server's-        capabilities in some other fashion (only if it proves useful to do-        so, and only if there are servers still in use which do not support-        CAPA but which do support POP3 extensions that are useful).--        @type useCache: L{bool}-        @param useCache: A flag that determines whether previously retrieved-            results should be used if available.--        @rtype: L{Deferred <defer.Deferred>} which successfully results in-            L{dict} mapping L{bytes} to L{list} of L{bytes} and/or L{bytes} to-            L{None}-        @return: A deferred which fires with a mapping of capability name to-        parameters.  For example::--            C: CAPA-            S: +OK Capability list follows-            S: TOP-            S: USER-            S: SASL CRAM-MD5 KERBEROS_V4-            S: RESP-CODES-            S: LOGIN-DELAY 900-            S: PIPELINING-            S: EXPIRE 60-            S: UIDL-            S: IMPLEMENTATION Shlemazle-Plotz-v302-            S: .--        will be lead to a result of::--            | {'TOP': None,-            |  'USER': None,-            |  'SASL': ['CRAM-MD5', 'KERBEROS_V4'],-            |  'RESP-CODES': None,-            |  'LOGIN-DELAY': ['900'],-            |  'PIPELINING': None,-            |  'EXPIRE': ['60'],-            |  'UIDL': None,-            |  'IMPLEMENTATION': ['Shlemazle-Plotz-v302']}-        """-        if useCache and self._capCache is not None:-            return defer.succeed(self._capCache)--        cache = {}--        def consume(line):-            tmp = line.split()-            if len(tmp) == 1:-                cache[tmp[0]] = None-            elif len(tmp) > 1:-                cache[tmp[0]] = tmp[1:]--        def capaNotSupported(err):-            err.trap(ServerErrorResponse)-            return None--        def gotCapabilities(result):-            self._capCache = cache-            return cache--        d = self._consumeOrAppend(b"CAPA", None, consume, None)-        d.addErrback(capaNotSupported).addCallback(gotCapabilities)-        return d--    def noop(self):-        """-        Send a NOOP command asking the server to do nothing but respond.--        @rtype: L{Deferred <defer.Deferred>} which successfully fires with-            L{bytes} or fails with L{ServerErrorResponse}-        @return: A deferred which fires when the server response is received.-            On an OK response, the deferred succeeds with the server-            response minus the status indicator.  On an ERR response, the-            deferred fails with a server error response failure.-        """-        return self.sendShort(b"NOOP", None)--    def reset(self):-        """-        Send a RSET command to unmark any messages that have been flagged-        for deletion on the server.--        @rtype: L{Deferred <defer.Deferred>} which successfully fires with-            L{bytes} or fails with L{ServerErrorResponse}-        @return: A deferred which fires when the server response is received.-            On an OK response, the deferred succeeds with the server-            response minus the status indicator.  On an ERR response, the-            deferred fails with a server error response failure.-        """-        return self.sendShort(b"RSET", None)--    def retrieve(self, index, consumer=None, lines=None):-        """-        Send a RETR or TOP command to retrieve all or part of a message from-        the server.--        @type index: L{int}-        @param index: A 0-based message index.--        @type consumer: L{None} or callable that takes-            L{bytes}-        @param consumer: A function which consumes each transformed line from a-            multi-line response as it is received.--        @type lines: L{None} or L{int}-        @param lines: If specified, the number of lines of the message to be-            retrieved.  Otherwise, the entire message is retrieved.--        @rtype: L{Deferred <defer.Deferred>} which fires with L{list} of-            L{bytes}, or callable that takes 2-L{tuple} of (0) L{int},-            (1) L{object}-        @return: A deferred which fires when the entire response has been-            received.  When a consumer is not provided, the return value is a-            list of the transformed lines.  Otherwise, it returns the consumer-            itself.-        """-        idx = b"%d" % (index + 1,)-        if lines is None:-            return self._consumeOrAppend(b"RETR", idx, consumer, _dotUnquoter)--        return self._consumeOrAppend(-            b"TOP", b"%b %d" % (idx, lines), consumer, _dotUnquoter-        )--    def stat(self):-        """-        Send a STAT command to get information about the size of the mailbox.--        @rtype: L{Deferred <defer.Deferred>} which successfully fires with-            a 2-tuple of (0) L{int}, (1) L{int} or fails with-            L{ServerErrorResponse}-        @return: A deferred which fires when the server response is received.-            On an OK response, the deferred succeeds with the number of-            messages in the mailbox and the size of the mailbox in octets.-            On an ERR response, the deferred fails with a server error-            response failure.-        """-        return self.sendShort(b"STAT", None).addCallback(_statXform)--    def listSize(self, consumer=None):-        """-        Send a LIST command to retrieve the sizes of all messages on the-        server.--        @type consumer: L{None} or callable that takes-            2-L{tuple} of (0) L{int}, (1) L{int}-        @param consumer: A function which consumes the 0-based message index-            and message size derived from the server response.--        @rtype: L{Deferred <defer.Deferred>} which fires L{list} of L{int} or-            callable that takes 2-L{tuple} of (0) L{int}, (1) L{int}-        @return: A deferred which fires when the entire response has been-            received.  When a consumer is not provided, the return value is a-            list of message sizes.  Otherwise, it returns the consumer itself.-        """-        return self._consumeOrSetItem(b"LIST", None, consumer, _listXform)--    def listUID(self, consumer=None):-        """-        Send a UIDL command to retrieve the UIDs of all messages on the server.--        @type consumer: L{None} or callable that takes-            2-L{tuple} of (0) L{int}, (1) L{bytes}-        @param consumer: A function which consumes the 0-based message index-            and UID derived from the server response.--        @rtype: L{Deferred <defer.Deferred>} which fires with L{list} of-            L{object} or callable that takes 2-L{tuple} of (0) L{int},-            (1) L{bytes}-        @return: A deferred which fires when the entire response has been-            received.  When a consumer is not provided, the return value is a-            list of message sizes.  Otherwise, it returns the consumer itself.-        """-        return self._consumeOrSetItem(b"UIDL", None, consumer, _uidXform)--    def quit(self):-        """-        Send a QUIT command to disconnect from the server.--        @rtype: L{Deferred <defer.Deferred>} which successfully fires with-            L{bytes} or fails with L{ServerErrorResponse}-        @return: A deferred which fires when the server response is received.-            On an OK response, the deferred succeeds with the server-            response minus the status indicator.  On an ERR response, the-            deferred fails with a server error response failure.-        """-        return self.sendShort(b"QUIT", None)-+warnings.warn(+    "twisted.mail.pop3client was deprecated in Twisted NEXT. Use twisted.mail.pop3 instead.",+    DeprecationWarning,+    stacklevel=2,+) -__all__ = []  # type: List[str]

It seems very unlikely that someone would have from twisted.mail.pop3client import * in their code, but if that line does somehow exist somewhere, keeping __all__ = [] would be better, since it preserves the old situation.

mthuurne

comment created time in 29 minutes

issue commentsamuelcolvin/pydantic

Class attributes starting with underscore do not support assignment

@PrettyWood Yep, I just have to be careful to use .id and not ._id in code. Thank you!

dmfigol

comment created time in 35 minutes

issue commentsamuelcolvin/pydantic

Class attributes starting with underscore do not support assignment

@emremrah Using alias id = Field(5, alias='_id') should work 👍

dmfigol

comment created time in 42 minutes

issue commentsamuelcolvin/pydantic

Required optional field has a default value of None after v1.7.0

Hello @leovp and thanks for reporting :) You're absolutely right! IMO the good fix would be to set default = Ellipsis when required Would you like to make a PR for this? If you want I can do it as well tonight for a v1.7.3. Please tell me. Cheers

leovp

comment created time in 43 minutes

issue openedpytest-dev/pytest-asyncio

Attached to a different loop

So I have been looking around the issues page for errors that are similar. It might have been that I did not understand the error, or I did not implement the test properly.

Well this is my error:

/root/.local/share/virtualenvs/atletico-BHfSxaZo/lib/python3.9/site-packages/httpx/_client.py:1633: in post
    return await self.request(
/root/.local/share/virtualenvs/atletico-BHfSxaZo/lib/python3.9/site-packages/httpx/_client.py:1371: in request
    response = await self.send(
/root/.local/share/virtualenvs/atletico-BHfSxaZo/lib/python3.9/site-packages/httpx/_client.py:1406: in send
    response = await self._send_handling_auth(
/root/.local/share/virtualenvs/atletico-BHfSxaZo/lib/python3.9/site-packages/httpx/_client.py:1444: in _send_handling_auth
    response = await self._send_handling_redirects(
/root/.local/share/virtualenvs/atletico-BHfSxaZo/lib/python3.9/site-packages/httpx/_client.py:1476: in _send_handling_redirects
    response = await self._send_single_request(request, timeout)
/root/.local/share/virtualenvs/atletico-BHfSxaZo/lib/python3.9/site-packages/httpx/_client.py:1502: in _send_single_request
    (status_code, headers, stream, ext,) = await transport.arequest(
/root/.local/share/virtualenvs/atletico-BHfSxaZo/lib/python3.9/site-packages/httpx/_transports/asgi.py:148: in arequest
    await self.app(scope, receive, send)
/root/.local/share/virtualenvs/atletico-BHfSxaZo/lib/python3.9/site-packages/fastapi/applications.py:179: in __call__
    await super().__call__(scope, receive, send)
/root/.local/share/virtualenvs/atletico-BHfSxaZo/lib/python3.9/site-packages/starlette/applications.py:111: in __call__
    await self.middleware_stack(scope, receive, send)
/root/.local/share/virtualenvs/atletico-BHfSxaZo/lib/python3.9/site-packages/starlette/middleware/errors.py:181: in __call__
    raise exc from None
/root/.local/share/virtualenvs/atletico-BHfSxaZo/lib/python3.9/site-packages/starlette/middleware/errors.py:159: in __call__
    await self.app(scope, receive, _send)
/root/.local/share/virtualenvs/atletico-BHfSxaZo/lib/python3.9/site-packages/starlette/middleware/sessions.py:75: in __call__
    await self.app(scope, receive, send_wrapper)
/root/.local/share/virtualenvs/atletico-BHfSxaZo/lib/python3.9/site-packages/starlette/exceptions.py:82: in __call__
    raise exc from None
/root/.local/share/virtualenvs/atletico-BHfSxaZo/lib/python3.9/site-packages/starlette/exceptions.py:71: in __call__
    await self.app(scope, receive, sender)
/root/.local/share/virtualenvs/atletico-BHfSxaZo/lib/python3.9/site-packages/starlette/routing.py:566: in __call__
    await route.handle(scope, receive, send)
/root/.local/share/virtualenvs/atletico-BHfSxaZo/lib/python3.9/site-packages/starlette/routing.py:227: in handle
    await self.app(scope, receive, send)
/root/.local/share/virtualenvs/atletico-BHfSxaZo/lib/python3.9/site-packages/starlette/routing.py:41: in app
    response = await func(request)
/root/.local/share/virtualenvs/atletico-BHfSxaZo/lib/python3.9/site-packages/fastapi/routing.py:182: in app
    raw_response = await run_endpoint_function(
/root/.local/share/virtualenvs/atletico-BHfSxaZo/lib/python3.9/site-packages/fastapi/routing.py:133: in run_endpoint_function
    return await dependant.call(**values)
routes/v1/endpoints/signup.py:32: in register_user
    result = await db.execute(
/root/.local/share/virtualenvs/atletico-BHfSxaZo/lib/python3.9/site-packages/sqlalchemy/ext/asyncio/session.py:135: in execute
    return await greenlet_spawn(
/root/.local/share/virtualenvs/atletico-BHfSxaZo/lib/python3.9/site-packages/sqlalchemy/util/_concurrency_py3k.py:91: in greenlet_spawn
    result = context.throw(*sys.exc_info())
/root/.local/share/virtualenvs/atletico-BHfSxaZo/lib/python3.9/site-packages/sqlalchemy/orm/session.py:1530: in execute
    result = conn._execute_20(statement, params or {}, execution_options)
/root/.local/share/virtualenvs/atletico-BHfSxaZo/lib/python3.9/site-packages/sqlalchemy/engine/base.py:1443: in _execute_20
    return meth(self, args_10style, kwargs_10style, execution_options)
/root/.local/share/virtualenvs/atletico-BHfSxaZo/lib/python3.9/site-packages/sqlalchemy/sql/elements.py:310: in _execute_on_connection
    return connection._execute_clauseelement(
/root/.local/share/virtualenvs/atletico-BHfSxaZo/lib/python3.9/site-packages/sqlalchemy/engine/base.py:1312: in _execute_clauseelement
    ret = self._execute_context(
/root/.local/share/virtualenvs/atletico-BHfSxaZo/lib/python3.9/site-packages/sqlalchemy/engine/base.py:1671: in _execute_context
    self._handle_dbapi_exception(
/root/.local/share/virtualenvs/atletico-BHfSxaZo/lib/python3.9/site-packages/sqlalchemy/engine/base.py:1856: in _handle_dbapi_exception
    util.raise_(exc_info[1], with_traceback=exc_info[2])
/root/.local/share/virtualenvs/atletico-BHfSxaZo/lib/python3.9/site-packages/sqlalchemy/util/compat.py:180: in raise_
    raise exception
/root/.local/share/virtualenvs/atletico-BHfSxaZo/lib/python3.9/site-packages/sqlalchemy/engine/base.py:1628: in _execute_context
    self.dialect.do_execute(
/root/.local/share/virtualenvs/atletico-BHfSxaZo/lib/python3.9/site-packages/sqlalchemy/engine/default.py:663: in do_execute
    cursor.execute(statement, parameters)
/root/.local/share/virtualenvs/atletico-BHfSxaZo/lib/python3.9/site-packages/sqlalchemy/dialects/postgresql/asyncpg.py:350: in execute
    self._handle_exception(error)
/root/.local/share/virtualenvs/atletico-BHfSxaZo/lib/python3.9/site-packages/sqlalchemy/dialects/postgresql/asyncpg.py:290: in _handle_exception
    self._adapt_connection._handle_exception(error)
/root/.local/share/virtualenvs/atletico-BHfSxaZo/lib/python3.9/site-packages/sqlalchemy/dialects/postgresql/asyncpg.py:511: in _handle_exception
    raise error
/root/.local/share/virtualenvs/atletico-BHfSxaZo/lib/python3.9/site-packages/sqlalchemy/dialects/postgresql/asyncpg.py:346: in execute
    self._adapt_connection.await_(
/root/.local/share/virtualenvs/atletico-BHfSxaZo/lib/python3.9/site-packages/sqlalchemy/util/_concurrency_py3k.py:41: in await_only
    return current.driver.switch(awaitable)
/root/.local/share/virtualenvs/atletico-BHfSxaZo/lib/python3.9/site-packages/sqlalchemy/util/_concurrency_py3k.py:86: in greenlet_spawn
    value = await result
/root/.local/share/virtualenvs/atletico-BHfSxaZo/lib/python3.9/site-packages/sqlalchemy/dialects/postgresql/asyncpg.py:312: in _prepare_and_execute
    await self._adapt_connection._start_transaction()
/root/.local/share/virtualenvs/atletico-BHfSxaZo/lib/python3.9/site-packages/sqlalchemy/dialects/postgresql/asyncpg.py:532: in _start_transaction
    self._handle_exception(error)
/root/.local/share/virtualenvs/atletico-BHfSxaZo/lib/python3.9/site-packages/sqlalchemy/dialects/postgresql/asyncpg.py:511: in _handle_exception
    raise error
/root/.local/share/virtualenvs/atletico-BHfSxaZo/lib/python3.9/site-packages/sqlalchemy/dialects/postgresql/asyncpg.py:530: in _start_transaction
    await self._transaction.start()
/root/.local/share/virtualenvs/atletico-BHfSxaZo/lib/python3.9/site-packages/asyncpg/transaction.py:138: in start
    await self._connection.execute(query)
/root/.local/share/virtualenvs/atletico-BHfSxaZo/lib/python3.9/site-packages/asyncpg/connection.py:295: in execute
    return await self._protocol.query(query, timeout)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

>   ???
E   RuntimeError: Task <Task pending name='Task-5' coro=<test_register_user() running at /app/atletico/tests/unit/test_registration.py:18> cb=[_run_until_complete_cb() at /usr/local/lib/python3.9/asyncio/base_events.py:184]> got Future <Future pending cb=[Protocol._on_waiter_completed()]> attached to a different loop

asyncpg/protocol/protocol.pyx:316: RuntimeError

setup.py

import pytest
from fastapi import FastAPI
from bin.setup import setup_app
from httpx import AsyncClient
from utils.config import Settings, get_settings


class SetupClient:

    settings: Settings
    app: FastAPI
    client: AsyncClient

    def __init__(self, app: FastAPI):
        self.settings = get_settings()
        self.app = app
        self.client = AsyncClient(app=app, base_url="http://127.0.0.1")


@pytest.fixture()
async def client_fixture() -> SetupClient:
    client = SetupClient(setup_app())
    return client

test_startup.py

import pytest
from .setup import client_fixture, SetupClient


@pytest.mark.asyncio
async def test_index(client_fixture: SetupClient) -> None:
    async with client_fixture.client as client:
        response = await client.get("/")
        assert response.status_code == 200
        assert response.json() == {"response": "This is the index directory."}

test_registration.py

import pytest
from .setup import client_fixture, SetupClient


@pytest.mark.asyncio
async def test_check_email(client_fixture: SetupClient) -> None:
    async with client_fixture.client as client:
        response = await client.post(
            "/api/v1/registration/check-email", json={"email": "test@test.com"}
        )
        data = response.json()
        assert bool(data["valid_email"])


@pytest.mark.asyncio
async def test_register_user(client_fixture: SetupClient) -> None:
    async with client_fixture.client as client:
        response = await client.post(
            "/api/v1/registration/new-user",
            json={
                "email": "test@test.com",
                "first_name": "steveo",
                "last_name": "west",
                "password": "123456",
                "birth_date": "1987/09/09",
            },
        )
        assert response.status_code == 200
        assert response.json() == {"detail": "The user was successfully created."}

created time in 44 minutes

issue commentsamuelcolvin/pydantic

Class attributes starting with underscore do not support assignment

Hey @emremrah Probably because you want to call super() not super ;)

Ahh you are right @PrettyWood ,:

class A(BaseModel):
    id = 5
    
    def dict(self):
        d = super().dict()
        d['_id'] = d['id']
        del d['id']
        return d

returned {'_id': 5}. So if anyone is interested. I just have to call .dict() method when inserting to MongoDB. But initiating A with a MongoDB document still won't work as we wanted.

dmfigol

comment created time in an hour

issue commentsamuelcolvin/pydantic

Class attributes starting with underscore do not support assignment

Hey @emremrah Probably because you want to call super() not super ;)

dmfigol

comment created time in an hour

issue commentsamuelcolvin/pydantic

Class attributes starting with underscore do not support assignment

I have just tried a workaround like this to issue the data model to MongoDB using .dict() method:

class A(BaseModel):
    _id = 5
    
    def dict(self):
        d = super.dict()
        d['_id'] = d['id']
        del d['id']
        return d

When I call A().dict(), it gives an error: AttributeError: type object 'super' has no attribute 'dict'. But BaseModel has a dict method. I'm probably missing some Python feature. Can someone enlight me why this is not working? Thanks.

dmfigol

comment created time in an hour

Pull request review commentpytest-dev/pytest

Add new option --append-ini

 def _getconftest_pathlist(self, name, path):             values.append(relroot)         return values +    def _get_append_ini_values(self, name: str, ini_type) -> List[str]:+        value = []+        # append_ini is a list of "ini=value" options+        # append all values if multiple values are set for same ini-name,+        # e.g. -a foo=bar1 -a foo=bar2 will append 'bar1 bar2' to foo+        for ini_config in self._append_ini:+            try:+                key, append_ini_value = ini_config.split("=", 1)+            except ValueError:+                raise UsageError(+                    "-a/--append-ini expects option=value style (got: {!r}).".format(+                        ini_config+                    )+                )+            else:+                if key == name:+                    if ini_type in ["pathlist", "args"]:+                        value.append(append_ini_value)+                    elif ini_type == "linelist":+                        value.append("\n{}".format(append_ini_value))

i see, you had to be very to be elaborate, i hope in future we can make shift the configuration loading/overriding more consistent/streamlined

gnikonorov

comment created time in 5 months

Pull request review commentpytest-dev/pytest

Add new option --append-ini

 passed multiple times. The expected format is ``name=value``. For example::     pytest -o console_output_style=classic -o cache_dir=/tmp/mycache +Configuration options of type ``args``, ``linelist``, or ``pathlist`` may be appended to in the command-line by+using ``-a/-append-ini``, which can also be passed multiple times. The expected format is ``name=value``. For example::++   pytest --append-ini addopts="-k should_throw_error" -a addopts=-x

lets use the markers option here, its a practical example of how test invokers/integrators can sort out setups they have no control here

gnikonorov

comment created time in 5 months

Pull request review commentpytest-dev/pytest

Add new option --append-ini

 def _getini(self, name: str) -> Any:         except KeyError:             raise ValueError("unknown configuration value: {!r}".format(name))         override_value = self._get_override_ini_value(name)-        if override_value is None:-            try:-                value = self.inicfg[name]-            except KeyError:+        append_values = self._get_append_ini_values(name, type)++        value = self.inicfg.get(name, None)+        if override_value is None and not append_values:+            if value is None:                 if default is not None:                     return default                 if type is None:                     return ""                 return []         else:-            value = override_value+            if override_value:+                value = override_value+            if append_values:+                if not value:+                    fail(+                        "append_ini option invalid for argument '{}' since it has no value".format(+                            name+                        ),+                        pytrace=False,+                    )+                else:+                    value = (+                        value + append_values+                        if isinstance(value, list)+                        else "{} {}".format(value, " ".join(append_values))

does this join correctly work for line lists? at first glance im under the impression that it would join elements into a single line

gnikonorov

comment created time in 5 months

issue commentsamuelcolvin/pydantic

Required optional field has a default value of None after v1.7.0

https://github.com/samuelcolvin/pydantic/blob/31bc2435d7968fdf8d1f0c5c67f0f851c1bef54e/pydantic/main.py#L789

Alright, I haven't looked really closely, but here's my guess: getattr here can never fallback to a default value of _missing, since ModelField.default is always there and has a value of None unless set explicitly.

leovp

comment created time in 2 hours

delete branch twisted/pydoctor

delete branch : coverage-exclusions

delete time in 2 hours

push eventtwisted/pydoctor

Maarten ter Huurne

commit sha 229ed75fd2ec243a1ba279473abddf3720219a84

Add more coverage exclusions

view details

Maarten ter Huurne

commit sha 62a9deaae63bfc5558a762565f1be71cc7629be6

Move coverage 'source' and 'omit' configuration to rcfile This makes it easier to run with the same configuration outside of tox during development.

view details

Maarten ter Huurne

commit sha 8ff0c6bafbcfa07cc91e2eea4244e0576ec0b4b3

Exclude Sphinx extensions from coverage measurement

view details

Maarten ter Huurne

commit sha 1d74b4a2a2ca46956e356c8a008e9a413f569899

Merge pull request #281 from twisted/coverage-exclusions Tweak coverage exclusions

view details

push time in 2 hours

PR merged twisted/pydoctor

Tweak coverage exclusions

By excluding things we don't intend to cover, lines that should be covered but are not stand out more.

+17 -1

1 comment

2 changed files

mthuurne

pr closed time in 2 hours

PR opened spacepy/dbprocessing

Fix make clean for the autosummary docs

#1 moved the Sphinx source from the sphinx/source directory to docs to play better with GitHub. This also means the autosummary output goes in docs, but the make clean rule wasn't updated to remove old autosummary output from the new location. This PR fixes that.

PR Checklist

  • [X] Pull request has descriptive title
  • [X] Pull request gives overview of changes
  • [X] (N/A) New code has inline comments where necessary
  • [X] (N/A) Any new modules, functions or classes have docstrings consistent with dbprocessing style
  • [X] (N/A) Major new functionality has appropriate Sphinx documentation
  • [X] (N/A) Added an entry to release notes if fixing a major bug or providing a major new feature
  • [X] (N/A) New features and bug fixes should have unit tests
  • [X] Relevant issues are linked in the description (use Closes # if this PR closes the issue, or some other reference, such as See # if it is related in some other way)
+1 -1

0 comment

1 changed file

pr created time in 2 hours

PR opened spacepy/dbprocessing

Move table definitions to separate, common module.

This PR takes the table definitions, which were primarily in CreateDB.py and copied where needed elsewhere, and moves them into a separate module that can be used elsewhere.

For now this does not convert CreateDBsabrs as the database format still different, but it provides the possibility for converging them later.

This PR doesn't reformat/rewrap the definitions, so that the correspondence with the original CreateDB is clearer for now (rewrap can happen in the future.) The one change is that the ix_file_big index definition is moved into the table definition itself rather than glued on after the table is created.

One note (that's in the comments, but worth calling out): the table definition module creates new Column objects every time it's called; reusing objects doesn't work if they're used in separate database, as happens in the unit tests.

This is the first time we have a docstring cross-linking to sqlalchemy, so this also adds the appropriate intersphinx entries to make that work.

PR Checklist

  • [X] Pull request has descriptive title
  • [X] Pull request gives overview of changes
  • [X] New code has inline comments where necessary
  • [X] Any new modules, functions or classes have docstrings consistent with dbprocessing style
  • [X] (N/A) Major new functionality has appropriate Sphinx documentation
  • [X] (N/A) Added an entry to release notes if fixing a major bug or providing a major new feature
  • [X] New features and bug fixes should have unit tests
  • [X] (N/A) Relevant issues are linked in the description (use Closes # if this PR closes the issue, or some other reference, such as See # if it is related in some other way)
+405 -250

0 comment

8 changed files

pr created time in 2 hours

PR opened PyCQA/modernize

[pre-commit.ci] pre-commit autoupdate
+1 -1

0 comment

1 changed file

pr created time in 2 hours

create barnchPyCQA/modernize

branch : pre-commit-ci-update-config

created branch time in 2 hours

push eventpytest-dev/plugincompat

pytestbot

commit sha a76bbaeb1ecea656593d360436adb3cce1166158

Updating index (from heroku)

view details

push time in 3 hours

PR opened Osirium/third-party

Update collectd

As part of https://github.com/Osirium/osirium-main/pull/4569 I wanted to use the postgresql plugin. That led me to make this update to collectd.

+9 -2

0 comment

3 changed files

pr created time in 3 hours

pull request commenttwisted/pydoctor

Tweak coverage exclusions

Codecov Report

Merging #281 (8ff0c6b) into master (13749a4) will increase coverage by 1.12%. The diff coverage is n/a.

Impacted file tree graph

@@            Coverage Diff             @@
##           master     #281      +/-   ##
==========================================
+ Coverage   81.89%   83.02%   +1.12%     
==========================================
  Files          25       23       -2     
  Lines        3812     3658     -154     
  Branches      792      773      -19     
==========================================
- Hits         3122     3037      -85     
+ Misses        476      412      -64     
+ Partials      214      209       -5     
Impacted Files Coverage Δ
pydoctor/templatewriter/pages/functionchild.py 79.16% <0.00%> (-3.29%) :arrow_down:
pydoctor/templatewriter/summary.py 83.08% <0.00%> (-2.45%) :arrow_down:
pydoctor/templatewriter/pages/attributechild.py 88.88% <0.00%> (-2.29%) :arrow_down:
pydoctor/astbuilder.py 87.79% <0.00%> (-1.83%) :arrow_down:
pydoctor/epydoc2stan.py 85.04% <0.00%> (-1.00%) :arrow_down:
pydoctor/templatewriter/pages/__init__.py 71.52% <0.00%> (-0.77%) :arrow_down:
pydoctor/zopeinterface.py 83.82% <0.00%> (-0.24%) :arrow_down:
pydoctor/templatewriter/pages/table.py 100.00% <0.00%> (ø)
pydoctor/sphinx_ext/build_apidocs.py
pydoctor/sphinx_ext/_help_output.py
... and 7 more

Continue to review full report at Codecov.

Legend - Click here to learn more Δ = absolute <relative> (impact), ø = not affected, ? = missing data Powered by Codecov. Last update 13749a4...8ff0c6b. Read the comment docs.

mthuurne

comment created time in 3 hours

PR opened twisted/pydoctor

Tweak coverage exclusions

By excluding things we don't intend to cover, lines that should be covered but are not stand out more.

+17 -1

0 comment

2 changed files

pr created time in 3 hours

create barnchtwisted/pydoctor

branch : coverage-exclusions

created branch time in 4 hours

startedsimukti/sqldb-logger

started time in 4 hours

delete branch twisted/pydoctor

delete branch : annotation-presentation

delete time in 4 hours

push eventtwisted/pydoctor

Maarten ter Huurne

commit sha 3113ff57c6036cb73c1d597ef1130319d31d3af7

Annotate functions that process annotations

view details

Maarten ter Huurne

commit sha 381fa98c2ef8669ab9c4f52f5a26954c2c05e12f

Remove Python 2.7 support from test_inferred_variable_types()

view details

Maarten ter Huurne

commit sha 49e69fd9763c5aa2c062798c9cc48ffcec9785d2

Preserve line number information when inferring types

view details

Maarten ter Huurne

commit sha 0fd0dd5c6d9ccea6837a9bc8d172383921db4aef

Preserve line number information when unstringing annotations

view details

Maarten ter Huurne

commit sha 808d374d3f1bc64f5ca54fd1cb33c0507589196d

Infer PEP 585 style lower case type names Besides being easier on the eyes, these are builtins names that don't need an import, which avoids name resolution problems later.

view details

Maarten ter Huurne

commit sha cac8ca7774fb8b9e33f69b1a238f726385c76593

Use links for names in annotations If a type name is known either because it's inside the code being documented or because it exists in an intersphinx inventory, link to its documentation.

view details

Maarten ter Huurne

commit sha 7dd0ffd3282c2aa64db4f80acc5d8a85b3f4eed4

Rename and document test helper function

view details

Maarten ter Huurne

commit sha eeb1014e8fa5cfbaf00313b7f46a2e1286de2b43

Add calls to resolve_identifier() to existing EpydocLinker tests

view details

Maarten ter Huurne

commit sha 871a1f5763ba13826821bb2c345f7dfc644a47fe

Exclude "raise NotImplementedError" from coverage This is code that should never be called.

view details

Maarten ter Huurne

commit sha 24f5b0025a298e35669872b4d7858fb3089dff46

Add a test case for looking up an internal object by its full name

view details

Maarten ter Huurne

commit sha 13749a47394a2271a22ec9af904704e469e2457a

Merge pull request #278 from twisted/annotation-presentation Annotation presentation

view details

push time in 4 hours

PR merged twisted/pydoctor

Annotation presentation

Until now, annotations were presented in the output as plain text. This PR changes that by processing the AST for the annotation and linking type names to their internal or external documentation.

This addresses one of the two use cases requested in #268.

The line number preservation changes aren't strictly necessary, since we don't actually report errors when presenting annotations, but having line number information for annotations might be useful in the future.

+276 -42

1 comment

6 changed files

mthuurne

pr closed time in 4 hours

push eventtwisted/pydoctor

Maarten ter Huurne

commit sha 7dd0ffd3282c2aa64db4f80acc5d8a85b3f4eed4

Rename and document test helper function

view details

Maarten ter Huurne

commit sha eeb1014e8fa5cfbaf00313b7f46a2e1286de2b43

Add calls to resolve_identifier() to existing EpydocLinker tests

view details

Maarten ter Huurne

commit sha 871a1f5763ba13826821bb2c345f7dfc644a47fe

Exclude "raise NotImplementedError" from coverage This is code that should never be called.

view details

Maarten ter Huurne

commit sha 24f5b0025a298e35669872b4d7858fb3089dff46

Add a test case for looking up an internal object by its full name

view details

push time in 4 hours

more