Esempio n. 1
0
 def calculate_done(self):
     for item in self:
         if item.product_id.categ_id.parent_id.name == 'Producto Terminado':
             list_serial_pt = Enumerable(
                 self.workorder_ids[0].summary_out_serial_ids).where(
                     lambda x: x.product_id.id == item.product_id.id).count(
                     )
             for move in item.move_raw_ids.filtered(
                     lambda x: not x.needs_lots):
                 move.active_move_line_ids.sudo().unlink()
                 component_ids = Enumerable(item.bom_id.bom_line_ids).where(
                     lambda x: x.product_id.id == move.product_id.id)
                 self.env['stock.move.line'].create({
                     'product_id':
                     move.product_id.id,
                     'production_id':
                     item.id,
                     'qty_done':
                     list_serial_pt *
                     component_ids.first_or_default().product_qty,
                     'location_id':
                     item.location_src_id.id,
                     'product_uom_id':
                     move.product_id.uom_id.id,
                     'location_dest_id':
                     self.env['stock.location'].search(
                         [('usage', '=', 'production')], limit=1).id,
                     'move_id':
                     move.id,
                     'lot_produced_id':
                     item.finished_move_line_ids.filtered(
                         lambda x: x.product_id.id == item.product_id.id).
                     lot_id.id
                 })
Esempio n. 2
0
class TestFunctions(TestCase):
    def setUp(self):
        self.empty = Enumerable(_empty)
        self.simple = Enumerable(_simple)
        self.complex = Enumerable(_complex)

    def test_to_list(self):
        self.assertListEqual(
            self.empty.to_list(),
            _empty,
            u"Empty to_list not correct")
        self.assertListEqual(
            self.simple.to_list(),
            _simple,
            u"Simple to_list not correct")
        self.assertListEqual(
            self.complex.to_list(),
            _complex,
            u"Complex to_list not correct")

    def test_sum(self):
        self.assertEqual(
            self.empty.sum(),
            0,
            u"Sum of empty enumerable should be 0")
        self.assertEqual(
            self.simple.sum(),
            6,
            u"Sum of simple enumerable should be 6")
        self.assertEqual(
            self.complex.sum(lambda x: x['value']),
            6,
            u"Sum of complex enumerable should be 6")

    def test_count(self):
        self.assertEqual(
            self.empty.count(),
            0,
            u"Empty enumerable has 0 elements")
        self.assertEqual(
            self.simple.count(),
            3,
            u"Simple enumerable has 3 elements")
        self.assertEqual(
            self.complex.count(),
            3,
            u"Complex enumerable has 3 elements")

    def test_select(self):
        self.assertEqual(
            self.empty.select(lambda x: x['value']).count(),
            0,
            u"Empty enumerable should still have 0 elements")

        simple_select = self.simple.select(lambda x: {'value': x})
        self.assertDictEqual(
            simple_select.first(),
            {'value': 1},
            u"Transformed simple enumerable element is dictionary")
        self.assertEqual(
            simple_select.count(),
            3,
            u"Transformed simple enumerable has 3 elements")

        complex_select = self.complex.select(lambda x: x['value'])
        self.assertEqual(
            complex_select.count(),
            3, u"Transformed complex enumerable has 3 elements")
        self.assertIsInstance(
            complex_select.first(),
            int,
            u"Transformed complex enumerable element is integer"
        )

    def test_max_min(self):
        self.assertRaises(NoElementsError, self.empty.min)
        self.assertEqual(
            self.simple.min(),
            1,
            u"Minimum value of simple enumerable is 1")
        self.assertEqual(
            self.complex.min(lambda x: x['value']),
            1,
            u"Min value of complex enumerable is 1"
        )

        self.assertRaises(NoElementsError, self.empty.max)
        self.assertEqual(
            self.simple.max(),
            3,
            u"Max value of simple enumerable is 3")
        self.assertEqual(
            self.complex.max(lambda x: x['value']),
            3,
            u"Max value of complex enumerable is 3")

    def test_avg(self):
        avg = float(2)
        self.assertRaises(NoElementsError, self.empty.avg)
        self.assertEqual(
            self.simple.avg(),
            avg,
            u"Avg value of simple enumerable is {0:.5f}".format(avg))
        self.assertEqual(
            self.complex.avg(lambda x: x['value']),
            avg,
            u"Avg value of complex enumerable is {0:.5f}".format(avg))

    def test_first_last(self):
        self.assertRaises(NoElementsError, self.empty.first)
        self.assertEqual(
            self.empty.first_or_default(),
            None,
            u"First or default should be None")
        self.assertIsInstance(
            self.simple.first(),
            int,
            u"First element in simple enumerable is int")
        self.assertEqual(
            self.simple.first(),
            1,
            u"First element in simple enumerable is 1")
        self.assertEqual(
            self.simple.first(),
            self.simple.first_or_default(),
            u"First and first or default should equal")
        self.assertIsInstance(
            self.complex.first(),
            dict,
            u"First element in complex enumerable is dict")
        self.assertDictEqual(
            self.complex.first(),
            {'value': 1},
            u"First element in complex enumerable is not correct dict")
        self.assertDictEqual(
            self.complex.first(),
            self.complex.first_or_default(),
            u"First and first or default should equal")
        self.assertEqual(
            self.simple.first(),
            self.complex.select(lambda x: x['value']).first(),
            u"First values in simple and complex should equal")

        self.assertRaises(NoElementsError, self.empty.last)
        self.assertEqual(
            self.empty.last_or_default(),
            None,
            u"Last or default should be None")
        self.assertIsInstance(
            self.simple.last(),
            int,
            u"Last element in simple enumerable is int")
        self.assertEqual(
            self.simple.last(),
            3,
            u"Last element in simple enumerable is 3")
        self.assertEqual(
            self.simple.last(),
            self.simple.last_or_default(),
            u"Last and last or default should equal")
        self.assertIsInstance(
            self.complex.last(),
            dict,
            u"Last element in complex enumerable is dict")
        self.assertDictEqual(
            self.complex.last(),
            {'value': 3},
            u"Last element in complex enumerable is not correct dict")
        self.assertDictEqual(
            self.complex.last(),
            self.complex.last_or_default(),
            u"Last and last or default should equal")
        self.assertEqual(
            self.simple.last(),
            self.complex.select(lambda x: x['value']).last(),
            u"Last values in simple and complex should equal")

    def test_sort(self):
        self.assertRaises(NullArgumentError, self.simple.order_by, None)
        self.assertRaises(
            NullArgumentError,
            self.simple.order_by_descending,
            None)

        self.assertListEqual(
            self.simple.order_by(lambda x: x).to_list(),
            self.simple.to_list(),
            u"Simple enumerable sort ascending should yield same list")
        self.assertListEqual(
            self.simple.order_by_descending(lambda x: x).to_list(),
            sorted(self.simple, key=lambda x: x, reverse=True),
            u"Simple enumerable sort descending should yield reverse list")

        self.assertListEqual(
            self.complex.order_by(lambda x: x['value']).to_list(),
            self.complex.to_list(),
            u"Complex enumerable sort ascending should yield same list")
        self.assertListEqual(
            self.complex.order_by_descending(lambda x: x['value']).to_list(),
            sorted(self.complex, key=lambda x: x['value'], reverse=True),
            u"Complex enumerable sort descending should yield reverse list")

        self.assertListEqual(
            self.simple.order_by(lambda x: x).to_list(),
            self.complex.select(
                lambda x: x['value']
            ).order_by(lambda x: x).to_list(),
            u"Projection and sort ascending of complex should yield simple")

    def test_median(self):
        self.assertRaises(NoElementsError, self.empty.median)

        median = float(2)
        self.assertEqual(
            self.simple.median(),
            median,
            u"Median of simple enumerable should be {0:.5f}".format(median))
        self.assertEqual(
            self.complex.median(lambda x: x['value']),
            median,
            u"Median of complex enumerable should be {0:.5f}".format(median))

    def test_skip_take(self):
        self.assertListEqual(
            self.empty.skip(2).to_list(),
            [],
            u"Skip 2 of empty list should yield empty list")
        self.assertListEqual(
            self.empty.take(2).to_list(),
            [],
            u"Take 2 of empty list should yield empty list")
        self.assertListEqual(
            self.simple.skip(3).to_list(),
            [],
            u"Skip 3 of simple enumerable should yield empty list")
        self.assertListEqual(
            self.simple.take(4).to_list(),
            _simple,
            u"Take 4 of simple enumerable should yield simple list")

        self.assertEqual(
            self.simple.skip(1).take(1).first(),
            2,
            u"Skip 1 and take 1 of simple should yield 2")
        self.assertEqual(
            self.complex.select(lambda x: x['value']).skip(1).take(1).first(),
            2,
            u"Skip 1 and take 1 of complex with projection should yield 2")

    def test_filter(self):
        self.assertListEqual(
            self.empty.where(lambda x: x == 0).to_list(),
            [],
            u"Filter on empty list should yield empty list")
        self.assertListEqual(
            self.simple.where(lambda x: x == 2).to_list(),
            [2],
            u"Filter where element equals 2 should yield list with 1 element")
        self.assertListEqual(
            self.complex.where(lambda x: x['value'] == 2).to_list(),
            [{'value': 2}],
            u"Filter where element value is 2 should give list with 1 element")
        self.assertListEqual(
            self.complex.where(lambda x: x['value'] == 2)
                .select(lambda x: x['value'])
                .to_list(),
            self.simple.where(lambda x: x == 2).to_list(),
            u"Should equal filter of simple enumerable")
        self.assertListEqual(
            self.simple.where(lambda x: x == 0).to_list(),
            self.empty.to_list(),
            u"Should yield an empty list")

    def test_single_single_or_default(self):
        self.assertRaises(NullArgumentError, self.empty.single, None)

        self.assertRaises(
            NoMatchingElement,
            self.empty.single,
            lambda x: x == 0)
        self.assertRaises(
            NoMatchingElement,
            self.simple.single,
            lambda x: x == 0)
        self.assertRaises(
            NoMatchingElement,
            self.complex.single,
            lambda x: x['value'] == 0)
        self.assertRaises(
            MoreThanOneMatchingElement,
            self.simple.single,
            lambda x: x > 0)
        self.assertRaises(
            MoreThanOneMatchingElement,
            self.complex.single,
            lambda x: x['value'] > 0)
        self.assertRaises(
            MoreThanOneMatchingElement,
            self.simple.single_or_default,
            lambda x: x > 0)
        self.assertRaises(
            MoreThanOneMatchingElement,
            self.complex.single_or_default,
            lambda x: x['value'] > 0)

        simple_single = self.simple.single(lambda x: x == 2)
        self.assertIsInstance(
            simple_single,
            int,
            u"Should yield int")
        self.assertEqual(
            simple_single,
            2,
            u"Should yield 2")

        complex_single = self.complex.single(lambda x: x['value'] == 2)
        self.assertIsInstance(
            complex_single,
            dict,
            "Should yield dict")
        self.assertDictEqual(
            complex_single,
            {'value': 2},
            u"Yield '{'value':2}'")
        self.assertEqual(
            simple_single,
            self.complex.select(lambda x: x['value']).single(lambda x: x == 2),
            u"Projection and single on complex should yield single on simple")

        self.assertEqual(
            self.empty.single_or_default(lambda x: x == 0),
            None,
            u"Single or default on empty list should yield None")
        self.assertEqual(
            self.simple.single_or_default(lambda x: x == 0),
            None,
            u"Should yield None")
        self.assertEqual(
            self.complex.single_or_default(lambda x: x['value'] == 0),
            None,
            u"Should yield None")

    def test_select_many(self):
        empty = Enumerable([[], [], []])
        simple = Enumerable([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
        __complex = Enumerable(
            [
                {'key': 1, 'values': [1, 2, 3]},
                {'key': 2, 'values': [4, 5, 6]},
                {'key': 3, 'values': [7, 8, 9]}
            ]
        )

        self.assertListEqual(
            empty.select_many().to_list(),
            [],
            u"Should yield empty list")
        self.assertListEqual(
            simple.select_many().to_list(),
            [1, 2, 3, 4, 5, 6, 7, 8, 9],
            u"Should yield simple enumerable with single list")
        self.assertListEqual(
            __complex.select_many(lambda x: x['values']).to_list(),
            simple.select_many().to_list(),
            u"Should yield simple enumerable with single list")

    def test_concat(self):
        self.assertListEqual(
            self.empty.concat(self.empty).to_list(),
            [],
            u"Concatenation of 2 empty lists gives empty list")
        self.assertListEqual(
            self.empty.concat(self.simple).to_list(),
            _simple,
            u"Concatenation of empty to simple yields simple")
        self.assertListEqual(
            self.simple.concat(self.empty).to_list(),
            _simple,
            u"Concatenation of simple to empty yields simple")

    def test_group_by(self):
        simple_grouped = self.simple.group_by(key_names=['id'])
        self.assertEqual(
            simple_grouped.count(),
            3,
            u"Three grouped elements in simple grouped")
        for g in simple_grouped:
            self.assertEqual(
                g.key.id,
                g.first(),
                u"Each id in simple grouped should match first value")

        complex_grouped = self.complex.group_by(
            key_names=['value'],
            key=lambda x: x['value'])
        self.assertEqual(
            complex_grouped.count(),
            3,
            u"Three grouped elements in complex grouped")
        for g in complex_grouped:
            self.assertEqual(
                g.key.value,
                g.select(lambda x: x['value']).first(),
                u"Each value in complex grouped should mach first value")

        locations_grouped = Enumerable(_locations) \
            .group_by(
            key_names=['country', 'city'],
            key=lambda x: [x[0], x[1]])
        self.assertEqual(
            locations_grouped.count(),
            7,
            u"Seven grouped elements in locations grouped")

        london = locations_grouped \
            .single(
                lambda c: c.key.city == 'London' and c.key.country == 'England'
            )
        self.assertEqual(
            london.sum(lambda c: c[3]),
            240000,
            u"Sum of London, England location does not equal")

    def test_distinct(self):
        self.assertListEqual(
            self.empty.distinct().to_list(),
            [],
            u"Distinct empty enumerable yields empty list")
        self.assertListEqual(
            self.simple.concat(self.simple).distinct().to_list(),
            _simple,
            u"Distinct yields simple list")
        locations = Enumerable(_locations).distinct(lambda x: x[0])
        self.assertEqual(
            locations.count(),
            3,
            u"Three distinct countries in locations enumerable")
        self.assertListEqual(
            locations.to_list(),
            [
                ('England', 'London', 'Branch1', 90000),
                ('Scotland', 'Edinburgh', 'Branch1', 20000),
                ('Wales', 'Cardiff', 'Branch1', 29700)
            ],
            u"Distinct locations do not match")

    def test_default_if_empty(self):
        self.assertListEqual(
            self.empty.default_if_empty().to_list(),
            [None],
            u"Should yield None singleton")
        self.assertListEqual(
            self.simple.default_if_empty().to_list(),
            _simple,
            u"Default if empty of simple enumerable should yield simple list")
        self.assertListEqual(
            self.complex.default_if_empty().to_list(),
            _complex,
            u"Should yield complex list")

    def test_any(self):
        self.assertRaises(NullArgumentError, self.simple.any, None)
        self.assertFalse(
            self.empty.any(lambda x: x == 1),
            u"Empty enumerable does not contain any elements that equal 1")
        self.assertTrue(
            self.simple.any(lambda x: x == 1),
            u"Simple enumerable does contain elements that equal 1")
        self.assertFalse(
            self.complex.any(lambda x: x['value'] < 1),
            u"Complex enumerable does not contain any elements with value < 1")
        self.assertTrue(
            self.complex.any(lambda x: x['value'] >= 1),
            u"Complex enumerable does contain elements with value >= 1")

    def test_contains(self):
        self.assertFalse(
            self.empty.contains(1),
            u"Empty enumerable should not contain 1 as element")
        self.assertTrue(
            self.simple.contains(1),
            u"Simple enumerable should contain 1 as element")
        self.assertTrue(
            self.complex.select(lambda x: x['value']).contains(1),
            u"Complex enumerable should contain 1 as an element value")

    def test_intersect(self):
        self.assertRaises(TypeError, self.empty.intersect, [])
        self.assertListEqual(
            self.empty.intersect(self.empty).to_list(),
            [],
            u"Intersect of two empty enumerables yield empty list")
        self.assertListEqual(
            self.empty.intersect(self.simple).to_list(),
            [],
            u"Intersect of empty and simple enumerables yields empty list")
        self.assertListEqual(
            self.simple.intersect(self.simple).to_list(),
            _simple,
            u"Intersect of two simple enumerables yields simple list")
        self.assertListEqual(
            self.simple.intersect(Enumerable([2])).to_list(),
            [2],
            u"Intersect of simple enumerable and [2] yields [2]")
        self.assertListEqual(
            self.simple.intersect(self.complex).to_list(),
            [],
            u"Intersect of simple and complex enumerable yields empty list")
        self.assertListEqual(
            self.complex.intersect(self.complex).to_list(),
            _complex,
            u"Intersect of two complex enumeraable yields complex list")
        self.assertListEqual(
            self.complex.intersect(Enumerable([{'value': 1}])).to_list(),
            [{'value': 1}],
            "Should yield {'value': 1}")

    def test_except(self):
        self.assertRaises(TypeError, self.empty.except_, [])
        self.assertListEqual(
            self.empty.except_(self.empty).to_list(),
            [],
            u"Complement of two empty enumerables yields empty list")
        self.assertListEqual(
            self.empty.except_(self.simple).to_list(),
            [],
            u"Complement of empty and simple enumerables yields empty list")
        self.assertListEqual(
            self.simple.except_(self.empty).to_list(),
            _simple,
            u"Complement of simple and empty enumerables yields simple list")
        self.assertListEqual(
            self.simple.except_(self.simple).to_list(),
            [],
            u"Complement of simple and simple enumerables yields empty list")
        self.assertListEqual(
            self.simple.except_(Enumerable([2])).to_list(),
            [1, 3],
            u"Complement of simple and [2] yields [1,3]")
        self.assertListEqual(
            self.simple.except_(self.complex).to_list(),
            _simple,
            u"Complement of simple and complex yields simple")
        self.assertListEqual(
            self.complex.except_(self.simple).to_list(),
            _complex,
            u"Complement of complex and simple yields complex")
        self.assertListEqual(
            self.complex.except_(self.complex).to_list(),
            [],
            u"Complement of complex and complex yields empty")
        self.assertListEqual(
            self.complex.except_(Enumerable([{'value': 1}])).to_list(),
            [{'value': 2}, {'value': 3}],
            "Should yield [{'value': 2}, 'value': 3]")

    def test_marks_intersect(self):
        marks1 = Enumerable([{'course': 'Chemistry', 'mark': 90}, {'course': 'Biology', 'mark': 85}])
        marks2 = Enumerable([{'course': 'Chemistry', 'mark': 65}, {'course': 'Computer Science', 'mark': 96}])
        self.assertListEqual(
            marks1.intersect(marks2, lambda c: c['course']).to_list(),
            [{'course': 'Chemistry', 'mark': 90}]
        )

    def test_marks_except(self):
        marks1 = Enumerable([{'course': 'Chemistry', 'mark': 90}, {'course': 'Biology', 'mark': 85}])
        marks2 = Enumerable([{'course': 'Chemistry', 'mark': 65}, {'course': 'Computer Science', 'mark': 96}])
        self.assertListEqual(
            marks1.except_(marks2, lambda c: c['course']).to_list(),
            [{'course': 'Biology', 'mark': 85}]
        )

    def test_union(self):
        self.assertListEqual(
            self.empty.union(self.empty).to_list(),
            [],
            u"Union of two empty enumerables yields empty list")
        self.assertListEqual(
            self.empty.union(self.simple).to_list(),
            _simple,
            u"Union of empty and simple yield simple")
        self.assertListEqual(
            self.simple.union(self.empty).to_list(),
            _simple,
            u"Union of simple and empty yield simple")
        self.assertListEqual(
            self.empty.union(self.complex).to_list(),
            _complex,
            u"Union of empty and complex yield complex")
        self.assertListEqual(
            self.complex.union(self.empty).to_list(),
            _complex,
            u"Union of complex and empty yield complex")

        simple_extended = _simple + [4, 5]
        self.assertListEqual(
            self.simple.union(Enumerable([4, 5])).to_list(),
            simple_extended,
            u"Union of simple and [4,5] yield simple + [4,5]")
        self.assertListEqual(
            self.simple.union(Enumerable([1, 4, 5]))
                .order_by(lambda x: x).to_list(),
            simple_extended,
            u"Union of simple and [1,4,5] yield simple + [4,5]")

        complex_extended = _complex + [{'value': 4}, {'value': 5}]
        self.assertListEqual(
            self.complex.union(
                Enumerable([{'value': 4}, {'value': 5}]),
                lambda x: x['value']).to_list(),
            complex_extended,
            u"Should yield complex + [{'value': 4}, {'value': 5}]")
        self.assertListEqual(
            self.complex.union(
                Enumerable([{'value': 1}, {'value': 4}, {'value': 5}]),
                lambda x: x['value']).order_by(lambda x: x['value']).to_list(),
            complex_extended,
            u"Should yield complex + [{'value': 4}, {'value': 5}]")

    def test_join(self):
        self.assertRaises(TypeError, self.empty.join, [])
        self.assertListEqual(
            self.empty.join(self.empty).to_list(),
            [],
            u"Joining 2 empty lists should yield empty list")
        self.assertListEqual(
            self.empty.join(self.simple).to_list(),
            [],
            u"Joining empty to simple yields empty list")
        self.assertListEqual(
            self.empty.join(self.complex).to_list(),
            [],
            u"Joining complex to simple yields empty list")

        self.assertListEqual(
            self.simple.join(self.empty).to_list(),
            [],
            u"Joining simple to empty yields empty list")
        self.assertListEqual(
            self.simple.join(self.simple)
                .order_by(lambda x: (x[0], x[1])).to_list(),
            [(1, 1), (2, 2), (3, 3)],
            u"Joining simple to simple yields [(1,1), (2,2), (3,3)]")
        self.assertListEqual(
            self.simple.join(
                self.complex,
                inner_key=lambda x: x['value'],
                result_func=lambda x: (x[0], x[1]['value'])).order_by(
                lambda x: (x[0], x[1])
            ).to_list(),
            [(1, 1), (2, 2), (3, 3)],
            u"Should yield [(1,1), (2,2), (3,3)]")

        self.assertListEqual(
            self.complex.join(
                self.complex,
                result_func=lambda x: (x[0]['value'], x[1]['value'])).order_by(
                    lambda x: (x[0], x[1])).to_list(),
            [(1, 1), (2, 2), (3, 3)],
            u"Should yield [(1,1), (2,2), (3,3)]")

    def test_group_join(self):
        self.assertRaises(TypeError, self.empty.group_join, [])
        self.assertListEqual(
            self.empty.group_join(self.empty).to_list(),
            [],
            u"Group join 2 empty yields empty")

        simple_empty_gj = self.simple.group_join(self.empty)
        self.assertEqual(
            simple_empty_gj.count(),
            3,
            u"Should have 3 elements")
        for i, e in enumerate(simple_empty_gj):
            self.assertEqual(
                e[0],
                i + 1,
                u"number property should be {0}".format(i + 1))
            self.assertEqual(
                e[1].count(),
                0,
                u"Should have 0 elements")
            self.assertEqual(
                e[1].first_or_default(),
                None,
                u"Value of first element should be None")

        simple_gj = self.simple.group_join(
            self.simple,
            result_func=lambda x: {
                'number': x[0],
                'collection': x[1]
            })
        for i, e in enumerate(simple_gj):
            self.assertEqual(
                e['number'],
                i + 1,
                u"number property should be {0}".format(i + 1))
            self.assertEqual(
                e['collection'].count(),
                1,
                u"Should only have one element")
            self.assertEqual(
                e['collection'].first(),
                i + 1,
                u"Value of first element should equal {0}".format(i + 1))

        complex_simple_gj = self.complex.group_join(
            self.simple,
            outer_key=lambda x: x['value'])
        for i, e in enumerate(complex_simple_gj):
            self.assertEqual(
                e[0]['value'],
                i + 1,
                u"value property of each element should be {0}".format(i + 1))
            self.assertEqual(
                e[1].count(),
                1,
                u"Should only have one element")
            self.assertEqual(
                e[1].first(),
                i + 1,
                u"Value of first element should equal {0}".format(i + 1))

        simple_gj = self.simple.group_join(
            Enumerable([2, 3]),
            result_func=lambda x: {
                'number': x[0],
                'collection': x[1]
            }).to_list()
        self.assertEqual(
            len(simple_gj),
            3,
            u"Should be 3 elements")
        for i, e in enumerate(simple_gj):
            self.assertEqual(
                e['number'],
                i + 1,
                u"number property should be {0}".format(i + 1))
            self.assertEqual(
                e['collection'].count(),
                0 if i == 0 else 1,
                u"should have {0} element(s)".format(0 if i == 0 else 1))
            self.assertListEqual(
                e['collection'].to_list(),
                [] if i == 0 else [i + 1],
                u"Collection should equal {0}".format(
                    [] if i == 0 else [i + 1])
            )

    def test_then_by(self):
        locations = Enumerable(_locations)
        self.assertListEqual(
            locations.order_by(lambda l: l[0])
            .then_by(lambda l: l[1])
            .select(lambda l: u"{0}, {1}".format(l[1], l[0]))
            .to_list(),
            [
                u'Liverpool, England',
                u'Liverpool, England',
                u'London, England',
                u'London, England',
                u'London, England',
                u'Manchester, England',
                u'Manchester, England',
                u'Edinburgh, Scotland',
                u'Glasgow, Scotland',
                u'Glasgow, Scotland',
                u'Bangor, Wales',
                u'Cardiff, Wales',
                u'Cardiff, Wales'
            ],
            u"then_by locations ordering is not correct")
        self.assertRaises(
            NullArgumentError,
            locations.order_by(lambda l: l[0]).then_by,
            None)

    def test_then_by_descending(self):
        locations = Enumerable(_locations)
        self.assertListEqual(
            locations.order_by(lambda l: l[0])
            .then_by(lambda l: l[1])
            .then_by_descending(lambda l: l[3])
            .select(lambda l: u"{0}, {1}: {2}".format(
                l[1], l[0], l[3]
            ))
            .to_list(),
            [
                u'Liverpool, England: 29700',
                u'Liverpool, England: 25000',
                u'London, England: 90000',
                u'London, England: 80000',
                u'London, England: 70000',
                u'Manchester, England: 50000',
                u'Manchester, England: 45600',
                u'Edinburgh, Scotland: 20000',
                u'Glasgow, Scotland: 12500',
                u'Glasgow, Scotland: 12000',
                u'Bangor, Wales: 12800',
                u'Cardiff, Wales: 30000',
                u'Cardiff, Wales: 29700'
            ],
            u"then_by_descending ordering is not correct"
        )

    def reverse(self, result, element):
        return element + " " + result

    def sum(self, result, element):
        return result + element

    def test_aggregate(self):
        words = u"the quick brown fox jumps over the lazy dog".split(" ")
        self.assertListEqual(words, ["the", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog"])
        test = Enumerable(words).aggregate(self.reverse)
        self.assertEqual(test, "dog lazy the over jumps fox brown quick the")

        self.assertRaises(NoElementsError, Enumerable().aggregate, [lambda x: x[0] + x[1], 0])

        test = self.simple.aggregate(self.sum, seed=0)
        self.assertEqual(test, 6)

    def test_all(self):
        test = Enumerable([1, 1, 1]).all(lambda x: x == 1)
        self.assertTrue(test)

        test = Enumerable([]).all(lambda x: x == 1)
        self.assertTrue(test)

        test = self.simple.all(lambda x: x == 1)
        self.assertFalse(test)

    def test_append(self):
        test = self.simple.append(4)
        self.assertEqual(test.count(), 4)
        self.assertEqual(test.element_at(3), 4)

    def test_prepend(self):
        test = self.simple.prepend(4)
        self.assertEqual(test.count(), 4)
        self.assertEqual(test.element_at(0), 4)

    def test_empty(self):
        test = Enumerable.empty()
        self.assertIsInstance(test, Enumerable)
        self.assertEqual(test.count(), 0)

    def test_range(self):
        test = Enumerable.range(1, 3)
        self.assertEqual(test.count(), 3)
        self.assertListEqual(self.simple.to_list(), test.to_list())

    def test_repeat(self):
        test = Enumerable.repeat(u'Z', 10)
        self.assertEqual(test.count(), 10)
        self.assertEqual(u"".join(test.to_list()), u'ZZZZZZZZZZ')

    def test_reverse(self):
        test = self.simple.reverse()
        self.assertListEqual(test.to_list(), [3, 2, 1])

        words = u"the quick brown fox jumps over the lazy dog".split(" ")
        self.assertListEqual(words, ["the", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog"])
        test = Enumerable(words).reverse()
        self.assertEqual(u" ".join(test.to_list()), u"dog lazy the over jumps fox brown quick the")

    def test_skip_last(self):
        test = Enumerable([1, 2, 3, 4, 5]).skip_last(2)
        self.assertListEqual(test.to_list(), [1, 2, 3])

        test = Enumerable(["one", "two", "three", "four", "five"]).skip(1).skip_last(1)
        self.assertListEqual(test.to_list(), ["two", "three", "four"])

    def test_skip_while(self):
        test = Enumerable([1, 4, 6, 4, 1]).skip_while(lambda x: x < 5)
        self.assertListEqual(test.to_list(), [6, 4, 1])

        test = Enumerable([]).skip_while(lambda x: x < 5)
        self.assertListEqual(test.to_list(), [])

    def test_take_last(self):
        test = Enumerable([1, 2, 3, 4, 5]).take_last(2)
        self.assertListEqual(test.to_list(), [4, 5])

        test = Enumerable(["one", "two", "three", "four", "five"]).take(3).take_last(1)
        self.assertListEqual(test.to_list(), ["three"])

    def test_take_while(self):
        test = Enumerable([1, 4, 6, 4, 1]).take_while(lambda x: x < 5)
        self.assertListEqual(test.to_list(), [1, 4])

        test = Enumerable([]).skip_while(lambda x: x < 5)
        self.assertListEqual(test.to_list(), [])

    def test_zip(self):
        test = Enumerable(["A", "B", "C", "D"]).zip(Enumerable(["x", "y"]), lambda t: "{0}{1}".format(t[0], t[1]))
        self.assertListEqual(test.to_list(), ["Ax", "By"])
Esempio n. 3
0
class IssueTests(TestCase):
    def setUp(self):
        self.empty = Enumerable(_empty)
        self.simple = Enumerable(_simple)
        self.complex = Enumerable(_complex)

    def test_issue19_1(self):
        foo = Enumerable([1])
        bar = Enumerable([1])
        self.assertEqual(foo.intersect(bar).count(), 1)

    def test_issue19_2(self):
        foo = Enumerable([1])
        bar = Enumerable([1]).distinct()
        self.assertEqual(foo.intersect(bar).count(), 1)

    def test_issue19_3(self):
        foo = Enumerable([1]).distinct()
        bar = Enumerable([1])
        self.assertEqual(foo.intersect(bar).count(), 1)

    def test_issue22(self):
        def my_iter():
            for i in range(10):
                yield i

        def low_iter():
            for i in range(5):
                yield i

        def high_iter():
            for k in range(5):
                yield k + 5

        data = my_iter()
        a = Enumerable(data)

        low = a.where(lambda x: x < 5)
        high = a.where(lambda x: x >= 5)

        self.assertListEqual([(0, 5), (1, 6), (2, 7), (3, 8), (4, 9)],
                             low.zip(high).to_list())

        self.assertListEqual([(0, 5), (1, 6), (2, 7), (3, 8), (4, 9)],
                             list(zip(low, high)))

    def test_generator_to_Enumerable(self):
        def first_3():
            for i in range(3):
                yield i

        p2 = Enumerable(first_3())
        self.assertListEqual([0, 1, 2], p2.to_list())

        p3 = Enumerable((i for i in first_3()))
        self.assertListEqual([0, 1, 2], p3.to_list())

    def test_issue22_join(self):
        class Val(object):
            def __init__(self, number, power):
                self.number = number
                self.power = power

            def __str__(self):
                return "VAL {0}: {1}".format(self.number, self.power)

        def powers_of_2():
            for i in range(2):
                yield Val(i, 2**i)

        def powers_of_10():
            for i in range(2):
                yield Val(i, 10**i)

        en2 = Enumerable(powers_of_2())
        en10 = Enumerable(powers_of_10())
        joined = en2.join(
            en10,
            lambda x: x.number,
            lambda y: y.number,
            lambda r: (r[0].power, r[1].power),
        )
        truth = zip([2**i for i in range(2)], [10**y for y in range(2)])
        self.assertListEqual(list(truth), joined.to_list())

    def test_first_with_lambda(self):
        self.assertRaises(IndexError, self.empty.first, lambda x: x == 0)
        self.assertEqual(2, self.simple.first(lambda x: x == 2))
        self.assertDictEqual({"value": 2},
                             self.complex.first(lambda x: x["value"] == 2))

    def test_first_or_default_with_lambda(self):
        self.assertIsNone(self.empty.first_or_default(lambda x: x == 0))
        self.assertEqual(
            self.simple.first(lambda x: x == 2),
            self.simple.first_or_default(lambda x: x == 2),
        )
        self.assertEqual(
            self.complex.first(lambda x: x["value"] == 2),
            self.complex.first_or_default(lambda x: x["value"] == 2),
        )

    def test_last_with_lambda(self):
        self.assertRaises(IndexError, self.empty.last, lambda x: x == 0)
        self.assertEqual(2, self.simple.last(lambda x: x == 2))
        self.assertDictEqual({"value": 2},
                             self.complex.last(lambda x: x["value"] == 2))
        self.assertEqual(self.simple.first(lambda x: x == 2),
                         self.simple.last(lambda x: x == 2))

    def test_last_or_default_with_lambda(self):
        self.assertIsNone(self.empty.last_or_default(lambda x: x == 0))
        self.assertEqual(
            self.simple.last(lambda x: x == 2),
            self.simple.last_or_default(lambda x: x == 2),
        )
        self.assertEqual(
            self.complex.last(lambda x: x["value"] == 2),
            self.complex.last_or_default(lambda x: x["value"] == 2),
        )
        self.assertEqual(
            self.simple.first_or_default(lambda x: x == 2),
            self.simple.last_or_default(lambda x: x == 2),
        )

    def test_issue_34(self):
        class Obj(object):
            def __init__(self, n, v):
                self.n = n
                self.v = v

        foo = Enumerable([Obj("foo", 1), Obj("bar", 2)])
        self.assertTrue(foo.any(lambda x: x.n == "foo"))
        self.assertTrue(foo.any(lambda x: x.n == "foo"))
        filtered_foo = foo.where(lambda x: x.n == "foo")
        self.assertIsNotNone(filtered_foo.first())
        self.assertEqual("foo", filtered_foo.first().n)
        self.assertTrue(filtered_foo.any(lambda x: x.v == 1))
        self.assertTrue(filtered_foo.any(lambda x: x.v == 1))

    def test_issue_35(self):
        a = Enumerable([9, 8, -7, 6, 5])
        b = a.order_by(lambda x: x)
        self.assertEqual(-7, b.first())
        self.assertEqual(-7, list(b)[0])
        self.assertEqual(-7, b.first())

    def test_issue_36(self):
        def append_to_list(lst, element):
            lst.append(element)

        filepath = os.path.join(os.getcwd(), "tests", "files",
                                "test_file1.txt")
        result = []
        with io.open(filepath) as f:
            lines = (Enumerable(f).skip(1).where(
                lambda l: not l.startswith("#")).aggregate(
                    append_to_list, result))
        self.assertEqual(1, len(result))
        self.assertEqual("This line should be counted", result[0])

    def test_issue_47(self):
        marks = Enumerable([(25, 'a'), (49, 'b'), (50, 'c'), (80, 'd'),
                            (90, 'e')])
        passing = marks.where(lambda x: x[0] >= 50)
        self.assertListEqual([(50, 'c'), (80, 'd'), (90, 'e')],
                             passing.to_list())
        omarks = Enumerable([(80, 'eighty'), (49, 'fortynine')])
        join_result = omarks.join(passing, lambda o: o[0], lambda y: y[0],
                                  lambda result: result).to_list()
        self.assertListEqual([((80, 'eighty'), (80, 'd'))], join_result)

    def test_empty_join(self):
        marks = Enumerable([(25, 'a'), (49, 'b'), (50, 'c'), (80, 'd'),
                            (90, 'e')])
        passing = marks.where(lambda x: x[0] > 90)
        self.assertListEqual([], passing.to_list())
        omarks = Enumerable([(80, 'eighty'), (49, 'fortynine')])
        join_result = omarks.join(passing, lambda o: o[0], lambda y: y[0],
                                  lambda result: result).to_list()
        self.assertListEqual([], join_result)

    def test_issue_50(self):
        """
        Only single char for key value on group_by
        """
        class MyObject(object):
            def __init__(self, name):
                self.field = name

            def get_field(self):
                return self.field

        test = Enumerable([
            MyObject("Bruce"),
            MyObject("Bruce"),
            MyObject("Fenske"),
            MyObject("Luke")
        ])
        group = test.group_by(key_names=['field_name'], key=lambda r: r.get_field()) \
            .order_by(lambda g: g.key.field_name)
        self.assertEqual("Bruce", group[0].key.field_name)

    def test_issue_50_2(self):
        class MyObject(object):
            def __init__(self, name):
                self.field = name

            def get_field(self):
                return self.field

        def get_field(item):
            return item.get_field()

        test = Enumerable([
            MyObject("Bruce"),
            MyObject("Bruce"),
            MyObject("Fenske"),
            MyObject("Luke")
        ])
        group = test.group_by(
            key_names=['field_name'],
            key=get_field).order_by(lambda g: g.key.field_name)
        self.assertEqual("Bruce", group[0].key.field_name)
Esempio n. 4
0
class TestFunctions(TestCase):
    def setUp(self):
        self.empty = Enumerable(_empty)
        self.simple = Enumerable(_simple)
        self.complex = Enumerable(_complex)

    def test_iter(self):
        self.assertListEqual(_simple, list(iter(self.simple)))
        self.assertListEqual(_empty, list(iter(self.empty)))
        self.assertListEqual(_complex, list(iter(self.complex)))

    def test_iter_select(self):
        self.assertListEqual(_empty, list(iter(self.empty.select(lambda x: x))))
        self.assertListEqual(_simple, list(iter(self.simple.select(lambda x: x))))
        self.assertListEqual(
            _simple, list(iter(self.complex.select(lambda x: x["value"])))
        )

    def test_iter_where(self):
        self.assertListEqual(_empty, list(iter(self.empty.where(lambda x: x == 2))))
        self.assertListEqual([2], list(iter(self.simple.where(lambda x: x == 2))))
        self.assertListEqual(
            [{"value": 2}], list(iter(self.complex.where(lambda x: x["value"] == 2)))
        )

    def test_len(self):
        self.assertEqual(0, len(self.empty))
        self.assertEqual(3, len(self.simple))

    def test_get_item(self):
        self.assertIsNone(self.empty[0])
        self.assertEqual(2, self.simple[1])
        self.assertDictEqual({"value": 2}, self.complex[1])

    def test_get_item_select(self):
        self.assertIsNone(self.empty.select(lambda x: x["value"])[0])
        self.assertEqual(2, self.complex.select(lambda x: x["value"])[1])
        self.assertEqual({"value": 2}, self.simple.select(lambda x: {"value": x})[1])

    def test_to_list(self):
        self.assertListEqual(_empty, self.empty.to_list())
        self.assertListEqual(_simple, self.simple.to_list())
        self.assertListEqual(_complex, self.complex.to_list())

    def test_sum(self):
        self.assertEqual(0, self.empty.sum())
        self.assertEqual(6, self.simple.sum())

    def test_sum_with_filter(self):
        self.assertEqual(6, self.complex.sum(lambda x: x["value"]))

    def test_count(self):
        self.assertEqual(self.empty.count(), 0)
        self.assertEqual(self.simple.count(), 3)
        self.assertEqual(self.complex.count(), 3)

    def test_count_with_filter(self):
        self.assertEqual(self.empty.count(lambda x: x == 1), 0)
        self.assertEqual(self.simple.count(lambda x: x == 1), 1)
        self.assertEqual(self.complex.count(lambda x: x["value"] > 1), 2)

    def test_select(self):
        self.assertListEqual(
            [], Enumerable.empty().select(lambda x: x["value"]).to_list()
        )
        self.assertListEqual(
            [{"value": 1}, {"value": 2}, {"value": 3}],
            Enumerable([1, 2, 3]).select(lambda x: {"value": x}).to_list(),
        )
        self.assertListEqual(
            [1, 2, 3],
            Enumerable(
                [
                    {"value": 1},
                    {"value": 2},
                    {"value": 3},
                ]
            )
            .select(lambda x: x["value"])
            .to_list(),
        )

    def test_min(self):
        self.assertRaises(NoElementsError, self.empty.min)
        self.assertEqual(1, self.simple.min())
        self.assertEqual(1, self.complex.min(lambda x: x["value"]))

    def test_max(self):
        self.assertRaises(NoElementsError, self.empty.max)
        self.assertEqual(3, self.simple.max())
        self.assertEqual(3, self.complex.max(lambda x: x["value"]))

    def test_avg(self):
        avg = float(2)
        self.assertRaises(NoElementsError, self.empty.avg)
        self.assertEqual(self.simple.avg(), avg)
        self.assertEqual(self.complex.avg(lambda x: x["value"]), avg)

    def test_element_at(self):
        self.assertRaises(IndexError, self.empty.element_at, 0)
        self.assertEqual(2, self.simple.element_at(1))
        self.assertDictEqual({"value": 2}, self.complex.element_at(1))

    def test_first(self):
        self.assertRaises(IndexError, self.empty.first)
        self.assertIsInstance(self.simple.first(), int)
        self.assertEqual(1, self.simple.order_by(lambda x: x).first())
        self.assertIsInstance(self.complex.first(), dict)
        self.assertDictEqual(
            {"value": 1}, self.complex.order_by(lambda x: x["value"]).first()
        )

    def test_first_or_default(self):
        self.assertIsNone(self.empty.first_or_default())
        self.assertIsInstance(self.simple.first_or_default(), int)
        self.assertDictEqual({"value": 1}, self.complex.first_or_default())

    def test_last(self):
        self.assertRaises(IndexError, self.empty.last)
        self.assertIsInstance(self.simple.last(), int)
        self.assertEqual(3, self.simple.order_by(lambda x: x).last())
        self.assertIsInstance(self.complex.last(), dict)
        self.assertDictEqual(
            {"value": 3}, self.complex.order_by(lambda x: x["value"]).last()
        )
        self.assertDictEqual(
            self.complex.order_by(lambda x: x["value"]).last(),
            self.complex.order_by(lambda x: x["value"]).last_or_default(),
        )

    def test_last_or_default(self):
        self.assertIsNone(self.empty.last_or_default())
        self.assertEqual(3, self.simple.order_by(lambda x: x).last_or_default())
        self.assertIsInstance(self.complex.last_or_default(), dict)
        self.assertDictEqual(
            {"value": 3}, self.complex.order_by(lambda x: x["value"]).last_or_default()
        )

    def test_order_by(self):
        self.assertRaises(NullArgumentError, self.simple.order_by, None)
        self.assertListEqual(_simple, self.simple.order_by(lambda x: x).to_list())
        self.assertListEqual(
            _complex, self.complex.order_by(lambda x: x["value"]).to_list()
        )

    def test_order_by_descending(self):
        self.assertRaises(NullArgumentError, self.simple.order_by_descending, None)
        self.assertListEqual(
            [3, 2, 1], self.simple.order_by_descending(lambda x: x).to_list()
        )
        self.assertListEqual(
            [{"value": 3}, {"value": 2}, {"value": 1}],
            self.complex.order_by_descending(lambda x: x["value"]).to_list(),
        )

    def test_order_by_with_select(self):
        self.assertListEqual(
            _simple,
            self.complex.select(lambda x: x["value"]).order_by(lambda x: x).to_list(),
        )

    def test_order_by_descending_with_select(self):
        self.assertListEqual(
            [3, 2, 1],
            self.complex.select(lambda x: x["value"])
            .order_by_descending(lambda x: x)
            .to_list(),
        )

    def test_order_by_with_where(self):
        self.assertListEqual(
            [2, 3], self.simple.where(lambda x: x >= 2).order_by(lambda x: x).to_list()
        )

    def test_order_by_descending_with_where(self):
        self.assertListEqual(
            [3, 2],
            self.simple.where(lambda x: x >= 2)
            .order_by_descending(lambda x: x)
            .to_list(),
        )

    def test_median(self):
        self.assertRaises(NoElementsError, self.empty.median)
        median = float(2)
        self.assertEqual(median, self.simple.median())
        self.assertEqual(median, self.complex.median(lambda x: x["value"]))

    def test_skip(self):
        self.assertListEqual([], Enumerable().skip(2).to_list())
        self.assertListEqual([], Enumerable([1, 2, 3]).skip(3).to_list())
        self.assertListEqual([2, 3], Enumerable([1, 2, 3]).skip(1).to_list())

    def test_take(self):
        self.assertListEqual(_simple, self.simple.take(4).to_list())

    def test_skip_with_take(self):
        self.assertListEqual([2], self.simple.skip(1).take(1).to_list())

    def test_skip_take_with_select(self):
        self.assertListEqual(
            [2], self.complex.select(lambda x: x["value"]).skip(1).take(1).to_list()
        )

    def test_filter(self):
        self.assertListEqual([], self.empty.where(lambda x: x == 0).to_list())
        self.assertListEqual([2], self.simple.where(lambda x: x == 2).to_list())
        self.assertListEqual(
            [{"value": 2}], self.complex.where(lambda x: x["value"] == 2).to_list()
        )
        self.assertListEqual([], self.simple.where(lambda x: x == 0).to_list())

    def test_select_with_filter(self):
        self.assertListEqual(
            [2],
            Enumerable([{"value": 1}, {"value": 2}, {"value": 3}])
            .where(lambda x: x["value"] == 2)
            .select(lambda x: x["value"])
            .to_list(),
        )

    def test_single(self):
        self.assertRaises(NoMatchingElement, self.empty.single, lambda x: x == 0)
        self.assertRaises(NoMatchingElement, self.empty.single, None)

        self.assertRaises(NoMatchingElement, self.simple.single, lambda x: x == 0)
        self.assertRaises(MoreThanOneMatchingElement, self.simple.single, None)

        self.assertRaises(
            NoMatchingElement, self.complex.single, lambda x: x["value"] == 0
        )
        self.assertRaises(MoreThanOneMatchingElement, self.complex.single, None)

        self.assertRaises(
            MoreThanOneMatchingElement, self.simple.single, lambda x: x > 0
        )
        self.assertRaises(
            MoreThanOneMatchingElement, self.complex.single, lambda x: x["value"] > 0
        )

    def test_single(self):
        simple_single = self.simple.single(lambda x: x == 2)
        self.assertIsInstance(simple_single, int)
        self.assertEqual(2, simple_single)

        complex_single = self.complex.single(lambda x: x["value"] == 2)
        self.assertIsInstance(complex_single, dict)
        self.assertDictEqual({"value": 2}, complex_single)

        select_single = self.complex.select(lambda x: x["value"]).single(
            lambda x: x == 2
        )
        self.assertEqual(2, select_single)

    def test_single_or_default(self):
        self.assertRaises(
            MoreThanOneMatchingElement, self.simple.single_or_default, lambda x: x > 0
        )
        self.assertIsNone(self.simple.single_or_default(lambda x: x > 3))
        self.assertRaises(
            MoreThanOneMatchingElement,
            self.complex.single_or_default,
            lambda x: x["value"] > 0,
        )

    def test_select_many(self):
        self.assertListEqual([], Enumerable([[], [], []]).select_many().to_list())
        self.assertListEqual(
            [1, 2, 3, 4, 5, 6, 7, 8, 9],
            Enumerable([[1, 2, 3], [4, 5, 6], [7, 8, 9]]).select_many().to_list(),
        )
        self.assertEqual(
            9, Enumerable([[1, 2, 3], [4, 5, 6], [7, 8, 9]]).select_many().count()
        )
        self.assertListEqual(
            [1, 2, 3, 4, 5, 6, 7, 8, 9],
            Enumerable(
                [
                    {"key": 1, "values": [1, 2, 3]},
                    {"key": 2, "values": [4, 5, 6]},
                    {"key": 3, "values": [7, 8, 9]},
                ]
            )
            .select_many(lambda x: x["values"])
            .to_list(),
        )
        self.assertEqual(
            9,
            Enumerable(
                [
                    {"key": 1, "values": [1, 2, 3]},
                    {"key": 2, "values": [4, 5, 6]},
                    {"key": 3, "values": [7, 8, 9]},
                ]
            )
            .select_many(lambda x: x["values"])
            .count(),
        )

    def test_concat(self):
        self.assertListEqual([], Enumerable().concat(Enumerable()).to_list())
        self.assertListEqual(
            [1, 2, 3], Enumerable().concat(Enumerable([1, 2, 3])).to_list()
        )
        self.assertListEqual(
            [1, 2, 3], Enumerable([1, 2, 3]).concat(Enumerable()).to_list()
        )
        self.assertListEqual(
            [1, 2, 3, 1, 2, 3],
            Enumerable([1, 2, 3])
            .concat(
                Enumerable(
                    [
                        {"value": 1},
                        {"value": 2},
                        {"value": 3},
                    ]
                ).select(lambda c: c["value"])
            )
            .to_list(),
        )
        self.assertListEqual(
            [1, 2, 3, 1, 2, 3],
            Enumerable(
                [
                    {"value": 1},
                    {"value": 2},
                    {"value": 3},
                ]
            )
            .select(lambda c: c["value"])
            .concat(Enumerable([1, 2, 3]))
            .to_list(),
        )
        self.assertListEqual(
            [1, 2, 3, {"value": 1}, {"value": 2}, {"value": 3}],
            Enumerable([1, 2, 3])
            .concat(
                Enumerable(
                    [
                        {"value": 1},
                        {"value": 2},
                        {"value": 3},
                    ]
                )
            )
            .to_list(),
        )

    def test_concat_mutating(self):
        empty = Enumerable()
        empty.concat(Enumerable())
        self.assertListEqual([], empty.to_list())

        simple = Enumerable()
        simple.concat(Enumerable([1, 2, 3]))
        self.assertListEqual([1, 2, 3], simple.to_list())

        double_simple = Enumerable([1, 2, 3])
        double_simple.concat(
            Enumerable(
                [
                    {"value": 1},
                    {"value": 2},
                    {"value": 3},
                ]
            ).select(lambda c: c["value"])
        )
        self.assertListEqual([1, 2, 3, 1, 2, 3], double_simple.to_list())

        simple_complex = Enumerable([1, 2, 3])
        simple_complex.concat(
            Enumerable(
                [
                    {"value": 1},
                    {"value": 2},
                    {"value": 3},
                ]
            )
        )
        self.assertListEqual(
            [1, 2, 3, {"value": 1}, {"value": 2}, {"value": 3}],
            simple_complex.to_list(),
        )

    def test_multiple_concatenate(self):
        simple = Enumerable([1, 2, 3])
        simple.add(4)
        self.assertEqual(4, simple.count())
        simple.add(5)
        self.assertEqual(5, simple.count())
        self.assertEqual(5, simple.last())

    def test_group_by(self):
        simple_grouped = Enumerable([1, 2, 3]).group_by(key_names=["id"])
        self.assertEqual(3, simple_grouped.count())
        second = simple_grouped.single(lambda s: s.key.id == 2)
        self.assertListEqual([2], second.to_list())

        complex_grouped = Enumerable(
            [{"value": 1}, {"value": 2}, {"value": 3}]
        ).group_by(key_names=["value"], key=lambda x: x["value"])
        self.assertEqual(complex_grouped.count(), 3)
        self.assertListEqual(
            [1, 2, 3],
            complex_grouped.select(lambda x: x.key.value)
            .order_by(lambda x: x)
            .to_list(),
        )

        locations_grouped = Enumerable(_locations).group_by(
            key_names=["country", "city"], key=lambda x: [x[0], x[1]]
        )
        self.assertEqual(locations_grouped.count(), 7)

        london = locations_grouped.single(
            lambda c: c.key.city == "London" and c.key.country == "England"
        )
        self.assertEqual(240000, london.sum(lambda c: c[3]))

    def test_distinct(self):
        self.assertListEqual([], Enumerable.empty().distinct().to_list())
        six.assertCountEqual(
            self,
            [1, 2, 3],
            Enumerable([1, 2, 3]).concat(Enumerable([1, 2, 3])).distinct().to_list(),
        )

        locations = Enumerable(_locations).distinct(lambda x: x[0])
        self.assertEqual(locations.count(), 3)

    def test_default_if_empty(self):
        self.assertListEqual([None], self.empty.default_if_empty().to_list())
        six.assertCountEqual(self, _simple, self.simple.default_if_empty().to_list())
        six.assertCountEqual(self, _complex, self.complex.default_if_empty().to_list())

    def test_any(self):
        self.assertFalse(Enumerable.empty().any(lambda x: x == 1))
        self.assertFalse(Enumerable.empty().any())

        self.assertTrue(Enumerable([1, 2, 3]).any(lambda x: x == 1))
        self.assertTrue(Enumerable([1, 2, 3]).any())

        self.assertTrue(Enumerable([{"value": 1}, {"value": 2}, {"value": 3}]).any())
        self.assertFalse(
            Enumerable([{"value": 1}, {"value": 2}, {"value": 3}]).any(
                lambda x: x["value"] < 1
            )
        )
        self.assertTrue(
            Enumerable([{"value": 1}, {"value": 2}, {"value": 3}]).any(
                lambda x: x["value"] >= 1
            )
        )

    def test_contains(self):
        self.assertFalse(self.empty.contains(1))
        self.assertTrue(self.simple.contains(1))
        self.assertTrue(self.complex.select(lambda x: x["value"]).contains(1))

    def test_intersect(self):
        self.assertRaises(TypeError, Enumerable.empty().intersect, [])
        self.assertListEqual([], Enumerable().intersect(Enumerable.empty()).to_list())
        self.assertListEqual(
            [], Enumerable.empty().intersect(Enumerable([1, 2, 3])).to_list()
        )
        self.assertListEqual(
            [1, 2, 3], Enumerable([1, 2, 3]).intersect(Enumerable([1, 2, 3])).to_list()
        )
        self.assertListEqual(
            [2], Enumerable([1, 2, 3]).intersect(Enumerable([2])).to_list()
        )
        self.assertListEqual(
            [],
            Enumerable([1, 2, 3])
            .intersect(
                Enumerable(
                    [
                        {"value": 1},
                        {"value": 2},
                        {"value": 3},
                    ]
                )
            )
            .to_list(),
        )
        self.assertListEqual(
            [
                {"value": 1},
                {"value": 2},
                {"value": 3},
            ],
            Enumerable(
                [
                    {"value": 1},
                    {"value": 2},
                    {"value": 3},
                ]
            )
            .intersect(
                Enumerable(
                    [
                        {"value": 1},
                        {"value": 2},
                        {"value": 3},
                    ]
                )
            )
            .to_list(),
        )
        self.assertListEqual(
            Enumerable(
                [
                    {"value": 1},
                    {"value": 2},
                    {"value": 3},
                ]
            )
            .intersect(Enumerable([{"value": 1}]))
            .to_list(),
            [{"value": 1}],
        )

    def test_except(self):
        self.assertRaises(TypeError, self.empty.except_, [])
        self.assertListEqual([], self.empty.except_(self.empty).to_list())
        self.assertListEqual([], self.empty.except_(self.simple).to_list())
        self.assertListEqual(_simple, self.simple.except_(self.empty).to_list())
        self.assertListEqual([], self.simple.except_(self.simple).to_list())
        self.assertListEqual([1, 3], self.simple.except_(Enumerable([2])).to_list())
        self.assertListEqual(_simple, self.simple.except_(self.complex).to_list())
        self.assertListEqual(_complex, self.complex.except_(self.simple).to_list())
        self.assertListEqual([], self.complex.except_(self.complex).to_list())
        self.assertListEqual(
            [{"value": 2}, {"value": 3}],
            self.complex.except_(Enumerable([{"value": 1}])).to_list(),
        )

    def test_marks_intersect(self):
        marks1 = Enumerable(
            [{"course": "Chemistry", "mark": 90}, {"course": "Biology", "mark": 85}]
        )
        marks2 = Enumerable(
            [
                {"course": "Chemistry", "mark": 65},
                {"course": "Computer Science", "mark": 96},
            ]
        )
        self.assertListEqual(
            [{"course": "Chemistry", "mark": 90}],
            marks1.intersect(marks2, lambda c: c["course"]).to_list(),
        )

    def test_marks_except(self):
        marks1 = Enumerable(
            [{"course": "Chemistry", "mark": 90}, {"course": "Biology", "mark": 85}]
        )
        marks2 = Enumerable(
            [
                {"course": "Chemistry", "mark": 65},
                {"course": "Computer Science", "mark": 96},
            ]
        )
        self.assertListEqual(
            [{"course": "Biology", "mark": 85}],
            marks1.except_(marks2, lambda c: c["course"]).to_list(),
        )

    def test_union(self):
        self.assertListEqual([], self.empty.union(self.empty).to_list())
        self.assertListEqual(
            _simple, self.empty.union(self.simple).order_by(lambda x: x).to_list()
        )
        self.assertListEqual(
            _simple, self.simple.union(self.empty).order_by(lambda x: x).to_list()
        )
        self.assertListEqual(
            _complex,
            self.empty.union(self.complex).order_by(lambda x: x["value"]).to_list(),
        )
        self.assertListEqual(
            _complex,
            self.complex.union(self.empty).order_by(lambda x: x["value"]).to_list(),
        )
        self.assertListEqual(
            _simple + [4, 5],
            self.simple.union(Enumerable([4, 5])).order_by(lambda x: x).to_list(),
        )
        self.assertListEqual(
            _simple + [4, 5],
            self.simple.union(Enumerable([1, 4, 5])).order_by(lambda x: x).to_list(),
        )
        self.assertListEqual(
            _complex + [{"value": 4}, {"value": 5}],
            self.complex.union(
                Enumerable([{"value": 4}, {"value": 5}]), lambda x: x["value"]
            )
            .order_by(lambda x: x["value"])
            .to_list(),
        )
        self.assertListEqual(
            _complex + [{"value": 4}, {"value": 5}],
            self.complex.union(
                Enumerable([{"value": 1}, {"value": 4}, {"value": 5}]),
                lambda x: x["value"],
            )
            .order_by(lambda x: x["value"])
            .order_by(lambda x: x["value"])
            .to_list(),
        )

    def test_join(self):
        self.assertRaises(TypeError, Enumerable.empty().join, [])
        self.assertListEqual([], Enumerable().join(Enumerable()).to_list())
        self.assertListEqual([], Enumerable().join(Enumerable([1, 2, 3])).to_list())
        self.assertListEqual(
            [],
            Enumerable()
            .join(Enumerable([{"value": 1}, {"value": 2}, {"value": 3}]))
            .to_list(),
        )

        self.assertListEqual(
            [(1, 1), (2, 2), (3, 3)],
            Enumerable([1, 2, 3])
            .join(Enumerable([1, 2, 3]))
            .order_by(lambda x: (x[0], x[1]))
            .to_list(),
        )
        self.assertListEqual(
            [(1, 1), (2, 2), (3, 3)],
            Enumerable([1, 2, 3])
            .join(
                Enumerable([{"value": 1}, {"value": 2}, {"value": 3}]),
                inner_key=lambda x: x["value"],
                result_func=lambda x: (x[0], x[1]["value"]),
            )
            .order_by(lambda x: (x[0], x[1]))
            .to_list(),
        )

        self.assertListEqual(
            [(1, 1), (2, 2), (3, 3)],
            Enumerable([{"value": 1}, {"value": 2}, {"value": 3}])
            .join(
                Enumerable([{"value": 1}, {"value": 2}, {"value": 3}]),
                result_func=lambda x: (x[0]["value"], x[1]["value"]),
            )
            .order_by(lambda x: (x[0], x[1]))
            .to_list(),
        )

    def test_group_join(self):
        self.assertRaises(TypeError, Enumerable.empty().group_join, [])
        self.assertListEqual([], Enumerable().group_join(Enumerable()).to_list())

        simple_empty_gj = Enumerable([1, 2, 3]).group_join(self.empty)
        self.assertListEqual([], simple_empty_gj.to_list())

        complex_simple_gj = Enumerable(
            [{"value": 1}, {"value": 2}, {"value": 3}]
        ).group_join(Enumerable([1, 2, 3, 3]), outer_key=lambda x: x["value"])
        self.assertListEqual(
            [({"value": 1}, [1]), ({"value": 2}, [2]), ({"value": 3}, [3, 3])],
            complex_simple_gj.select(lambda g: (g[0], g[1].to_list())).to_list(),
        )

        simple_gj = Enumerable([1, 2, 3]).group_join(
            Enumerable([2, 3]),
            result_func=lambda x: {"number": x[0], "collection": x[1].to_list()},
        )
        self.assertEqual(2, simple_gj.count())
        self.assertListEqual(
            [
                {"number": 2, "collection": [2]},
                {"number": 3, "collection": [3]},
            ],
            simple_gj.to_list(),
        )

    def test_then_by(self):
        locations = Enumerable(_locations)
        self.assertRaises(
            NullArgumentError, locations.order_by(lambda l: l[0]).then_by, None
        )
        self.assertListEqual(
            [
                u"Liverpool, England",
                u"Liverpool, England",
                u"London, England",
                u"London, England",
                u"London, England",
                u"Manchester, England",
                u"Manchester, England",
                u"Edinburgh, Scotland",
                u"Glasgow, Scotland",
                u"Glasgow, Scotland",
                u"Bangor, Wales",
                u"Cardiff, Wales",
                u"Cardiff, Wales",
            ],
            locations.order_by(lambda l: l[0])
            .then_by(lambda l: l[1])
            .select(lambda l: u"{0}, {1}".format(l[1], l[0]))
            .to_list(),
        )

    def test_then_by_descending(self):
        locations = Enumerable(_locations)
        self.assertListEqual(
            [
                u"Liverpool, England: 29700",
                u"Liverpool, England: 25000",
                u"London, England: 90000",
                u"London, England: 80000",
                u"London, England: 70000",
                u"Manchester, England: 50000",
                u"Manchester, England: 45600",
                u"Edinburgh, Scotland: 20000",
                u"Glasgow, Scotland: 12500",
                u"Glasgow, Scotland: 12000",
                u"Bangor, Wales: 12800",
                u"Cardiff, Wales: 30000",
                u"Cardiff, Wales: 29700",
            ],
            locations.order_by(lambda l: l[0])
            .then_by(lambda l: l[1])
            .then_by_descending(lambda l: l[3])
            .select(lambda l: u"{0}, {1}: {2}".format(l[1], l[0], l[3]))
            .to_list(),
        )

    def reverse(self, result, element):
        return element + " " + result

    def sum(self, result, element):
        return result + element

    def test_aggregate(self):
        words = u"the quick brown fox jumps over the lazy dog".split(" ")
        self.assertListEqual(
            words,
            ["the", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog"],
        )
        test = Enumerable(words).aggregate(self.reverse)
        self.assertEqual(test, "dog lazy the over jumps fox brown quick the")

        self.assertEqual(0, Enumerable().aggregate(lambda x: x[0] + x[1], 0))

        test = self.simple.aggregate(self.sum, seed=0)
        self.assertEqual(test, 6)

    def test_all(self):
        test = Enumerable([1, 1, 1]).all(lambda x: x == 1)
        self.assertTrue(test)

        test = Enumerable([]).all(lambda x: x == 1)
        self.assertTrue(test)

        test = self.simple.all(lambda x: x == 1)
        self.assertFalse(test)

    def test_append(self):
        test = self.simple.append(4)
        self.assertEqual(test.count(), 4)
        self.assertEqual(test.element_at(3), 4)

    def test_prepend(self):
        test = self.simple.prepend(4)
        self.assertEqual(test.count(), 4)
        self.assertEqual(test.element_at(0), 4)

    def test_empty(self):
        test = Enumerable.empty()
        self.assertIsInstance(test, Enumerable)
        self.assertEqual(test.count(), 0)

    def test_range(self):
        test = Enumerable.range(1, 3)
        self.assertEqual(test.count(), 3)
        self.assertListEqual(self.simple.to_list(), test.to_list())

    def test_repeat(self):
        test = Enumerable.repeat(u"Z", 10)
        self.assertEqual(10, test.count())
        self.assertEqual(u"ZZZZZZZZZZ", u"".join(test.to_list()))

    def test_reverse(self):
        test = self.empty.reverse()
        self.assertListEqual(test.to_list(), [])

        test = self.simple.reverse()
        self.assertListEqual(test.to_list(), [3, 2, 1])
        self.assertEqual(3, test.count())

        words = u"the quick brown fox jumps over the lazy dog".split(" ")
        self.assertListEqual(
            words,
            ["the", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog"],
        )
        test = Enumerable(words).reverse()
        self.assertEqual(
            u" ".join(test.to_list()), u"dog lazy the over jumps fox brown quick the"
        )

    def test_skip_last(self):
        test = Enumerable([1, 2, 3, 4, 5]).skip_last(2)
        self.assertListEqual([1, 2, 3], test.to_list())

        test = Enumerable(["one", "two", "three", "four", "five"]).skip(1).skip_last(1)
        self.assertListEqual(test.to_list(), ["two", "three", "four"])

    def test_skip_while(self):
        test = Enumerable([1, 4, 6, 4, 1]).skip_while(lambda x: x < 5)
        self.assertListEqual([6, 4, 1], test.to_list())

        test = Enumerable([]).skip_while(lambda x: x < 5)
        self.assertListEqual([], test.to_list())

    def test_take_last(self):
        test = Enumerable([1, 2, 3, 4, 5]).take_last(2)
        self.assertListEqual(test.to_list(), [4, 5])

        test = Enumerable(["one", "two", "three", "four", "five"]).take(3).take_last(1)
        self.assertListEqual(test.to_list(), ["three"])

    def test_take_while(self):
        test = Enumerable([1, 4, 6, 4, 1]).take_while(lambda x: x < 5)
        self.assertListEqual(test.to_list(), [1, 4])

        test = Enumerable([]).skip_while(lambda x: x < 5)
        self.assertListEqual(test.to_list(), [])

    def test_zip(self):
        test = Enumerable(["A", "B", "C", "D"]).zip(
            Enumerable(["x", "y"]), lambda t: "{0}{1}".format(t[0], t[1])
        )
        self.assertListEqual(test.to_list(), ["Ax", "By"])
Esempio n. 5
0
def claim_loot(event, context):
    """ Allows a character to claim the loot from their fight """
    logger.info("Claim requested")
    connection_id = _get_connection_id(event)

    try:
        body = _get_body(event)

        for attribute in ['char_id', 'fight_id']:
            if attribute not in body:
                logger.debug(f'failed: {attribute} not in message')
                return _get_response(400, f'{attribute} not in message')

        char_id = body['char_id']
        fight_id = body['fight_id']

        fight = _get_fight(fight_id)

        if 'id' not in fight:
            raise Exception('Fight is missing')

        characters = Enumerable(fight['characters'])

        # check for the character in the fight
        char = characters.first_or_default(lambda c: c['id'] == char_id)

        if char is None:
            raise Exception('The character specified was not in the fight')

        loot_item_id = char.get('loot_item_id', None)

        if loot_item_id is None:
            raise Exception('There was no loot for the character')

        # get the item
        item = _get_item(loot_item_id)

        add_result = _char_add_item(char_id, item)

        if add_result >= 400:
            raise Exception('Could not add the loot to the character')

        mark_result = _mark_loot_claimed(fight_id, char_id)

        if mark_result >= 400:
            raise Exception('Could not mark the loot claimed')

        c_data = {
            'message': 'LOOT_CLAIMED',
            'fight_id': fight_id,
            'char_id': char_id,
            'item_id': item['id']
        }

        _send_to_connection(connection_id, c_data, event)

        return _get_response(200, 'Loot claimed')
    except Exception as ex:
        logger.error(ex)
        c_data = {'message': 'LOOT_CLAIMED_ERROR'}
        _send_to_connection(connection_id, c_data, event)
        return _get_response(500, ex)
Esempio n. 6
0
class IssueTests(TestCase):
    def setUp(self):
        self.empty = Enumerable(_empty)
        self.simple = Enumerable(_simple)
        self.complex = Enumerable(_complex)

    def test_issue19_1(self):
        foo = Enumerable([1])
        bar = Enumerable([1])
        self.assertEqual(foo.intersect(bar).count(), 1)

    def test_issue19_2(self):
        foo = Enumerable([1])
        bar = Enumerable([1]).distinct()
        self.assertEqual(foo.intersect(bar).count(), 1)

    def test_issue19_3(self):
        foo = Enumerable([1]).distinct()
        bar = Enumerable([1])
        self.assertEqual(foo.intersect(bar).count(), 1)

    def test_issue22(self):
        def my_iter():
            for i in range(10):
                yield i

        def low_iter():
            for i in range(5):
                yield i

        def high_iter():
            for k in range(5):
                yield k + 5

        data = my_iter()
        a = Enumerable(data)

        low = a.where(lambda x: x < 5)
        high = a.where(lambda x: x >= 5)

        self.assertListEqual(
            [(0, 5), (1, 6), (2, 7), (3, 8), (4, 9)], low.zip(high).to_list()
        )

        self.assertListEqual(
            [(0, 5), (1, 6), (2, 7), (3, 8), (4, 9)], list(zip(low, high))
        )

    def test_generator_to_Enumerable(self):
        def first_3():
            for i in range(3):
                yield i

        p2 = Enumerable(first_3())
        self.assertListEqual([0, 1, 2], p2.to_list())

        p3 = Enumerable((i for i in first_3()))
        self.assertListEqual([0, 1, 2], p3.to_list())

    def test_issue22_join(self):
        class Val(object):
            def __init__(self, number, power):
                self.number = number
                self.power = power

            def __str__(self):
                return "VAL {0}: {1}".format(self.number, self.power)

        def powers_of_2():
            for i in range(2):
                yield Val(i, 2 ** i)

        def powers_of_10():
            for i in range(2):
                yield Val(i, 10 ** i)

        en2 = Enumerable(powers_of_2())
        en10 = Enumerable(powers_of_10())
        joined = en2.join(
            en10,
            lambda x: x.number,
            lambda y: y.number,
            lambda r: (r[0].power, r[1].power),
        )
        truth = zip([2 ** i for i in range(2)], [10 ** y for y in range(2)])
        self.assertListEqual(list(truth), joined.to_list())

    def test_first_with_lambda(self):
        self.assertRaises(IndexError, self.empty.first, lambda x: x == 0)
        self.assertEqual(2, self.simple.first(lambda x: x == 2))
        self.assertDictEqual(
            {"value": 2}, self.complex.first(lambda x: x["value"] == 2)
        )

    def test_first_or_default_with_lambda(self):
        self.assertIsNone(self.empty.first_or_default(lambda x: x == 0))
        self.assertEqual(
            self.simple.first(lambda x: x == 2),
            self.simple.first_or_default(lambda x: x == 2),
        )
        self.assertEqual(
            self.complex.first(lambda x: x["value"] == 2),
            self.complex.first_or_default(lambda x: x["value"] == 2),
        )

    def test_last_with_lambda(self):
        self.assertRaises(IndexError, self.empty.last, lambda x: x == 0)
        self.assertEqual(2, self.simple.last(lambda x: x == 2))
        self.assertDictEqual({"value": 2}, self.complex.last(lambda x: x["value"] == 2))
        self.assertEqual(
            self.simple.first(lambda x: x == 2), self.simple.last(lambda x: x == 2)
        )

    def test_last_or_default_with_lambda(self):
        self.assertIsNone(self.empty.last_or_default(lambda x: x == 0))
        self.assertEqual(
            self.simple.last(lambda x: x == 2),
            self.simple.last_or_default(lambda x: x == 2),
        )
        self.assertEqual(
            self.complex.last(lambda x: x["value"] == 2),
            self.complex.last_or_default(lambda x: x["value"] == 2),
        )
        self.assertEqual(
            self.simple.first_or_default(lambda x: x == 2),
            self.simple.last_or_default(lambda x: x == 2),
        )

    def test_issue_34(self):
        class Obj(object):
            def __init__(self, n, v):
                self.n = n
                self.v = v

        foo = Enumerable([Obj("foo", 1), Obj("bar", 2)])
        self.assertTrue(foo.any(lambda x: x.n == "foo"))
        self.assertTrue(foo.any(lambda x: x.n == "foo"))
        filtered_foo = foo.where(lambda x: x.n == "foo")
        self.assertIsNotNone(filtered_foo.first())
        self.assertEqual("foo", filtered_foo.first().n)
        self.assertTrue(filtered_foo.any(lambda x: x.v == 1))
        self.assertTrue(filtered_foo.any(lambda x: x.v == 1))

    def test_issue_35(self):
        a = Enumerable([9, 8, -7, 6, 5])
        b = a.order_by(lambda x: x)
        self.assertEqual(-7, b.first())
        self.assertEqual(-7, list(b)[0])
        self.assertEqual(-7, b.first())

    def test_issue_36(self):
        def append_to_list(lst, element):
            lst.append(element)

        filepath = os.path.join(os.getcwd(), "tests", "files", "test_file1.txt")
        result = []
        with io.open(filepath) as f:
            lines = (
                Enumerable(f)
                .skip(1)
                .where(lambda l: not l.startswith("#"))
                .aggregate(append_to_list, result)
            )
        self.assertEqual(1, len(result))
        self.assertEqual("This line should be counted", result[0])
Esempio n. 7
0
def handler(event, context):
    logger.debug(f'Event received: {json.dumps(event)}')
    char_id = event['pathParameters']['id']

    request = {'pathParameters': {'id': char_id}}

    invoke_response = lambda_client.invoke(FunctionName=char_lambda,
                                           InvocationType='RequestResponse',
                                           Payload=json.dumps(request))

    data = json.loads(invoke_response.get('Payload').read())

    data = json.loads(data['body'])

    char_inventory = data['inventory']
    inventory = []
    items_data = []

    request = {
        'queryStringParameters': {
            'player_class': int(data['player_class']),
        }
    }

    invoke_response = lambda_client.invoke(FunctionName=item_lambda,
                                           InvocationType='RequestResponse',
                                           Payload=json.dumps(request))

    item_data = json.loads(invoke_response.get('Payload').read())
    item_data = json.loads(item_data.get('body'))

    #items_data.append(item_data)
    #print(len(item_data))

    items = Enumerable(item_data['items'])
    print(items.count())
    for inv_item in char_inventory:
        item_id = inv_item['id']
        item = items.first_or_default(lambda x: x['id'] == item_id)

        if not item:
            continue

        item = {
            'id': inv_item['id'],
            'inv_id': inv_item.get('inv_id', ''),
            'equipped': inv_item['equipped'],
            'stamina': item['stamina'],
            'damage': item['damage'],
            'crit_chance': item['crit_chance'],
            'name': item['name'],
            'description': item['description'],
            'quality': item['quality'],
            'quality_name': item['quality_name'],
            'slot': item['slot'],
            'slot_name': item['slot_name'],
            'level': item['level'],
            # 'is_archer': item['is_archer'],
            # 'is_warrior': item['is_warrior'],
            # 'is_rogue': item['is_rogue'],
            # 'is_sorcerer': item['is_sorcerer']
        }

        inventory.append(item)

    data['inventory'] = inventory

    response = {
        'statusCode': 200,
        'body': json.dumps(data),
        'headers': {
            'Access-Control-Allow-Origin': '*'
        }
    }

    return response
Esempio n. 8
0
def handler(event, context):
    logger.debug(f'Event received')

    try:
        fight_id = event['pathParameters']['id']
        data = json.loads(event.get('body'))

        fight = FightModel.get(fight_id)

        if fight is None:
            raise Exception(f'No fight found for id:{fight_id}')

        loot_list = Enumerable(data)

        for char in fight.characters:
            c_loot = loot_list.first_or_default(
                lambda x: x['char_id'] == char.id)

            if c_loot is None:
                continue

            char.loot_item_id = c_loot['item_id']
            char.loot_claimed = False

        fight.save()

        response = {
            'statusCode': 200,
            'body': json.dumps(fight, cls=ModelEncoder),
            'headers': {
                'Access-Control-Allow-Origin': '*'
            }
        }

        logger.debug(f'Response: {json.dumps(response)}')

        return response

    except Exception as e:
        if hasattr(e, 'message'):
            logger.error(f'Error: {e.message}')
        else:
            logger.error(e)

        return {
            'statusCode': 500,
            'body': json.dumps({'error': 'Could not create loot.'})
        }


# if __name__ == "__main__":
#     from uuid import uuid4

#     if not FightModel.exists():
#         FightModel.create_table(read_capacity_units=5,
#                                 write_capacity_units=100,
#                                 wait=True)

#     from create import create as create_fight

#     characters = [
#             { "id":"1", "attack_speed":1600, "crit_chance": 0.17, "curr_hp": 1000, "min_damage":55, "max_damage": 128 },
#             { "id":"2", "attack_speed":1500, "crit_chance": 0.27, "curr_hp": 1000, "min_damage":75, "max_damage": 168 },
#             { "id":"3", "attack_speed":2700, "crit_chance": 0.29, "curr_hp": 1000, "min_damage":85, "max_damage": 228 },
#             { "id":"4", "attack_speed":1800, "crit_chance": 0.25, "curr_hp": 1000, "min_damage":45, "max_damage": 101 },
#             { "id":"5", "attack_speed":2100, "crit_chance": 0.24, "curr_hp": 1000, "min_damage":65, "max_damage": 128 }
#         ]

#     fight_req = {
#         "enemy": {
#             "id": "111",
#             "can_block": True,
#             "can_dodge": True,
#             "block_pct": 0.05,
#             "block_amt": 0.51,
#             "dodge_pct": 0.07,
#             "hit_points": 3000
#         },
#         "characters": characters
#     }

#     fight_req = {
#         'body': json.dumps(fight_req)
#     }

#     fight_response = create_fight(fight_req, None)

#     # print(fight_response)

#     fight_data = json.loads(fight_response.get('body'))

#     fight_id = fight_data['id']

#     c_loot = []
#     for c in characters:
#         loot_i = {
#             'char_id': c.get('id'),
#             'item_id': str(uuid4())
#         }

#         c_loot.append(loot_i)

#     cr_loot_request = {
#         'pathParameters': {
#             'id': fight_id
#         },
#         'body': json.dumps(c_loot)
#     }

#     response = handler(cr_loot_request, None)

#     print(response)