def test_excepts():
    # These are descriptors, make sure this works correctly.
    assert excepts.__name__ == 'excepts'
    assert (
        'A wrapper around a function to catch exceptions and\n'
        '    dispatch to a handler.\n'
    ) in excepts.__doc__

    def idx(a):
        """idx docstring
        """
        return [1, 2].index(a)

    def handler(e):
        """handler docstring
        """
        assert isinstance(e, ValueError)
        return -1

    excepting = excepts(ValueError, idx, handler)
    assert excepting(1) == 0
    assert excepting(2) == 1
    assert excepting(3) == -1

    assert excepting.__name__ == 'idx_excepting_ValueError'
    assert 'idx docstring' in excepting.__doc__
    assert 'ValueError' in excepting.__doc__
    assert 'handler docstring' in excepting.__doc__

    def getzero(a):
        """getzero docstring
        """
        return a[0]

    excepting = excepts((IndexError, KeyError), getzero)
    assert excepting([]) is None
    assert excepting([1]) == 1
    assert excepting({}) is None
    assert excepting({0: 1}) == 1

    assert excepting.__name__ == 'getzero_excepting_IndexError_or_KeyError'
    assert 'getzero docstring' in excepting.__doc__
    assert 'return_none' in excepting.__doc__
    assert 'Returns None' in excepting.__doc__

    def raise_(a):
        """A function that raises an instance of the exception type given.
        """
        raise a()

    excepting = excepts((ValueError, KeyError), raise_)
    assert excepting(ValueError) is None
    assert excepting(KeyError) is None
    assert raises(TypeError, lambda: excepting(TypeError))
    assert raises(NotImplementedError, lambda: excepting(NotImplementedError))

    excepting = excepts(object(), object(), object())
    assert excepting.__name__ == 'excepting'
    assert excepting.__doc__ == excepts.__doc__
Esempio n. 2
0
def test_excepts():
    # These are descriptors, make sure this works correctly.
    assert excepts.__name__ == 'excepts'
    assert excepts.__doc__.startswith(
        'A wrapper around a function to catch exceptions and\n'
        '    dispatch to a handler.\n'
    )

    def idx(a):
        """idx docstring
        """
        return [1, 2].index(a)

    def handler(e):
        """handler docstring
        """
        assert isinstance(e, ValueError)
        return -1

    excepting = excepts(ValueError, idx, handler)
    assert excepting(1) == 0
    assert excepting(2) == 1
    assert excepting(3) == -1

    assert excepting.__name__ == 'idx_excepting_ValueError'
    assert 'idx docstring' in excepting.__doc__
    assert 'ValueError' in excepting.__doc__
    assert 'handler docstring' in excepting.__doc__

    def getzero(a):
        """getzero docstring
        """
        return a[0]

    excepting = excepts((IndexError, KeyError), getzero)
    assert excepting([]) is None
    assert excepting([1]) == 1
    assert excepting({}) is None
    assert excepting({0: 1}) == 1

    assert excepting.__name__ == 'getzero_excepting_IndexError_or_KeyError'
    assert 'getzero docstring' in excepting.__doc__
    assert 'return_none' in excepting.__doc__
    assert 'Returns None' in excepting.__doc__

    def raise_(a):
        """A function that raises an instance of the exception type given.
        """
        raise a()

    excepting = excepts((ValueError, KeyError), raise_)
    assert excepting(ValueError) is None
    assert excepting(KeyError) is None
    assert raises(TypeError, lambda: excepting(TypeError))
    assert raises(NotImplementedError, lambda: excepting(NotImplementedError))

    excepting = excepts(object(), object(), object())
    assert excepting.__name__ == 'excepting'
    assert excepting.__doc__ == excepts.__doc__
Esempio n. 3
0
def upload_envelopes(envelope_dir: str, resource_bucket: str,
                     envelope_prefix: str, parties: Store[str, Party]) -> None:
    client = boto3.client('s3')

    for envelope in listdir(envelope_dir):
        envelope_file = path.join(envelope_dir, envelope)

        if path.isfile(envelope_file) and _is_image(envelope_file):
            maybe_party = excepts(ClientError, parties.get)(path.splitext(
                path.basename(envelope_file))[0])

            envelope_key = envelope_prefix + (
                '/' if not envelope_prefix.endswith('/') else '') + envelope

            client.upload_file(envelope_file, resource_bucket, envelope_key)

            option.fmap(lambda party: client.put_object_tagging(
                Bucket=resource_bucket,
                Key=envelope_key,
                Tagging={
                    'TagSet': [{
                        'Key':
                        'party',
                        'Value':
                        ''.join(
                            filter(lambda c: c in string.ascii_letters, party.
                                   title))[:256]
                    }]
                }))(maybe_party)
Esempio n. 4
0
 def __handler(exc, handler):
     return lambda f: excepts(exc, f, handler)
Esempio n. 5
0
def get_guest(guest_id: str,
              party: Party) -> Optional[Guest]:
    return excepts(StopIteration, first)(
        guest for guest in party.guests
        if guest.id == guest_id
    )
Esempio n. 6
0
    'rsvp_stage': optional(RsvpStageField, 'rsvpStage', missing = NotInvited.shows)
})
PartyCodec: JsonCodec[Party] = codec(PartySchema(strict=True))


Passenger, PassengerSchema = build('Passenger', {
    'first_name': required(String, 'firstName'),
    'guest_id'  : required(String, 'guestId'  )
})
PassengerCodec: JsonCodec[Passenger] = codec(PassengerSchema(strict=True))


Phone, PhoneSchema = build('Phone', {
    'area'    : required(Integer, validate = Range(200, 999)),
    'exchange': required(Integer, validate = Range(200, 999)),
    'line'    : required(String , validate = lambda s: 0 <= excepts(ValueError, int, -1)(s) <= 9999)
})
PhoneCodec: JsonCodec[Phone] = codec(PhoneSchema(strict=True))


Contact, ContactSchema = build('Contact', {
    'phone': required(PhoneSchema),
    'email': required(EmailAddressSchema)
})
ContactCodec: JsonCodec[Contact] = codec(ContactSchema(strict=True))


PassengerGroup, PassengerGroupSchema = build('PassengerGroup', {
    'id'          : required(String                    ),
    'passengers'  : required(PassengerSchema, many=True),
    'arrival'     : required(DateTime                  ),
Esempio n. 7
0
        self.zipfile = zipfile
        self.stream = None

    def __enter__(self):
        self.stream = self.zipfile.open(self.filename)
        ustream = TextIOWrapper(self.stream, 'utf-8')
        return csv.reader(ustream, quotechar='"')

    def __exit__(self, *exc_info):
        self.stream.close()


open_as_csv = curry(OpenFileInZipAsCSV, gtf)
by_nth = curry(lambda nth, uid, obj: obj[nth] == str(uid))
list_first = curry(lambda it: [first(it)])
list_first_or_empty = excepts(StopIteration, list_first, lambda _: [])
filter_by_nth = curry(
    lambda nth, uid, stream: filter(by_nth(nth, uid), stream))
filter_by_uid = filter_by_nth(0)


@curry
def swap(i, j, arr):
    arr[i], arr[j] = arr[j], arr[i]
    return arr


def list_file(name):
    with open_as_csv(name) as stream:
        return list(stream)