Ejemplo n.º 1
0
    def test_list_receipt(self):
        """Method to test receipt index"""
        donation_table = DynamoTable('donations')
        receipt_id = "asdf1234"

        existing_receipts = donation_table.query_hash("receipt_id",
                                                      receipt_id,
                                                      index="ReceiptIndex",
                                                      limit=10)
        assert not existing_receipts

        # Add a record
        data = {
            "campaign_id": "my_campaign",
            "donation_on": arrow.utcnow().isoformat(),
            "donator_name": "John Doeski",
            "donator_email": "*****@*****.**",
            "donation_cents": 1000,
            "receipt_id": receipt_id,
            "email_bucket": "my_bucket",
            "email_key": "key1"
        }
        donation_table.put_item(data)

        existing_receipts = donation_table.query_hash("receipt_id",
                                                      receipt_id,
                                                      index="ReceiptIndex",
                                                      limit=10)

        assert len(existing_receipts) == 1
    def test_complex_campaign(self):
        """Method to test a more complex campaign with donors"""
        data = {
            "charity_id": "aclu",
            "campaigner_name": "John Doeski2",
            "campaigner_email": "*****@*****.**",
            "match_cents": 2500000
        }
        rv = self.app.post('/campaign', data=data, follow_redirects=True)

        self.assertEqual(rv.status_code, 201)
        response = json.loads(rv.data)
        campaign_id = response["campaign_id"]

        # Add some donors
        dontation_table = DynamoTable('donations')

        donations = []
        for x in range(0, 7):
            donation = {
                "campaign_id": campaign_id,
                "donation_on": arrow.utcnow().isoformat(),
                "donor_name": "Friend {}".format(x),
                "donor_email": "friend{}@gmail.com".format(x),
                "donation_cents": 400000 - (25000 * x),
                "email_object": "https://s3.aws.com/somghasd"
            }
            dontation_table.put_item(donation)
            donations.append(donation)
            time.sleep(1)

        # Get item
        rv = self.app.get('/campaign/{}'.format(campaign_id),
                          follow_redirects=True)
        self.assertEqual(rv.status_code, 200)
        response = json.loads(rv.data)
        self.assertEqual(response["charity_id"], data["charity_id"])
        self.assertEqual(response["campaigner_name"], data["campaigner_name"])
        self.assertEqual(response["campaigner_email"],
                         data["campaigner_email"])
        self.assertEqual(response["match_cents"], data["match_cents"])
        self.assertEqual(response["notified_on"], response["notified_on"])

        for donor, x in zip(response["large_donors"], range(0, 5)):
            self.assertEqual(donor["donor_name"], "Friend {}".format(x))

        for donor, x in zip(response["recent_donors"], range(6, 1, -1)):
            self.assertEqual(donor["donor_name"], "Friend {}".format(x))

        self.assertEqual(response["donation_total_cents"], 2275000)
Ejemplo n.º 3
0
    def test_list_unrelated_receipts(self):
        """Method to test receipt index"""
        donation_table = DynamoTable('donations')

        # Add a record
        data = {
            "campaign_id": "my_campaign",
            "donation_on": arrow.utcnow().isoformat(),
            "donator_name": "John Doeski",
            "donator_email": "*****@*****.**",
            "donation_cents": 1000,
            "receipt_id": "alsdf3234",
            "email_bucket": "my_bucket",
            "email_key": "key1"
        }
        donation_table.put_item(data)

        data["receipt_id"] = "adsfghdfg"
        donation_table.put_item(data)

        data["receipt_id"] = "hjydfgsdfg"
        donation_table.put_item(data)

        existing_receipts = donation_table.query_hash("receipt_id",
                                                      "jfghghjf",
                                                      index="ReceiptIndex",
                                                      limit=10)

        assert not existing_receipts
Ejemplo n.º 4
0
    def test_scan_table(self):
        """Method to test scanning a table"""
        def scan_func(items, input_val):
            for item in items:
                if item["campaign_status"]["S"] == "complete":
                    input_val['count'] += 1
            return input_val

        campaign_table = DynamoTable('campaigns')

        # Add a record
        for idx in range(0, 10):
            data = {
                "campaign_id": "my_campaign_{}".format(idx),
                "notified_on": arrow.utcnow().isoformat(),
                "campaign_status": "complete"
            }
            campaign_table.put_item(data)

        # Scan table
        result = {"count": 0}
        campaign_table.scan_table(scan_func, result, "campaign_status")

        self.assertEqual(result["count"], 10)
Ejemplo n.º 5
0
    def test_delete_item(self):
        """Method to test receipt index"""
        campaign_table = DynamoTable('campaigns')

        # Add a record
        data = {
            "campaign_id": "my_campaign",
            "notified_on": arrow.utcnow().isoformat(),
            "campaign_status": "active"
        }
        campaign_table.put_item(data)

        # Verify write
        key = {"campaign_id": "my_campaign"}
        item = campaign_table.get_item(key)
        assert item is not None
        self.assertEqual(item["campaign_status"], "active")

        # Delete
        campaign_table.delete_item(key)

        # Verify it deleted
        item = campaign_table.get_item(key)
        assert item is None
Ejemplo n.º 6
0
    def test_stats(self):
        """Method to test stats endpoint"""
        rv = self.app.get('/stats', follow_redirects=True)
        self.assertEqual(rv.status_code, 200)
        response = json.loads(rv.data)
        self.assertEqual(response["campaign_count"], 0)
        self.assertEqual(response["donation_count"], 0)
        self.assertEqual(response["total_donation_cents"], 0)

        data = {
            "charity_id": "aclu",
            "campaigner_name": "John Doeski",
            "campaigner_email": "*****@*****.**",
            "match_cents": 5000
        }
        for idx in range(0, 15):
            rv = self.app.post('/campaign', data=data, follow_redirects=True)
            self.assertEqual(rv.status_code, 201)
        response = json.loads(rv.data)

        # Add some cancelled and matched campaignes
        campaign_table = DynamoTable('campaigns')

        for x in range(0, 4):
            camp = {
                "campaign_id": shortuuid.uuid(),
                "notified_on": arrow.utcnow().isoformat(),
                "campaign_status": "cancelled",
                "match_cents": 20000
            }
            campaign_table.put_item(camp)

        for x in range(0, 2):
            camp = {
                "campaign_id": shortuuid.uuid(),
                "notified_on": arrow.utcnow().isoformat(),
                "campaign_status": "matched",
                "match_cents": 20000
            }
            campaign_table.put_item(camp)

        # Add some donations
        dontation_table = DynamoTable('donations')
        donations = []
        for x in range(0, 7):
            donation = {
                "campaign_id": response["campaign_id"],
                "donation_on": arrow.utcnow().isoformat(),
                "donor_name": "Friend {}".format(x),
                "donor_email": "friend{}@gmail.com".format(x),
                "donation_cents": 20000
            }
            dontation_table.put_item(donation)
            donations.append(donation)

        rv = self.app.get('/stats', follow_redirects=True)
        self.assertEqual(rv.status_code, 200)
        response = json.loads(rv.data)

        self.assertEqual(response["campaign_count"], 21)
        self.assertEqual(response["campaign_active_count"], 15)
        self.assertEqual(response["campaign_matched_count"], 2)
        self.assertEqual(response["campaign_cancelled_count"], 4)
        self.assertEqual(response["campaign_total_cents"], 115000)
        self.assertEqual(response["donation_count"], 7)
        self.assertEqual(response["total_donation_cents"], 140000)
Ejemplo n.º 7
0
class Campaign(Resource):
    def __init__(self):
        super(Resource, self).__init__()
        self.table = DynamoTable('campaigns')

    @swagger.operation(notes='Service to create a new campaign',
                       nickname='Create a Campaign',
                       parameters=[{
                           "name":
                           "charity_id",
                           "description":
                           "Identifier of charity. Supported: {}".format(
                               ", ".join(
                                   [c["id"] for c in SUPPORTED_CHARITIES])),
                           "required":
                           True,
                           "allowMultiple":
                           False,
                           "dataType":
                           'string',
                           "paramType":
                           "query"
                       }, {
                           "name": "campaigner_name",
                           "description": "Campaigner's name",
                           "required": True,
                           "allowMultiple": False,
                           "dataType": 'string',
                           "paramType": "query"
                       }, {
                           "name": "campaigner_email",
                           "description": "Campaigner's email",
                           "required": True,
                           "allowMultiple": False,
                           "dataType": 'string',
                           "paramType": "query"
                       }, {
                           "name": "match_cents",
                           "description": "Target amount to match in cents",
                           "required": True,
                           "allowMultiple": False,
                           "dataType": 'integer',
                           "paramType": "query"
                       }])
    def post(self):
        """Create a Campaign"""
        args = story_post_parser.parse_args()

        # Verify charity is supported
        if args["charity_id"] not in [c["id"] for c in SUPPORTED_CHARITIES]:
            abort(400,
                  description="Unsupported charity: {}".format(
                      args["charity_id"]))

        # Create campaign id
        while True:
            u = uuid.uuid4()
            s = shortuuid.encode(u)[:5]
            if not self.table.get_item({"campaign_id": s}):
                break
        printable = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
        name_str = filter(lambda x: x in printable,
                          args["campaigner_name"].strip().lower())
        name_str = name_str.replace(" ", "-")

        args["campaign_id"] = "{}-{}".format(name_str, s)
        args["campaigner_name"] = args["campaigner_name"].strip()
        args["campaigner_email"] = args["campaigner_email"].strip()
        args["campaign_status"] = "active"
        args['notified_on'] = arrow.utcnow().isoformat()
        args['created_on'] = arrow.utcnow().isoformat()
        args['secret_id'] = shortuuid.uuid()
        args['charity_id'] = args["charity_id"]

        # Put the object
        self.table.put_item(args)

        # Notify the matcher
        dm_email = DonatematesEmail(
            campaigner_address=args["campaigner_email"])
        dm_email.send_campaign_created(args["campaign_id"], args["secret_id"])

        # Return
        return {"campaign_id": args["campaign_id"]}, 201