id
int64
0
843k
repository_name
stringlengths
7
55
file_path
stringlengths
9
332
class_name
stringlengths
3
290
human_written_code
stringlengths
12
4.36M
class_skeleton
stringlengths
19
2.2M
total_program_units
int64
1
9.57k
total_doc_str
int64
0
4.2k
AvgCountLine
float64
0
7.89k
AvgCountLineBlank
float64
0
300
AvgCountLineCode
float64
0
7.89k
AvgCountLineComment
float64
0
7.89k
AvgCyclomatic
float64
0
130
CommentToCodeRatio
float64
0
176
CountClassBase
float64
0
48
CountClassCoupled
float64
0
589
CountClassCoupledModified
float64
0
581
CountClassDerived
float64
0
5.37k
CountDeclInstanceMethod
float64
0
4.2k
CountDeclInstanceVariable
float64
0
299
CountDeclMethod
float64
0
4.2k
CountDeclMethodAll
float64
0
4.2k
CountLine
float64
1
115k
CountLineBlank
float64
0
9.01k
CountLineCode
float64
0
94.4k
CountLineCodeDecl
float64
0
46.1k
CountLineCodeExe
float64
0
91.3k
CountLineComment
float64
0
27k
CountStmt
float64
1
93.2k
CountStmtDecl
float64
0
46.1k
CountStmtExe
float64
0
90.2k
MaxCyclomatic
float64
0
759
MaxInheritanceTree
float64
0
16
MaxNesting
float64
0
34
SumCyclomatic
float64
0
6k
6,300
ArabellaTech/aa-stripe
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/ArabellaTech_aa-stripe/aa_stripe/serializers.py
aa_stripe.serializers.StripeCouponSerializer.Meta
class Meta: model = StripeCoupon fields = [ "coupon_id", "amount_off", "currency", "duration", "duration_in_months", "livemode", "max_redemptions", "metadata", "percent_off", "redeem_by", "times_redeemed", "valid", "is_created_at_stripe", "created", "updated", "is_deleted" ]
class Meta: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
7
0
7
3
6
0
3
3
2
0
0
0
0
6,301
ArabellaTech/aa-stripe
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/ArabellaTech_aa-stripe/tests/test_customers.py
tests.test_customers.TestRefreshCustomersCommand
class TestRefreshCustomersCommand(BaseTestCase): def setUp(self): self._create_customer(is_active=False, is_created_at_stripe=False) self.active_customer = self._create_customer() @requests_mock.Mocker() def test_command(self, m): def get_customer_data(customer_id, sources, default_source=None): return { "id": customer_id, "object": "customer", "sources": { "object": "list", "data": sources, "has_more": False, "total_count": 1, "url": "/v1/customers/{}/sources".format(customer_id), }, "default_source": default_source, } stripe_response_part1 = { "object": "list", "url": "/v1/customers", "has_more": True, "data": [get_customer_data("cus_xyz", [{"id": "card_1"}], default_source="card_1")], } stripe_response_part2 = { "object": "list", "url": "/v1/customers", "has_more": False, "data": [get_customer_data("cus_b", [{"id": "card_2"}])], } m.register_uri("GET", "https://api.stripe.com/v1/customers", text=json.dumps(stripe_response_part1)) m.register_uri( "GET", "https://api.stripe.com/v1/customers?starting_after=cus_xyz", [ # make sure the command will try again {"text": "", "status_code": 500}, {"text": json.dumps(stripe_response_part2), "status_code": 200}, ], ) call_command("refresh_customers", verbosity=2) self.active_customer.refresh_from_db() self.assertEqual( self.active_customer.default_source_data, {"id": "card_1"}) # the command should fail if call to api fails more than 5 times with mock.patch("stripe.Customer.list") as mocked_list: mocked_list.side_effect = stripe.error.APIError() with self.assertRaises(stripe.error.APIError): call_command("refresh_customers") @requests_mock.Mocker() def test_customer_refresh_from_stripe(self, m): self._create_customer() api_url = "https://api.stripe.com/v1/customers/cus_xyz" api_response = { "id": "cus_xyz", "object": "customer", "account_balance": 0, "created": 1476810921, "currency": "usd", "default_source": "card_xyz", "delinquent": False, "description": None, "discount": None, "email": None, "livemode": False, "metadata": {}, "shipping": None, "sources": { "object": "list", "data": [{"id": "card_xyz", "object": "card"}], "has_more": False, "total_count": 1, "url": "/v1/customers/cus_xyz/sources", }, "subscriptions": { "object": "list", "data": [], "has_more": False, "total_count": 0, "url": "/v1/customers/cus_xyz/subscriptions", }, } m.register_uri("GET", api_url, text=json.dumps(api_response)) self.customer.refresh_from_stripe() self.assertEqual(self.customer.sources, [ {"id": "card_xyz", "object": "card"}]) self.assertEqual(self.customer.default_source, "card_xyz") def test_get_default_source(self): self._create_customer() self.customer.sources = [{"id": "card_abc"}, {"id": "card_xyz"}] self.customer.save() self.assertIsNone(self.customer.default_source_data) self.customer.default_source = "card_xyz" self.customer.save() self.assertEqual(self.customer.default_source_data, {"id": "card_xyz"})
class TestRefreshCustomersCommand(BaseTestCase): def setUp(self): pass @requests_mock.Mocker() def test_command(self, m): pass def get_customer_data(customer_id, sources, default_source=None): pass @requests_mock.Mocker() def test_customer_refresh_from_stripe(self, m): pass def test_get_default_source(self): pass
8
0
21
1
20
0
1
0.02
1
0
0
0
4
1
4
8
99
6
92
14
84
2
34
11
28
1
2
2
5
6,302
ArabellaTech/aa-stripe
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/ArabellaTech_aa-stripe/aa_stripe/serializers.py
aa_stripe.serializers.StripeCustomerSerializer.Meta
class Meta: model = StripeCustomer fields = ["stripe_js_response"]
class Meta: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
3
0
3
3
2
0
3
3
2
0
0
0
0
6,303
ArabellaTech/aa-stripe
ArabellaTech_aa-stripe/tests/test_settings.py
tests.test_settings.TestSettings
class TestSettings(TestCase): def test_defaults(self): self.assertEqual(stripe_settings.PENDING_WEBHOOKS_THRESHOLD, 20)
class TestSettings(TestCase): def test_defaults(self): pass
2
0
2
0
2
0
1
0
1
0
0
0
1
0
1
1
3
0
3
2
1
0
3
2
1
1
1
0
1
6,304
ArabellaTech/aa-stripe
ArabellaTech_aa-stripe/tests/test_customers.py
tests.test_customers.TestCustomerDetailsAPI
class TestCustomerDetailsAPI(BaseTestCase): def setUp(self): self._create_user() self.second_user = self._create_user(email="second@user.com", set_self=False) self._create_customer( user=self.user, customer_id="cus_xyz", sources=[{"id": "card_1"}], default_source="card_1" ) self.url = reverse("stripe-customer-details", args=["cus_xyz"]) def test_api(self): # other user should not be able to update other user's customer self.client.force_authenticate(user=self.second_user) response = self.client.get(self.url) self.assertEqual(response.status_code, 404) self.client.force_authenticate(user=self.user) response = self.client.get(self.url) self.assertEqual(response.status_code, 200) self.assertEqual( response.data, { "id": self.customer.id, "user": self.user.id, "stripe_customer_id": "cus_xyz", "is_active": True, "sources": [{"id": "card_1"}], "default_source": "card_1", "default_source_data": {"id": "card_1"}, }, ) response = self.client.patch(self.url, {}, format="json") self.assertEqual(response.status_code, 400) self.assertEqual(response.data, {"stripe_js_response": ["This field is required."]}) # test changing card with incorrect data data = {"stripe_js_response": {"card": {}}} response = self.client.patch(self.url, data, format="json") self.assertEqual(response.status_code, 400) self.assertEqual(response.data, {"stripe_js_response": ["This field must contain JSON data from Stripe JS."]}) # test adding new default card # customer response after update stripe_customer_response = { "id": "cus_xyz", "object": "customer", "created": 1476810921, "default_source": "card_2", "sources": { "object": "list", "data": [{"id": "card_1", "object": "card"}, {"id": "card_2", "object": "card"}], "has_more": False, "total_count": 1, "url": "/v1/customers/cus_xyz/sources", }, } stripe_js_response = { "id": "tok_193mTaHSTEMJ0IPXhhZ5vuTX", "card": { "id": "card_2", "object": "card", "brand": "Visa", "exp_month": 8, "exp_year": 2017, "last4": "4242", }, } data["stripe_js_response"] = stripe_js_response api_url = "https://api.stripe.com/v1/customers/cus_xyz" with requests_mock.Mocker() as m: m.register_uri("GET", api_url, text=json.dumps(stripe_customer_response)) m.register_uri( "POST", api_url, [ { "status_code": 400, "text": json.dumps( { "error": { "message": "Some error.", "type": "customer_error", "param": "", "code": "error", } } ), }, {"status_code": 200, "text": json.dumps(stripe_customer_response)}, ], ) # test in case of error from Stripe response = self.client.patch(self.url, data, format="json") self.assertEqual(response.status_code, 400) self.assertEqual(response.data, {"stripe_error": "Some error."}) response = self.client.patch(self.url, data, format="json") self.assertEqual(response.status_code, 200) self.assertEqual(dict(response.data["default_source_data"]), {"id": "card_2", "object": "card"})
class TestCustomerDetailsAPI(BaseTestCase): def setUp(self): pass def test_api(self): pass
3
0
49
3
44
3
1
0.06
1
1
0
0
2
3
2
6
99
6
88
12
85
5
34
10
31
1
2
1
2
6,305
ArabellaTech/aa-stripe
ArabellaTech_aa-stripe/tests/test_customers.py
tests.test_customers.TestCreatingUsers
class TestCreatingUsers(BaseTestCase): def setUp(self): self.user = self._create_user() self.stripe_js_response = { "id": "tok_193mTaHSTEMJ0IPXhhZ5vuTX", "object": "customer", "client_ip": None, "created": 1476277734, "livemode": False, "type": "card", "used": False, "card": { "id": "card_193mTaHSTEMJ0IPXIoOiuOdF", "object": "card", "address_city": None, "address_country": None, "address_line1": None, "address_line1_check": None, "address_line2": None, "address_state": None, "address_zip": None, "address_zip_check": None, "brand": "Visa", "country": "US", "cvc_check": None, "dynamic_last4": None, "exp_month": 8, "exp_year": 2017, "funding": "credit", "last4": "4242", "name": None, "customerization_method": None, "metadata": {}, }, } def test_user_create(self): self.assertEqual(StripeCustomer.objects.count(), 0) url = reverse("stripe-customers") data = {} response = self.client.post(url, format="json") self.assertEqual(response.status_code, 403) # not logged self.client.force_authenticate(user=self.user) response = self.client.post(url, format="json") self.assertEqual(response.status_code, 400) with requests_mock.Mocker() as m: m.register_uri( "POST", "https://api.stripe.com/v1/customers", [ { "text": json.dumps( { "error": { "message": "Your card was declined.", "type": "card_error", "param": "", "code": "card_declined", "decline_code": "do_not_honor", } } ), "status_code": 400, }, { "text": json.dumps( { "id": "cus_9Oop0gQ1R1ATMi", "object": "customer", "account_balance": 0, "created": 1476810921, "currency": "usd", "default_source": "card_xyz", "delinquent": False, "description": None, "discount": None, "email": None, "livemode": False, "metadata": {}, "shipping": None, "sources": { "object": "list", "data": [{"id": "card_xyz", "object": "card"}], "has_more": False, "total_count": 1, "url": "/v1/customers/cus_9Oop0gQ1R1ATMi/sources", }, "subscriptions": { "object": "list", "data": [], "has_more": False, "total_count": 0, "url": "/v1/customers/cus_9Oop0gQ1R1ATMi/subscriptions", }, } ) }, ], ) # test response error stripe_customer_qs = StripeCustomer.objects.filter(is_created_at_stripe=True) data = {"stripe_js_response": self.stripe_js_response} self.client.force_authenticate(user=self.user) response = self.client.post(url, data, format="json") self.assertEqual(response.status_code, 400) self.assertEqual(m.call_count, 1) self.assertEqual(set(response.data.keys()), {"stripe_error"}) self.assertEqual(response.data["stripe_error"], "Your card was declined.") self.assertEqual(stripe_customer_qs.count(), 0) # test success response from Stripe response = self.client.post(url, data, format="json") self.assertEqual(response.status_code, 201) self.assertEqual(m.call_count, 2) self.assertEqual(stripe_customer_qs.count(), 1) customer = stripe_customer_qs.first() self.assertTrue(customer.is_active) self.assertEqual(customer.user, self.user) self.assertEqual(customer.stripe_js_response, self.stripe_js_response) self.assertEqual(customer.stripe_customer_id, "cus_9Oop0gQ1R1ATMi") self.assertEqual(customer.stripe_response["id"], "cus_9Oop0gQ1R1ATMi") self.assertEqual(customer.sources, [{"id": "card_xyz", "object": "card"}]) self.assertEqual(customer.default_source, "card_xyz") def test_change_description(self): customer_id = self.stripe_js_response["id"] customer = StripeCustomer(user=self.user, stripe_customer_id=customer_id) api_url = "https://api.stripe.com/v1/customers/{customer_id}".format(customer_id=customer_id) with requests_mock.Mocker() as m: m.register_uri("GET", api_url, text=json.dumps(self.stripe_js_response)) m.register_uri("POST", api_url, text=json.dumps(self.stripe_js_response)) customer.change_description("abc")
class TestCreatingUsers(BaseTestCase): def setUp(self): pass def test_user_create(self): pass def test_change_description(self): pass
4
0
44
2
42
1
1
0.02
1
2
1
0
3
2
3
7
136
7
127
16
123
3
44
14
40
1
2
1
3
6,306
ArabellaTech/aa-stripe
ArabellaTech_aa-stripe/tests/models.py
tests.models.TestUser
class TestUser(AbstractUser): uuid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True)
class TestUser(AbstractUser): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
2
0
2
2
1
0
2
2
1
0
1
0
0
6,307
ArabellaTech/aa-stripe
ArabellaTech_aa-stripe/aa_stripe/settings.py
aa_stripe.settings.StripeSettings
class StripeSettings(object): def __getattr__(self, attr): if attr not in DEFAULTS: raise AttributeError("Invalid API setting: '%s'" % attr) val = getattr(settings, "STRIPE_{}".format(attr), DEFAULTS[attr]) # Cache the result setattr(self, attr, val) return val
class StripeSettings(object): def __getattr__(self, attr): pass
2
0
8
1
6
1
2
0.14
1
1
0
0
1
0
1
1
9
1
7
3
5
1
7
3
5
2
1
1
2
6,308
ArabellaTech/aa-stripe
ArabellaTech_aa-stripe/aa_stripe/admin.py
aa_stripe.admin.ReadOnly
class ReadOnly(ReadOnlyBase, admin.ModelAdmin): editable_fields = []
class ReadOnly(ReadOnlyBase, admin.ModelAdmin): pass
1
0
0
0
0
0
0
0
2
0
0
5
0
0
0
3
2
0
2
2
1
0
2
2
1
0
2
0
0
6,309
ArabellaTech/aa-stripe
ArabellaTech_aa-stripe/aa_stripe/settings.py
aa_stripe.settings.StripeSettingOutter
class StripeSettingOutter(object): def __init__(self, settings_inner): self.settings_inner = settings_inner def __getattr__(self, attr): return getattr(self.settings_inner, attr)
class StripeSettingOutter(object): def __init__(self, settings_inner): pass def __getattr__(self, attr): pass
3
0
2
0
2
0
1
0
1
0
0
0
2
1
2
2
6
1
5
4
2
0
5
4
2
1
1
0
2
6,310
ArabellaTech/aa-stripe
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/ArabellaTech_aa-stripe/aa_stripe/serializers.py
aa_stripe.serializers.StripeCustomerDetailsSerializer.Meta
class Meta: model = StripeCustomer fields = [ "id", "user", "stripe_customer_id", "is_active", "sources", "default_source", "default_source_data", "stripe_js_response" ] read_only_fields = ["id", "user", "stripe_customer_id", "is_active", "sources", "default_source"]
class Meta: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
7
0
7
4
6
0
4
4
3
0
0
0
0
6,311
ArabellaTech/aa-stripe
ArabellaTech_aa-stripe/aa_stripe/serializers.py
aa_stripe.serializers.StripeCustomerSerializer
class StripeCustomerSerializer(ModelSerializer): stripe_js_response = JSONField() def create(self, validated_data): instance = None if validated_data.get("stripe_js_response"): # Create a Customer try: user = self.context['request'].user stripe_js_response = validated_data.pop("stripe_js_response") instance = StripeCustomer.objects.create( user=user, stripe_js_response=stripe_js_response) instance.create_at_stripe() except stripe.error.StripeError as e: logging.error( "[AA-Stripe] creating customer failed for user {user.id}: {error}".format(user=user, error=e) ) raise ValidationError({"stripe_error": e._message}) return instance class Meta: model = StripeCustomer fields = ["stripe_js_response"]
class StripeCustomerSerializer(ModelSerializer): def create(self, validated_data): pass class Meta:
3
0
17
1
15
1
3
0.05
1
1
1
0
1
0
1
1
24
3
20
10
17
1
17
9
14
3
1
2
3
6,312
ArabellaTech/aa-stripe
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/ArabellaTech_aa-stripe/tests/test_webhooks.py
tests.test_webhooks.TestWebhook
class TestWebhook(BaseTestCase): def _create_ping_webhook(self): payload = json.loads( """{ "id": "", "object": "event", "api_version": "2017-06-05", "created": 1503474921, "livemode": false, "pending_webhooks": 0, "request": { "id": "", "idempotency_key": null }, "type": "ping" }""" ) payload["id"] = "evt_{}".format(uuid4()) payload["request"]["id"] = "req_{}".format(uuid4()) payload["created"] = int(time.mktime(datetime.now().timetuple())) return StripeWebhook.objects.create(id=payload["id"], raw_data=payload) def test_subscription_creation(self): self.assertEqual(StripeWebhook.objects.count(), 0) payload = json.loads( """{ "created": 1326853478, "livemode": false, "id": "evt_00000000000000", "type": "charge.failed", "object": "event", "request": null, "pending_webhooks": 1, "api_version": "2017-06-05", "data": { "object": { "id": "ch_00000000000000", "object": "charge", "amount": 100, "amount_refunded": 0, "application": null, "application_fee": null, "balance_transaction": "txn_00000000000000", "captured": false, "created": 1496953100, "currency": "usd", "customer": null, "description": "My First Test Charge (created for API docs)", "destination": null, "dispute": null, "failure_code": null, "failure_message": null, "fraud_details": { }, "invoice": null, "livemode": false, "metadata": { }, "on_behalf_of": null, "order": null, "outcome": null, "paid": false, "receipt_email": null, "receipt_number": null, "refunded": false, "refunds": {}, "review": null, "shipping": null, "source": { "id": "card_00000000000000", "object": "card", "address_city": null, "address_country": null, "address_line1": null, "address_line1_check": null, "address_line2": null, "address_state": null, "address_zip": null, "address_zip_check": null, "brand": "Visa", "country": "US", "customer": null, "cvc_check": null, "dynamic_last4": null, "exp_month": 8, "exp_year": 2018, "fingerprint": "DsGmBIQwiNOvChPk", "funding": "credit", "last4": "4242", "metadata": { }, "name": null, "tokenization_method": null }, "source_transfer": null, "statement_descriptor": null, "status": "succeeded", "transfer_group": null } } }""" ) url = reverse("stripe-webhooks") response = self.client.post(url, data=payload, format="json") self.assertEqual(response.status_code, 400) # not signed # todo: generate signature headers = {"HTTP_STRIPE_SIGNATURE": "wrong"} self.client.credentials(**headers) response = self.client.post(url, data=payload, format="json") self.assertEqual(response.status_code, 400) # wrong signature self.client.credentials(**self._get_signature_headers(payload)) response = self.client.post(url, data=payload, format="json") self.assertEqual(response.status_code, 201) self.assertEqual(StripeWebhook.objects.count(), 1) webhook = StripeWebhook.objects.first() self.assertEqual(webhook.id, payload["id"]) self.assertEqual(webhook.raw_data, payload) self.assertTrue(webhook.is_parsed) def test_coupon_create(self): self.assertEqual(StripeCoupon.objects.count(), 0) payload = json.loads( """{ "id": "evt_1AtuXzLoWm2f6pRwC5YntNLU", "object": "event", "api_version": "2017-06-05", "created": 1503478151, "data": { "object": { "id": "nicecoupon", "object": "coupon", "amount_off": 1000, "created": 1503478151, "currency": "usd", "duration": "once", "duration_in_months": null, "livemode": false, "max_redemptions": null, "metadata": { }, "percent_off": null, "redeem_by": null, "times_redeemed": 0, "valid": true } }, "livemode": false, "pending_webhooks": 1, "request": { "id": "req_RzV8JI9bg7fPiR", "idempotency_key": null }, "type": "coupon.created" }""" ) stripe_response = json.loads( """{ "id": "nicecoupon", "object": "coupon", "amount_off": 1000, "created": 1503478151, "currency": "usd", "duration": "once", "duration_in_months": null, "livemode": false, "max_redemptions": null, "metadata": { }, "percent_off": null, "redeem_by": null, "times_redeemed": 0, "valid": true }""" ) url = reverse("stripe-webhooks") with requests_mock.Mocker() as m: m.register_uri( "GET", "https://api.stripe.com/v1/coupons/nicecoupon", text=json.dumps(stripe_response), ) self.client.credentials(**self._get_signature_headers(payload)) response = self.client.post(url, data=payload, format="json") self.assertEqual(response.status_code, 201) self.assertEqual(StripeCoupon.objects.count(), 1) coupon = StripeCoupon.objects.first() # the rest of the data is retrieved from Stripe API, which is stubbed above # so there is no need to compare it self.assertEqual(coupon.coupon_id, "nicecoupon") # test coupon.created while the coupon has already been deleted from Stripe before the webhook arrived m.register_uri( "GET", "https://api.stripe.com/v1/coupons/doesnotexist", status_code=404, text=json.dumps({"error": {"type": "invalid_request_error"}}), ) payload["id"] = "evt_another" payload["request"]["id"] = ["req_blahblah"] payload["data"]["object"]["id"] = "doesnotexist" self.client.credentials(**self._get_signature_headers(payload)) self.assertEqual(StripeCoupon.objects.filter( coupon_id="doesnotexist").count(), 0) response = self.client.post(url, data=payload, format="json") self.assertEqual(response.status_code, 201) self.assertEqual(StripeCoupon.objects.filter( coupon_id="doesnotexist").count(), 0) # test receiving coupon.created to a coupon that already exists in our database coupon_qs = StripeCoupon.objects.all_with_deleted().filter(coupon_id="nicecoupon") payload["id"] = "evt_1" payload["request"]["id"] = "req_1" payload["data"]["object"]["id"] = "nicecoupon" self.assertEqual(coupon_qs.count(), 1) self.client.credentials(**self._get_signature_headers(payload)) response = self.client.post(url, data=payload, format="json") self.assertEqual(response.status_code, 201) self.assertEqual( StripeWebhook.objects.get(id=response.data["id"]).parse_error, "Coupon with this coupon_id and creation date already exists", ) self.assertEqual(coupon_qs.count(), 1) # test receiving coupon.created to a coupon that already exists in our # database but creation timestamps are different stripe_response["created"] += 1 payload["id"] = "evt_2" payload["request"]["id"] = "req_2" payload["data"]["object"]["created"] = stripe_response["created"] with requests_mock.Mocker() as m: m.register_uri( "GET", "https://api.stripe.com/v1/coupons/nicecoupon", text=json.dumps(stripe_response), ) self.assertEqual(coupon_qs.filter(is_deleted=False).count(), 1) self.assertEqual(coupon_qs.filter(is_deleted=True).count(), 0) self.client.credentials(**self._get_signature_headers(payload)) response = self.client.post(url, data=payload, format="json") self.assertEqual(response.status_code, 201) self.assertEqual(coupon_qs.count(), 2) self.assertEqual(coupon_qs.filter(is_deleted=False).count(), 1) self.assertEqual(coupon_qs.filter(is_deleted=True).count(), 1) # test receiving coupon.created with a coupon in webhook data that does not exist in our database # but when the webhook is being saved, it receives other coupon (same name, but different creation timestamp) # it's to make sure we are saving proper coupon, because the webhook for the new coupon will arrive later payload["id"] = "evt_3" payload["request"]["id"] = "req_3" payload["data"]["object"]["created"] = stripe_response["created"] + 1 with requests_mock.Mocker() as m: m.register_uri( "GET", "https://api.stripe.com/v1/coupons/nicecoupon", text=json.dumps(stripe_response), ) self.assertEqual(coupon_qs.count(), 2) self.client.credentials(**self._get_signature_headers(payload)) response = self.client.post(url, data=payload, format="json") self.assertEqual(response.status_code, 201) self.assertEqual( StripeWebhook.objects.get(id=response.data["id"]).parse_error, "Coupon with this coupon_id and creation date already exists", ) self.assertEqual(coupon_qs.count(), 2) def test_coupon_update(self): coupon = self._create_coupon( "nicecoupon", amount_off=100, duration=StripeCoupon.DURATION_ONCE, metadata={"nie": "tak", "lol1": "rotfl"}, ) payload = json.loads( """{ "id": "evt_1AtuTOLoWm2f6pRw6dYfQzWh", "object": "event", "api_version": "2017-06-05", "created": 1503477866, "data": { "object": { "id": "nicecoupon", "object": "coupon", "amount_off": 10000, "created": 1503412710, "currency": "usd", "duration": "forever", "duration_in_months": null, "livemode": false, "max_redemptions": null, "metadata": { "lol1": "rotfl2", "lol2": "yeah" }, "percent_off": null, "redeem_by": null, "times_redeemed": 0, "valid": true }, "previous_attributes": { "metadata": { "nie": "tak", "lol1": "rotfl", "lol2": null } } }, "livemode": false, "pending_webhooks": 1, "request": { "id": "req_putcEg4hE9bkUb", "idempotency_key": null }, "type": "coupon.updated" }""" ) payload["data"]["object"]["created"] = coupon.stripe_response["created"] url = reverse("stripe-webhooks") self.client.credentials(**self._get_signature_headers(payload)) response = self.client.post(url, data=payload, format="json") coupon.refresh_from_db() self.assertEqual(response.status_code, 201) self.assertEqual(coupon.metadata, {"lol1": "rotfl2", "lol2": "yeah"}) # test updating non existing coupon - nothing else than saving the webhook should happen payload["id"] = "evt_1" payload["request"]["id"] = "req_1" payload["data"]["object"]["id"] = "doesnotexist" self.assertFalse(StripeCoupon.objects.filter( coupon_id="doesnotexist").exists()) self.client.credentials(**self._get_signature_headers(payload)) response = self.client.post(url, data=payload, format="json") self.assertEqual(response.status_code, 201) self.assertFalse(StripeCoupon.objects.filter( coupon_id="doesnotexist").exists()) @requests_mock.Mocker() def test_coupon_delete(self, m): coupon = self._create_coupon( "nicecoupon", amount_off=100, duration=StripeCoupon.DURATION_ONCE) self.assertFalse(coupon.is_deleted) payload = json.loads( """{ "id": "evt_1Atthtasdsaf6pRwkdLOSKls", "object": "event", "api_version": "2017-06-05", "created": 1503474921, "data": { "object": { "id": "nicecoupon", "object": "coupon", "amount_off": 10000, "created": 1503474890, "currency": "usd", "duration": "once", "duration_in_months": null, "livemode": false, "max_redemptions": null, "metadata": { }, "percent_off": null, "redeem_by": null, "times_redeemed": 0, "valid": false } }, "livemode": false, "pending_webhooks": 1, "request": { "id": "req_9UO71nsJyOhQfi", "idempotency_key": null }, "type": "coupon.deleted" }""" ) payload["data"]["object"]["created"] = coupon.stripe_response["created"] m.register_uri( "GET", "https://api.stripe.com/v1/coupons/nicecoupon", status_code=404, text=json.dumps({"error": {"type": "invalid_request_error"}}), ) url = reverse("stripe-webhooks") self.client.credentials(**self._get_signature_headers(payload)) with mock.patch("aa_stripe.models.webhook_pre_parse.send") as mocked_signal: response = self.client.post(url, data=payload, format="json") self.assertEqual(response.status_code, 201) self.assertTrue(StripeCoupon.objects.deleted().filter( pk=coupon.pk).exists()) webhook = StripeWebhook.objects.first() self.assertTrue(webhook.is_parsed) mocked_signal.assert_called_with( event_action="deleted", event_model="coupon", event_type="coupon.deleted", instance=webhook, sender=StripeWebhook, ) # test deleting event that has already been deleted - should not raise any errors # it will just make sure is_deleted is set for this coupon payload["id"] = "evt_someother" payload["request"]["id"] = ["req_someother"] self.client.credentials(**self._get_signature_headers(payload)) response = self.client.post(url, data=payload, format="json") self.assertEqual(response.status_code, 201) self.assertTrue(StripeCoupon.objects.deleted().filter( pk=coupon.pk).exists()) # make sure trying to parse already parsed webhook is impossible self.assertTrue(webhook.is_parsed) with self.assertRaises(StripeWebhookAlreadyParsed): webhook.parse() def test_ping(self): # test receiving ping event (the only event without "." inside the event name) StripeWebhook.objects.all().delete() payload = json.loads( """{ "id": "evt_1Atthtasdsaf6pRwkdLOhKls", "object": "event", "api_version": "2017-06-05", "created": 1503474921, "livemode": false, "pending_webhooks": 1, "request": { "id": "req_9UO71nsJyzhQfi", "idempotency_key": null }, "type": "ping" }""" ) self.client.credentials(**self._get_signature_headers(payload)) with mock.patch("aa_stripe.models.webhook_pre_parse.send") as mocked_signal: response = self.client.post( reverse("stripe-webhooks"), data=payload, format="json") self.assertEqual(response.status_code, 201) mocked_signal.assert_called_with( event_action=None, event_model=None, event_type="ping", instance=StripeWebhook.objects.first(), sender=StripeWebhook, ) @override_settings(ADMINS=(("Admin", "admin@example.com"),)) def test_check_pending_webhooks_command(self): stripe_settings.PENDING_WEBHOOKS_THRESHOLD = 1 # create site self._create_ping_webhook() webhook = self._create_ping_webhook() # create response with fake limits base_stripe_response = json.loads( """{ "object": "list", "url": "/v1/events", "has_more": true, "data": [] }""" ) event1_data = webhook.raw_data.copy() event1_data["id"] = "evt_1" stripe_response_part1 = base_stripe_response.copy() stripe_response_part1["data"] = [event1_data] event2_data = event1_data.copy() event2_data["id"] = "evt_2" stripe_response_part2 = base_stripe_response.copy() stripe_response_part2["data"] = [event2_data] stripe_response_part2["has_more"] = False last_webhook = StripeWebhook.objects.first() with requests_mock.Mocker() as m: m.register_uri( "GET", "https://api.stripe.com/v1/events/{}".format(last_webhook.id), [ {"text": json.dumps(last_webhook.raw_data)}, {"text": json.dumps(last_webhook.raw_data)}, { "text": json.dumps({"error": {"type": "invalid_request_error"}}), "status_code": 404, }, ], ) m.register_uri( "GET", "https://api.stripe.com/v1/events?ending_before={}&limit=100".format( last_webhook.id), text=json.dumps(stripe_response_part1), ) m.register_uri( "GET", "https://api.stripe.com/v1/events?ending_before={}&limit=100".format( event1_data["id"]), text=json.dumps(stripe_response_part2), ) with self.assertRaises(StripePendingWebooksLimitExceeded): call_command("check_pending_webhooks") self.assertEqual(len(mail.outbox), 1) message = mail.outbox[0] self.assertEqual(message.to, "admin@example.com") self.assertIn(event1_data["id"], message) self.assertIn(event2_data["id"], message) self.assertIn("Server environment: test-env", message) self.assertIn("example.com", message) self.assertNotIn(webhook["id"], message) mail.outbox = [] stripe_settings.PENDING_WEBHOOKS_THRESHOLD = 20 call_command("check_pending_webhooks") self.assertEqual(len(mail.outbox), 0) # in case the last event in the database does not longer exist at Stripe # the url below must be called (events are removed after 30 days) m.register_uri( "GET", "https://api.stripe.com/v1/events?&limit=100", text=json.dumps(stripe_response_part2), ) call_command("check_pending_webhooks") # make sure the --site parameter works - pass not existing site id - should fail with self.assertRaises(Site.DoesNotExist): call_command("check_pending_webhooks", site=-1) def test_dispute(self): self.assertEqual(StripeWebhook.objects.count(), 0) payload = { "object": "event", "type": "charge.dispute.created", "id": "evt_123", "api_version": "2018-01-01", "created": 1503477866, "data": { "object": { "id": "dp_ANSJH7zPDQPGqPEw0Cxq", "object": "dispute", "charge": "ch_5Q4BjL06oPWwho", "evidence": { "customer_name": "Jane Austen", "customer_purchase_ip": "127.0.0.1", "product_description": "An Awesome product", "shipping_tracking_number": "Z01234567890", "uncategorized_text": "Additional notes and comments", }, "evidence_details": {"due_by": 1403047735, "submission_count": 1}, } }, } self.client.credentials(**self._get_signature_headers(payload)) response = self.client.post( reverse("stripe-webhooks"), data=payload, format="json") self.assertEqual(201, response.status_code) @requests_mock.Mocker() def test_customer_update(self, m): payload = { "id": "evt_xyz", "object": "event", "api_version": "2018-01-01", "created": 1503477866, "data": { "object": { "id": "cus_xyz", "object": "customer", "sources": [{"id": "card_xyz"}], } }, "request": {"id": "req_putcEg4hE9bkUb", "idempotency_key": None}, "type": "customer.updated", } customer_api_response = { "id": "cus_xyz", "object": "customer", "account_balance": 0, "created": 1476810921, "currency": "usd", "default_source": None, "delinquent": False, "description": None, "discount": None, "email": None, "livemode": False, "metadata": {}, "shipping": None, "sources": { "object": "list", "data": [ # different than in Webhook (data from Webhook is not always up to date!) {"id": "card_xyz", "object": "card"} ], "has_more": False, "total_count": 1, "url": "/v1/customers/cus_xyz/sources", }, "subscriptions": { "object": "list", "data": [], "has_more": False, "total_count": 0, "url": "/v1/customers/cus_xyz/subscriptions", }, } self._create_customer() m.register_uri( "GET", "https://api.stripe.com/v1/customers/cus_xyz", text=json.dumps(customer_api_response), ) url = reverse("stripe-webhooks") self.client.credentials(**self._get_signature_headers(payload)) response = self.client.post(url, data=payload, format="json") self.assertEqual(response.status_code, 201) self.customer.refresh_from_db() self.assertEqual(self.customer.sources, [ {"id": "card_xyz", "object": "card"}]) # customer should also be updated when one of it's sources is updated # (although if a card is removed or added, Stripe will trigger customer.updated webhook) payload["type"] = "customer.source.updated" payload["id"] = "evt_123" payload["data"]["object"] = { "id": "card_1BhOfILoWm2f6pRwe4gkIJc7", "object": "card", "customer": "cus_xyz", } self.client.credentials(**self._get_signature_headers(payload)) with mock.patch("aa_stripe.models.StripeCustomer.refresh_from_stripe") as mocked_refresh: response = self.client.post(url, data=payload, format="json") self.assertEqual(response.status_code, 201, response.content) mocked_refresh.assert_called() # make sure that any Stripe API error will not cause 500 error self.customer.sources = [] self.customer.save() payload["id"] = "evt_abc" self.client.credentials(**self._get_signature_headers(payload)) with mock.patch("aa_stripe.models.StripeCustomer.refresh_from_stripe") as mocked_refresh: mocked_refresh.side_effect = stripe.error.APIError("error") response = self.client.post(url, data=payload, format="json") self.assertEqual(response.status_code, 201) self.customer.refresh_from_db() self.assertEqual(self.customer.sources, [])
class TestWebhook(BaseTestCase): def _create_ping_webhook(self): pass def test_subscription_creation(self): pass def test_coupon_create(self): pass def test_coupon_update(self): pass @requests_mock.Mocker() def test_coupon_delete(self, m): pass def test_ping(self): pass @override_settings(ADMINS=(("Admin", "admin@example.com"),)) def test_check_pending_webhooks_command(self): pass def test_dispute(self): pass @requests_mock.Mocker() def test_customer_update(self, m): pass
13
0
70
3
65
3
1
0.04
1
6
4
0
9
0
9
13
639
31
586
55
573
26
204
47
194
1
2
2
9
6,313
ArabellaTech/aa-stripe
ArabellaTech_aa-stripe/aa_stripe/models.py
aa_stripe.models.StripeWebhook
class StripeWebhook(models.Model): id = models.CharField(primary_key=True, max_length=255) # id from stripe. This will prevent subsequent calls. created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) is_parsed = models.BooleanField(default=False) raw_data = JSONField(blank=True) parse_error = models.TextField(blank=True) def _parse_coupon_notification(self, action): coupon_id = self.raw_data["data"]["object"]["id"] created = timestamp_to_timezone_aware_date(self.raw_data["data"]["object"]["created"]) if action == "created": try: StripeCoupon.objects.all_with_deleted().get(coupon_id=coupon_id, created=created) except StripeCoupon.DoesNotExist: try: StripeCoupon(coupon_id=coupon_id).save(force_retrieve=True) except stripe.error.InvalidRequestError: raise StripeWebhookParseError(_("Coupon with this coupon_id does not exists at Stripe API")) except StripeCouponAlreadyExists as e: raise StripeWebhookParseError(e.details) else: raise StripeWebhookParseError(StripeCouponAlreadyExists.details) elif action == "updated": try: coupon = StripeCoupon.objects.get(coupon_id=coupon_id, created=created) coupon.metadata = self.raw_data["data"]["object"]["metadata"] super(StripeCoupon, coupon).save() # use the super method not to call Stripe API except StripeCoupon.DoesNotExist: pass # do not update if does not exist elif action == "deleted": StripeCoupon.objects.filter(coupon_id=coupon_id, created=created).delete() def _parse_customer_notification(self, model, action): if model == "customer.source": customer_id = self.raw_data["data"]["object"]["customer"] else: customer_id = self.raw_data["data"]["object"]["id"] if action == "updated": try: customer = StripeCustomer.objects.get(stripe_customer_id=customer_id) customer.refresh_from_stripe() except (StripeCustomer.DoesNotExist, stripe.error.StripeError) as e: logger.warning("[AA-Stripe] cannot parse customer.updated webhook: {}".format(e)) def _parse_dispute_notification(self, action): logger.info("[AA-Stripe] New dispute for charge {}".format(self.raw_data["data"]["object"]["charge"])) def parse(self, save=False): if self.is_parsed: raise StripeWebhookAlreadyParsed event_type = self.raw_data.get("type") try: event_model, event_action = event_type.rsplit(".", 1) except ValueError: event_model, event_action = None, None webhook_pre_parse.send( sender=self.__class__, instance=self, event_type=event_type, event_model=event_model, event_action=event_action, ) # parse if event_model: if event_model == "coupon": self._parse_coupon_notification(event_action) elif event_model in ["customer", "customer.source"]: self._parse_customer_notification(event_model, event_action) elif event_model == "charge.dispute": self._parse_dispute_notification(event_action) self.is_parsed = True if save: self.save() def save(self, *args, **kwargs): if not self.is_parsed: try: self.parse() except StripeWebhookParseError as e: self.parse_error = str(e) return super(StripeWebhook, self).save(*args, **kwargs) class Meta: ordering = ["-created"]
class StripeWebhook(models.Model): def _parse_coupon_notification(self, action): pass def _parse_customer_notification(self, model, action): pass def _parse_dispute_notification(self, action): pass def parse(self, save=False): pass def save(self, *args, **kwargs): pass class Meta:
7
0
15
1
14
1
5
0.05
1
8
5
0
5
1
5
5
91
12
78
24
71
4
67
20
60
8
1
3
24
6,314
ArabellaTech/aa-stripe
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/ArabellaTech_aa-stripe/tests/test_subscriptions.py
tests.test_subscriptions.TestSubscriptions
class TestSubscriptions(TestCase): def setUp(self): self.user = UserModel.objects.create( email="foo@bar.bar", username="foo", password="dump-password") self.customer = StripeCustomer.objects.create( user=self.user, stripe_customer_id="example", stripe_js_response='"foo"') self.plan = StripeSubscriptionPlan.objects.create( amount=100, is_created_at_stripe=True, name="example plan", interval=StripeSubscriptionPlan.INTERVAL_MONTH, interval_count=3, ) def test_subscription_creation(self): self.assertEqual(StripeSubscription.objects.count(), 0) subscription = StripeSubscription.objects.create( customer=self.customer, user=self.user, plan=self.plan, metadata={"name": "test subscription"}, ) self.assertFalse(subscription.is_created_at_stripe) with requests_mock.Mocker() as m: stripe_subscription_raw = { "id": "sub_AnksTMRdnWfq9m", "object": "subscription", "application_fee_percent": None, "cancel_at_period_end": False, "canceled_at": None, "created": 1496861935, "current_period_end": 1499453935, "current_period_start": 1496861935, "customer": "cus_AnksoMvJIinvZm", "discount": None, "ended_at": None, "items": { "object": "list", "data": [{ "id": "si_1AS9Mp2eZvKYlo2Cmmf01eoi", "object": "subscription_item", "created": 1496861935, "plan": { "id": self.plan.id, "object": "plan", "amount": 100, "created": 1496857185, "currency": "usd", "interval": "month", "interval_count": 3, "livemode": False, "metadata": {}, "name": "example plan", "statement_descriptor": None, "trial_period_days": None }, "quantity": 1 }], "has_more": False, "total_count": 1, "url": "/v1/subscription_items?subscription=sub_AnksTMRdnWfq9m" }, "livemode": False, "metadata": {"name": "test subscription"}, "plan": { "id": self.plan.id, "object": "plan", "amount": 100, "created": 1496857185, "currency": "usd", "interval": "month", "interval_count": 3, "livemode": False, "metadata": {}, "name": "example plan", "statement_descriptor": None, "trial_period_days": None }, "quantity": 1, "start": 1496861935, "status": "active", "tax_percent": None, "trial_end": None, "trial_start": None } m.register_uri("POST", "https://api.stripe.com/v1/subscriptions", [{"text": json.dumps(stripe_subscription_raw)}]) subscription.create_at_stripe() self.assertTrue(subscription.is_created_at_stripe) self.assertEqual( subscription.stripe_response["id"], "sub_AnksTMRdnWfq9m") self.assertEqual( subscription.stripe_subscription_id, "sub_AnksTMRdnWfq9m") self.assertEqual( subscription.stripe_response["plan"]["name"], self.plan.name) self.assertEqual( subscription.stripe_response["plan"]["amount"], self.plan.amount) self.assertEqual(subscription.status, subscription.STATUS_ACTIVE) self.assertEqual( subscription.stripe_response["current_period_start"], 1496861935) # update stripe_subscription_raw["status"] = "past_due" stripe_subscription_raw["current_period_start"] = 1496869999 m.register_uri("GET", "https://api.stripe.com/v1/subscriptions/sub_AnksTMRdnWfq9m", [{"text": json.dumps(stripe_subscription_raw)}]) subscription.refresh_from_stripe() self.assertEqual(subscription.status, subscription.STATUS_PAST_DUE) self.assertEqual( subscription.stripe_response["current_period_start"], 1496869999) @freeze_time("2017-06-29 12:00:00+00") def test_subscriptions_end(self): subscription = StripeSubscription.objects.create( customer=self.customer, user=self.user, plan=self.plan, metadata={"name": "test subscription"}, end_date=timezone.now() + timedelta(days=5), status=StripeSubscription.STATUS_ACTIVE, ) self.assertIsNone(subscription.canceled_at) with mock.patch("aa_stripe.models.StripeSubscription._stripe_cancel") as mocked_cancel: ret = { "status": "canceled" } mocked_cancel.return_value = ret StripeSubscription.end_subscriptions() call_command("end_subscriptions") with freeze_time("2017-07-04 12:00:00+00"): call_command("end_subscriptions") mocked_cancel.assert_called_with(at_period_end=True) subscription.refresh_from_db() self.assertIsNotNone(subscription.canceled_at) mocked_cancel.reset_mock() call_command("end_subscriptions") mocked_cancel.assert_not_called()
class TestSubscriptions(TestCase): def setUp(self): pass def test_subscription_creation(self): pass @freeze_time("2017-06-29 12:00:00+00") def test_subscriptions_end(self): pass
5
0
44
3
41
0
1
0.01
1
4
3
0
3
3
3
3
137
10
126
14
121
1
42
11
38
1
1
2
3
6,315
ArabellaTech/aa-stripe
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/ArabellaTech_aa-stripe/aa_stripe/forms.py
aa_stripe.forms.StripeCouponForm.Meta
class Meta: model = StripeCoupon fields = [ "coupon_id", "amount_off", "currency", "duration", "duration_in_months", "livemode", "max_redemptions", "metadata", "percent_off", "redeem_by", "times_redeemed", "valid", "is_deleted" ]
class Meta: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
6
0
6
3
5
0
3
3
2
0
0
0
0
6,316
ArabellaTech/aa-stripe
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/ArabellaTech_aa-stripe/tests/test_coupons.py
tests.test_coupons.TestCoupons
class TestCoupons(BaseTestCase): @freeze_time("2016-01-01 00:00:00") def test_create(self): # test creating simple coupon with no coupon_id specified (will be generated by Stripe) created = int(time.mktime(datetime.now().timetuple())) stripe_response = { "id": "25OFF", "object": "coupon", "amount_off": 1, "created": created, "currency": "usd", "duration": StripeCoupon.DURATION_FOREVER, "duration_in_months": None, "livemode": False, "max_redemptions": None, "metadata": {}, "percent_off": 25, "redeem_by": created + 60, "times_redeemed": 0, "valid": True, } with requests_mock.Mocker() as m: m.register_uri( "POST", "https://api.stripe.com/v1/coupons", text=json.dumps(stripe_response), ) coupon = StripeCoupon.objects.create( duration=StripeCoupon.DURATION_FOREVER, percent_off=25, redeem_by=timezone.now() + timedelta(seconds=60), ) self.assertEqual(coupon.coupon_id, stripe_response["id"]) self.assertEqual( coupon.created, timestamp_to_timezone_aware_date(stripe_response["created"]), ) self.assertEqual(coupon.stripe_response, stripe_response) self.assertIn( "redeem_by={}".format( dateformat.format(coupon.redeem_by, "U")), m.last_request.body, ) # test creating coupon with coupon_id stripe_response["id"] = "YOLO1" m.register_uri( "POST", "https://api.stripe.com/v1/coupons", text=json.dumps(stripe_response), ) coupon = StripeCoupon.objects.create( coupon_id=stripe_response["id"], duration=StripeCoupon.DURATION_FOREVER ) self.assertEqual(coupon.coupon_id, stripe_response["id"]) def test_update(self): with requests_mock.Mocker() as m: created = int(time.mktime(datetime.now().timetuple())) stripe_response = { "id": "25OFF", "object": "coupon", "amount_off": 1, "created": created, "currency": "usd", "duration": StripeCoupon.DURATION_FOREVER, "duration_in_months": None, "livemode": False, "max_redemptions": None, "metadata": {}, "percent_off": 25, "redeem_by": created + 60, "times_redeemed": 0, "valid": True, } coupon = self._create_coupon( coupon_id="25OFF", duration=StripeCoupon.DURATION_FOREVER, amount_off=1) self.assertFalse(coupon.is_deleted) # try accessing coupon that does not exist - should delete the coupon from our database m.register_uri( "GET", "https://api.stripe.com/v1/coupons/25OFF", status_code=404, text=json.dumps({"error": {"type": "invalid_request_error"}}), ) coupon.metadata = {"yes": "no"} coupon.save() self.assertTrue(StripeCoupon.objects.deleted().filter( pk=coupon.pk).exists()) # try changing other Stripe data than coupon's metadata m.register_uri( "GET", "https://api.stripe.com/v1/coupons/25OFF", text=json.dumps(stripe_response), ) m.register_uri( "POST", "https://api.stripe.com/v1/coupons/25OFF", text=json.dumps(stripe_response), ) coupon = self._create_coupon( coupon_id="25OFF", duration=StripeCoupon.DURATION_FOREVER, amount_off=1) coupon.duration = StripeCoupon.DURATION_ONCE coupon.save() coupon.refresh_from_db() self.assertNotEqual(coupon.duration, StripeCoupon.DURATION_ONCE) self.assertEqual( coupon.redeem_by, timestamp_to_timezone_aware_date(stripe_response["redeem_by"]), ) def test_delete(self): coupon = self._create_coupon( coupon_id="CPON", amount_off=1, duration=StripeCoupon.DURATION_FOREVER) self.assertEqual(StripeCoupon.objects.deleted().count(), 0) stripe_response = { "id": "CPON", "object": "coupon", "amount_off": 100, "created": int(time.mktime(datetime.now().timetuple())), "currency": "usd", "duration": StripeCoupon.DURATION_FOREVER, "duration_in_months": None, "livemode": False, "max_redemptions": None, "metadata": {}, "percent_off": 25, "redeem_by": None, "times_redeemed": 0, "valid": True, } with requests_mock.Mocker() as m: for coupon_name in ["CPON", "CPON2", "CPON3"]: for method in ["GET", "DELETE"]: m.register_uri( method, "https://api.stripe.com/v1/coupons/{}".format( coupon_name), text=json.dumps(stripe_response), ) coupon.delete() self.assertEqual(StripeCoupon.objects.deleted().count(), 1) # also test the overriden queryset's delete coupon2 = self._create_coupon(coupon_id="CPON2") coupon3 = self._create_coupon(coupon_id="CPON3") self.assertEqual(StripeCoupon.objects.filter( is_deleted=False).count(), 2) delete_result = StripeCoupon.objects.filter( pk__in=[coupon2.pk, coupon3.pk]).delete() self.assertEqual(delete_result, (2, {"aa_stripe.StripeCoupon": 2})) self.assertEqual(StripeCoupon.objects.deleted().count(), 3) self.assertEqual(StripeCoupon.objects.filter( is_deleted=False).count(), 0) def test_admin_form(self): # test correct creation data = { "coupon_id": "25OFF", "amount_off": 1, "currency": "usd", "duration": StripeCoupon.DURATION_ONCE, "metadata": {}, "times_redeemed": 0, "valid": True, } self.assertTrue(StripeCouponForm(data=data).is_valid()) # test passing none of amount_off or percent_off del data["amount_off"] self.assertFalse(StripeCouponForm(data=data).is_valid()) # test passing both of amount_off and percent_off data["amount_off"] = 100 data["percent_off"] = 10 self.assertFalse(StripeCouponForm(data=data).is_valid()) del data["percent_off"] # test passing amount_off without currency del data["currency"] self.assertFalse(StripeCouponForm(data=data).is_valid()) data["currency"] = "usd" # test passing duration repeating with empty duration_in_months data["duration"] = StripeCoupon.DURATION_REPEATING self.assertFalse(StripeCouponForm(data=data).is_valid()) # test passing duration_in_months when duration is not repeating data["duration"] = StripeCoupon.DURATION_ONCE data["duration_in_months"] = 1 self.assertFalse(StripeCouponForm(data=data).is_valid()) del data["duration_in_months"] stripe_response = { "id": "25OFF", "object": "coupon", "amount_off": 1, "created": int(time.mktime(datetime.now().timetuple())), "currency": "usd", "duration": StripeCoupon.DURATION_FOREVER, "duration_in_months": None, "livemode": False, "max_redemptions": None, "metadata": {}, "percent_off": 25, "redeem_by": None, "times_redeemed": 0, "valid": True, } with requests_mock.Mocker() as m: for method in ["GET", "POST", "DELETE"]: m.register_uri( method, "https://api.stripe.com/v1/coupons/25OFF", text=json.dumps(stripe_response), ) coupon = self._create_coupon(data["coupon_id"], amount_off=1) # test creating a new coupon, when there is one that is not deleted self.assertTrue(StripeCoupon.objects.filter( coupon_id=data["coupon_id"], is_deleted=False).exists()) self.assertFalse(StripeCouponForm(data=data).is_valid()) # delete and try again coupon.is_deleted = True coupon.save() self.assertTrue(StripeCouponForm(data=data).is_valid()) def test_details_api(self): # test accessing without authentication url = reverse("stripe-coupon-details", kwargs={"coupon_id": "FAKE-COUPON"}) response = self.client.get(url, format="json") self.assertEqual(response.status_code, 403) user = UserModel.objects.create( email="foo@bar.bar", username="foo", password="dump-password") self.client.force_authenticate(user=user) # test accessing coupon that does not exist response = self.client.get(url, format="json") self.assertEqual(response.status_code, 404) # test regular coupon = self._create_coupon("COUPON") url = reverse("stripe-coupon-details", kwargs={"coupon_id": coupon.coupon_id}) response = self.client.get(url, format="json") self.assertEqual(response.status_code, 200) self.assertEqual( set(response.data.keys()), { "coupon_id", "amount_off", "currency", "duration", "duration_in_months", "livemode", "max_redemptions", "metadata", "percent_off", "redeem_by", "times_redeemed", "valid", "is_created_at_stripe", "created", "updated", "is_deleted", }, ) # test accessing coupon that has already been deleted # update does not call object's .save(), so we do not need to mock Stripe API StripeCoupon.objects.filter(pk=coupon.pk).update(is_deleted=True) response = self.client.get(url, format="json") self.assertEqual(response.status_code, 404) def test_refresh_coupons_command(self): coupons = { "1A": self._create_coupon("1A"), "2A": self._create_coupon("2A"), "3A": self._create_coupon("3A"), "4A": self._create_coupon("4A", amount_off=100), } self.assertEqual(StripeCoupon.objects.count(), 4) # fake deleted coupon, this coupon should be recreated in the database StripeCoupon.objects.filter( pk=coupons["3A"].pk).update(is_deleted=True) coupon_1a_new_response = coupons["1A"].stripe_response.copy() coupon_1a_new_response["metadata"] = {"new": "data"} coupon_4a_new_response = coupons["4A"].stripe_response.copy() coupon_4a_new_response["created"] += 1 coupon_4a_new_response["amount_off"] = 9999 # fake limit stripe_response_part1 = { "object": "list", "url": "/v1/coupons", "has_more": True, "data": [ coupon_1a_new_response, # 1A will be updated, # 2A will be deleted coupons["3A"].stripe_response, # 3A will be recreated coupon_4a_new_response, # 4A will be deleted and recreated with the same name ], } new_coupon_stripe_response = coupons["1A"].stripe_response.copy() new_coupon_stripe_response["id"] = "1B" stripe_response_part2 = stripe_response_part1.copy() stripe_response_part2.update( {"has_more": False, "data": [new_coupon_stripe_response]}) with requests_mock.Mocker() as m: m.register_uri( "GET", "https://api.stripe.com/v1/coupons", text=json.dumps(stripe_response_part1), ) m.register_uri( "GET", "https://api.stripe.com/v1/coupons?starting_after=4A", text=json.dumps(stripe_response_part2), ) # 3A will be recreated m.register_uri( "GET", "https://api.stripe.com/v1/coupons/3A", text=json.dumps(coupons["3A"].stripe_response), ) # 4A will be recreated with new data m.register_uri( "GET", "https://api.stripe.com/v1/coupons/4A", text=json.dumps(coupon_4a_new_response), ) # 1B will be created m.register_uri( "GET", "https://api.stripe.com/v1/coupons/1B", text=json.dumps(new_coupon_stripe_response), ) call_command("refresh_coupons") # 4 + 3 were created self.assertEqual( StripeCoupon.objects.all_with_deleted().count(), 7) for coupon_id, coupon in coupons.items(): coupons[coupon_id] = StripeCoupon.objects.all_with_deleted().get( pk=coupon.pk) self.assertEqual(coupons["1A"].metadata, coupon_1a_new_response["metadata"]) self.assertTrue(coupons["2A"].is_deleted) new_3a_coupon = StripeCoupon.objects.get( coupon_id="3A", is_deleted=False) self.assertNotEqual(new_3a_coupon.pk, coupons["3A"].pk) self.assertTrue(coupons["4A"].is_deleted) new_4a_coupon = StripeCoupon.objects.get( coupon_id="4A", is_deleted=False) self.assertNotEqual(new_4a_coupon.pk, coupons["4A"].pk) self.assertEqual( new_4a_coupon.amount_off, Decimal(coupon_4a_new_response["amount_off"]) / 100, ) self.assertTrue(StripeCoupon.objects.filter( coupon_id="1B", is_deleted=False).exists)
class TestCoupons(BaseTestCase): @freeze_time("2016-01-01 00:00:00") def test_create(self): pass def test_update(self): pass def test_delete(self): pass def test_admin_form(self): pass def test_details_api(self): pass def test_refresh_coupons_command(self): pass
8
0
56
3
49
5
2
0.09
1
7
2
0
6
0
6
10
343
23
297
43
289
27
127
37
120
3
2
3
10
6,317
ArabellaTech/aa-stripe
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/ArabellaTech_aa-stripe/tests/test_charge.py
tests.test_charge.TestCharges
class TestCharges(TestCase): def _success_handler(self, sender, instance, **kwargs): self.success_signal_was_called = True def _exception_handler(self, sender, instance, **kwargs): self.exception_signal_was_called = True def _charge_refunded_handler(self, sender, instance, **kwargs): self.charge_refunded_signal_was_called = True def _reset_signals(self): self.exception_signal_was_called = False self.success_signal_was_called = False self.charge_refunded_signal_was_called = False def setUp(self): self.user = UserModel.objects.create( email="foo@bar.bar", username="foo", password="dump-password") self._reset_signals() stripe_charge_succeeded.connect(self._success_handler) stripe_charge_card_exception.connect(self._exception_handler) stripe_charge_refunded.connect(self._charge_refunded_handler) self.data = { "customer_id": "cus_AlSWz1ZQw7qG2z", "currency": "usd", "amount": 100, "description": "ABC", } self.customer = StripeCustomer.objects.create( user=self.user, stripe_customer_id=self.data["customer_id"], stripe_js_response='"foo"', ) self.charge = StripeCharge.objects.create( user=self.user, amount=self.data["amount"], customer=self.customer, description=self.data["description"], source=self.customer, ) @mock.patch("aa_stripe.management.commands.charge_stripe.stripe.Charge.create") def test_charge_unknown_stripe_error(self, charge_create_mocked): stripe_error_json_body = {"error": {"type": "api_error"}} charge_create_mocked.side_effect = StripeError( json_body=stripe_error_json_body) with self.assertRaises(SystemExit): out = StringIO() sys.stdout = out call_command("charge_stripe") self.charge.refresh_from_db() self.assertFalse(self.success_signal_was_called) self.assertFalse(self.exception_signal_was_called) self.assertFalse(self.charge.is_charged) self.assertFalse(self.charge.charge_attempt_failed) self.assertDictEqual(self.charge.stripe_response, stripe_error_json_body) self.assertIn("Exception happened", out.getvalue()) @mock.patch("aa_stripe.management.commands.charge_stripe.stripe.Charge.create") def test_charge_stripe_error(self, charge_create_mocked): stripe_error_json_body = { "error": { "code": "resource_missing", "doc_url": "https://stripe.com/docs/error-codes/resource-missing", "message": "No such customer: cus_ESrgXHlDA3E7mQ", "param": "customer", "type": "invalid_request_error", } } charge_create_mocked.side_effect = StripeError( json_body=stripe_error_json_body) call_command("charge_stripe") self.charge.refresh_from_db() self.assertFalse(self.success_signal_was_called) self.assertTrue(self.exception_signal_was_called) self.assertFalse(self.charge.is_charged) self.assertTrue(self.charge.charge_attempt_failed) self.assertDictEqual(self.charge.stripe_response, stripe_error_json_body) @mock.patch("aa_stripe.management.commands.charge_stripe.stripe.Charge.create") def test_charge_card_declined(self, charge_create_mocked): card_error_json_body = { "error": { "charge": "ch_1F5C8nBszOVoiLmgPWC36cnI", "code": "card_declined", "decline_code": "generic_decline", "doc_url": "https://stripe.com/docs/error-codes/card-declined", "message": "Your card was declined.", "type": "card_error", } } charge_create_mocked.side_effect = CardError( message="a", param="b", code="c", json_body=card_error_json_body) call_command("charge_stripe") self.charge.refresh_from_db() self.assertFalse(self.success_signal_was_called) self.assertTrue(self.exception_signal_was_called) self.assertDictEqual(self.charge.stripe_response, card_error_json_body) self.assertEqual(self.charge.stripe_charge_id, "ch_1F5C8nBszOVoiLmgPWC36cnI") @mock.patch("aa_stripe.management.commands.charge_stripe.stripe.Charge.create") def test_charge_with_idempotency_key(self, charge_create_mocked): charge_create_mocked.return_value = stripe.Charge(id="AA1") idempotency_key = "idempotency_key123" self.charge.charge(idempotency_key=idempotency_key) self.assertTrue(self.charge.is_charged) self.assertTrue(self.success_signal_was_called) self.assertFalse(self.exception_signal_was_called) self.assertEqual(self.charge.stripe_response["id"], "AA1") charge_create_mocked.assert_called_with( idempotency_key="{}-{}-{}".format(self.charge.object_id, self.charge.content_type_id, idempotency_key), amount=self.charge.amount, currency=self.data["currency"], customer=self.data["customer_id"], description=self.data["description"], metadata={ "object_id": self.charge.object_id, "content_type_id": self.charge.content_type_id, "origin": settings.PAYMENT_ORIGIN, "member_uuid": str(self.user.uuid), }, ) @mock.patch("aa_stripe.management.commands.charge_stripe.stripe.Charge.create") def test_already_charged(self, charge_create_mocked): charge_create_mocked.return_value = stripe.Charge(id="AA1") self.charge.charge() self.assertTrue(self.charge.is_charged) self.assertTrue(self.success_signal_was_called) self.assertFalse(self.exception_signal_was_called) self._reset_signals() with self.assertRaises(StripeMethodNotAllowed) as ctx: self.charge.charge() self.assertEqual(ctx.exception.args[0], "Already charged.") self.assertTrue(self.charge.is_charged) self.assertFalse(self.success_signal_was_called) self.assertFalse(self.exception_signal_was_called) @mock.patch("aa_stripe.management.commands.charge_stripe.stripe.Charge.create") def test_stripe_api_error(self, charge_create_mocked): error_json = { "error": {"message": "An unknown error occurred", "type": "api_error"}} charge_create_mocked.side_effect = stripe.error.APIError( message="An unknown error occurred", json_body=error_json, ) with self.assertRaises(StripeInternalError): self.charge.charge() assert not self.success_signal_was_called assert not self.charge.is_charged assert self.charge.charge_attempt_failed assert self.charge.stripe_response == error_json @mock.patch("aa_stripe.management.commands.charge_stripe.stripe.Refund.create") def test_refund_on_not_charged(self, refund_create_mocked): self.charge.refresh_from_db() refund_create_mocked.return_value = stripe.Refund(id="R1") self.assertTrue( self.customer, StripeCustomer.get_latest_active_customer_for_user(self.user)) with self.assertRaises(StripeMethodNotAllowed) as ctx: self.charge.refund() self.assertEqual( ctx.exception.args[0], "Cannot refund not charged transaction.") self.assertFalse(self.charge.is_refunded) self.assertFalse(self.charge_refunded_signal_was_called) @mock.patch("aa_stripe.management.commands.charge_stripe.stripe.Refund.create") def test_already_refunded(self, refund_create_mocked): refund_create_mocked.return_value = stripe.Refund(id="R1") self.charge.is_charged = True self.charge.is_refunded = True with self.assertRaises(StripeMethodNotAllowed) as ctx: self.charge.refund() self.assertEqual(ctx.exception.args[0], "Already refunded.") self.assertTrue(self.charge.is_refunded) self.assertFalse(self.charge_refunded_signal_was_called) @mock.patch("aa_stripe.management.commands.charge_stripe.stripe.Refund.create") def test_full_refund(self, refund_create_mocked): refund_create_mocked.return_value = stripe.Refund(id="R1") self.charge.is_charged = True self.charge.refund() self.assertTrue(self.charge.is_refunded) self.assertEqual(self.charge.stripe_refund_id, "R1") self.assertEqual(self.charge.amount_refunded, self.charge.amount) self.assertTrue(self.charge_refunded_signal_was_called) @mock.patch("aa_stripe.management.commands.charge_stripe.stripe.Refund.create") def test_partial_refund(self, refund_create_mocked): refund_create_mocked.return_value = stripe.Refund(id="R1") self.charge.is_charged = True with mock.patch("aa_stripe.signals.stripe_charge_refunded.send") as refund_signal_send: to_refund = 30 # first refund self.charge.refund(to_refund) refund_create_mocked.assert_called_with( charge=self.charge.stripe_charge_id, amount=to_refund, idempotency_key="{}-{}-{}-{}".format( self.charge.object_id, self.charge.content_type_id, 0, to_refund), ) self.assertFalse(self.charge.is_refunded) refund_signal_send.assert_called_with( sender=StripeCharge, instance=self.charge) # second refund self._reset_signals() refund_create_mocked.reset_mock() self.charge.refund(to_refund) refund_create_mocked.assert_called_with( charge=self.charge.stripe_charge_id, amount=to_refund, idempotency_key="{}-{}-{}-{}".format( self.charge.object_id, self.charge.content_type_id, 30, to_refund ), ) self.assertFalse(self.charge.is_refunded) refund_signal_send.assert_called_with( sender=StripeCharge, instance=self.charge) self.assertEqual(self.charge.amount_refunded, 60) @mock.patch("aa_stripe.management.commands.charge_stripe.stripe.Refund.create") def test_full_refund_of_partials(self, refund_create_mocked): refund_create_mocked.return_value = stripe.Refund(id="R1") self.charge.is_charged = True with mock.patch("aa_stripe.signals.stripe_charge_refunded.send") as refund_signal_send: to_refund = 50 # first refund self.charge.refund(to_refund) refund_create_mocked.assert_called_with( charge=self.charge.stripe_charge_id, amount=to_refund, idempotency_key="{}-{}-{}-{}".format( self.charge.object_id, self.charge.content_type_id, 0, to_refund), ) self.assertFalse(self.charge.is_refunded) refund_signal_send.assert_called_with( sender=StripeCharge, instance=self.charge) # second refund refund_create_mocked.reset_mock() self.charge.refund(to_refund) refund_create_mocked.assert_called_with( charge=self.charge.stripe_charge_id, amount=to_refund, idempotency_key="{}-{}-{}-{}".format( self.charge.object_id, self.charge.content_type_id, 50, to_refund ), ) self.assertTrue(self.charge.is_refunded) refund_signal_send.assert_called_with( sender=StripeCharge, instance=self.charge) self.assertEqual(self.charge.amount_refunded, 100) @mock.patch("aa_stripe.management.commands.charge_stripe.stripe.Refund.create") def test_refund_over_charge_amount(self, refund_create_mocked): refund_create_mocked.return_value = stripe.Refund(id="R1") self.charge.is_charged = True with self.assertRaises(StripeMethodNotAllowed) as ctx: self.charge.refund(101) self.assertEqual(ctx.exception.args[0], "Refunds exceed charge") self.assertFalse(self.charge.is_refunded) self.assertFalse(self.charge_refunded_signal_was_called) @mock.patch( "aa_stripe.management.commands.charge_stripe.stripe.Refund.create", side_effect=[ stripe.error.InvalidRequestError("message", "param"), stripe.Refund(id="R1"), ], ) @mock.patch( "aa_stripe.management.commands.charge_stripe.stripe.Charge.retrieve", return_value=build_small_manual_refunded_charge(), ) def test_refund_after_partial_manual_refund(self, refund_create_mocked, charge_retrieve_mocked): self.charge.is_charged = True self.charge.stripe_charge_id = "AA1" self.charge.refund(100) self.assertEqual(self.charge.amount_refunded, 100) @mock.patch( "aa_stripe.management.commands.charge_stripe.stripe.Refund.create", side_effect=stripe.error.InvalidRequestError( "message", "param", code="charge_already_refunded"), ) @mock.patch( "aa_stripe.management.commands.charge_stripe.stripe.Charge.retrieve", return_value=build_full_manual_refunded_charge(), ) def test_already_manually_refunded(self, refund_create_mocked, charge_retrieve_mocked): self.charge.is_charged = True self.charge.stripe_charge_id = "AA1" self.charge.refund(100) self.assertEqual(self.charge.amount_refunded, 100)
class TestCharges(TestCase): def _success_handler(self, sender, instance, **kwargs): pass def _exception_handler(self, sender, instance, **kwargs): pass def _charge_refunded_handler(self, sender, instance, **kwargs): pass def _reset_signals(self): pass def setUp(self): pass @mock.patch("aa_stripe.management.commands.charge_stripe.stripe.Charge.create") def test_charge_unknown_stripe_error(self, charge_create_mocked): pass @mock.patch("aa_stripe.management.commands.charge_stripe.stripe.Charge.create") def test_charge_stripe_error(self, charge_create_mocked): pass @mock.patch("aa_stripe.management.commands.charge_stripe.stripe.Charge.create") def test_charge_card_declined(self, charge_create_mocked): pass @mock.patch("aa_stripe.management.commands.charge_stripe.stripe.Charge.create") def test_charge_with_idempotency_key(self, charge_create_mocked): pass @mock.patch("aa_stripe.management.commands.charge_stripe.stripe.Charge.create") def test_already_charged(self, charge_create_mocked): pass @mock.patch("aa_stripe.management.commands.charge_stripe.stripe.Charge.create") def test_stripe_api_error(self, charge_create_mocked): pass @mock.patch("aa_stripe.management.commands.charge_stripe.stripe.Refund.create") def test_refund_on_not_charged(self, refund_create_mocked): pass @mock.patch("aa_stripe.management.commands.charge_stripe.stripe.Refund.create") def test_already_refunded(self, refund_create_mocked): pass @mock.patch("aa_stripe.management.commands.charge_stripe.stripe.Refund.create") def test_full_refund(self, refund_create_mocked): pass @mock.patch("aa_stripe.management.commands.charge_stripe.stripe.Refund.create") def test_partial_refund(self, refund_create_mocked): pass @mock.patch("aa_stripe.management.commands.charge_stripe.stripe.Refund.create") def test_full_refund_of_partials(self, refund_create_mocked): pass @mock.patch("aa_stripe.management.commands.charge_stripe.stripe.Refund.create") def test_refund_over_charge_amount(self, refund_create_mocked): pass @mock.patch( "aa_stripe.management.commands.charge_stripe.stripe.Refund.create", side_effect=[ stripe.error.InvalidRequestError("message", "param"), stripe.Refund(id="R1"), ], ) @mock.patch( "aa_stripe.management.commands.charge_stripe.stripe.Charge.retrieve", return_value=build_small_manual_refunded_charge(), ) def test_refund_after_partial_manual_refund(self, refund_create_mocked, charge_retrieve_mocked): pass @mock.patch( "aa_stripe.management.commands.charge_stripe.stripe.Refund.create", side_effect=stripe.error.InvalidRequestError( "message", "param", code="charge_already_refunded"), ) @mock.patch( "aa_stripe.management.commands.charge_stripe.stripe.Charge.retrieve", return_value=build_full_manual_refunded_charge(), ) def test_already_manually_refunded(self, refund_create_mocked, charge_retrieve_mocked): pass
36
0
12
0
12
0
1
0.02
1
6
4
0
19
7
19
19
281
20
257
64
206
4
159
35
139
1
1
1
19
6,318
ArabellaTech/aa-stripe
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/ArabellaTech_aa-stripe/aa_stripe/serializers.py
aa_stripe.serializers.StripeWebhookSerializer.Meta
class Meta: model = StripeWebhook fields = ["id", "raw_data"]
class Meta: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
3
0
3
3
2
0
3
3
2
0
0
0
0
6,319
ArabellaTech/aa-stripe
ArabellaTech_aa-stripe/aa_stripe/serializers.py
aa_stripe.serializers.StripeCustomerDetailsSerializer
class StripeCustomerDetailsSerializer(ModelSerializer): # source data from Stripe JS response used to add a new card stripe_js_response = serializers.JSONField(write_only=True, required=True) sources = serializers.JSONField(read_only=True) def validate_stripe_js_response(self, value): if "id" not in value: raise serializers.ValidationError(_("This field must contain JSON data from Stripe JS.")) return value def validate(self, data): if "stripe_js_response" not in data: raise ValidationError({"stripe_js_response": ["This field is required."]}) return super(StripeCustomerDetailsSerializer, self).validate(data) def update(self, instance, validated_data): stripe_js_response = validated_data["stripe_js_response"] new_source_token = stripe_js_response["id"] try: instance.add_new_source(new_source_token, stripe_js_response) except stripe.error.StripeError as e: logging.error( "[AA-Stripe] adding new source to customer failed for user {user.id}: {error}".format( user=self.context["request"].user, error=e) ) raise ValidationError({"stripe_error": e._message}) return instance class Meta: model = StripeCustomer fields = [ "id", "user", "stripe_customer_id", "is_active", "sources", "default_source", "default_source_data", "stripe_js_response" ] read_only_fields = ["id", "user", "stripe_customer_id", "is_active", "sources", "default_source"]
class StripeCustomerDetailsSerializer(ModelSerializer): def validate_stripe_js_response(self, value): pass def validate_stripe_js_response(self, value): pass def update(self, instance, validated_data): pass class Meta:
5
0
7
0
7
0
2
0.03
1
1
0
0
3
0
3
3
36
5
30
13
25
1
24
12
19
2
1
1
6
6,320
ArabellaTech/aa-stripe
ArabellaTech_aa-stripe/aa_stripe/migrations/0016_stripecharge_is_refunded.py
aa_stripe.migrations.0016_stripecharge_is_refunded.Migration
class Migration(migrations.Migration): dependencies = [ ('aa_stripe', '0015_auto_20170925_0838'), ] operations = [ migrations.AddField( model_name='stripecharge', name='is_refunded', field=models.BooleanField(default=False), ), migrations.AddField( model_name='stripecharge', name='stripe_refund_id', field=models.CharField(blank=True, max_length=255), ), ]
class Migration(migrations.Migration): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
18
2
16
3
15
0
3
3
2
0
1
0
0
6,321
ArabellaTech/aa-stripe
ArabellaTech_aa-stripe/tests/test_utils.py
tests.test_utils.BaseTestCase
class BaseTestCase(APITestCase): def _create_user(self, email="foo@bar.bar", set_self=True): user = UserModel.objects.create(email=email, username=email.split("@")[0], password="dump-password") if set_self: self.user = user return user def _create_coupon(self, coupon_id, amount_off=None, duration=StripeCoupon.DURATION_FOREVER, metadata=None): with requests_mock.Mocker() as m: # create a simple coupon which will be used for tests stripe_response = { "id": coupon_id, "object": "coupon", "amount_off": int(amount_off * 100) if amount_off else None, "created": int(time.mktime(datetime.now().timetuple())), "currency": "usd", "duration": duration, "duration_in_months": None, "livemode": False, "max_redemptions": None, "metadata": metadata or {}, "percent_off": 25, "redeem_by": None, "times_redeemed": 0, "valid": True } m.register_uri("POST", "https://api.stripe.com/v1/coupons", text=json.dumps(stripe_response)) return StripeCoupon.objects.create( coupon_id=coupon_id, duration=duration, amount_off=amount_off ) def _create_customer(self, user=None, customer_id="cus_xyz", sources=None, default_source="", is_active=True, is_created_at_stripe=True): if not user: if hasattr(self, "user"): user = self.user else: user = self._create_user() sources = sources or [] self.customer = StripeCustomer.objects.create( user=user, is_active=is_active, stripe_customer_id=customer_id if is_created_at_stripe else "", is_created_at_stripe=is_created_at_stripe, sources=sources, default_source=default_source ) return self.customer def _get_signature_headers(self, payload): timestamp = int(time.time()) raw_payload = json.dumps(payload).replace(": ", ":") raw_payload = raw_payload.replace(", ", ",") signed_payload = "{timestamp:d}.{raw_payload}".format(timestamp=timestamp, raw_payload=raw_payload) signature = WebhookSignature._compute_signature(signed_payload, stripe_settings.WEBHOOK_ENDPOINT_SECRET) return { "HTTP_STRIPE_SIGNATURE": ("t={timestamp:d},v1={signature}" ",v0=not_important".format(timestamp=timestamp, signature=signature)) }
class BaseTestCase(APITestCase): def _create_user(self, email="foo@bar.bar", set_self=True): pass def _create_coupon(self, coupon_id, amount_off=None, duration=StripeCoupon.DURATION_FOREVER, metadata=None): pass def _create_customer(self, user=None, customer_id="cus_xyz", sources=None, default_source="", is_active=True, is_created_at_stripe=True): pass def _get_signature_headers(self, payload): pass
5
0
15
1
14
0
2
0.02
1
4
2
5
4
2
4
4
62
5
56
15
50
1
26
13
21
4
1
2
9
6,322
ArabellaTech/aa-stripe
ArabellaTech_aa-stripe/aa_stripe/migrations/0014_stripecharge_charge_attempt_failed.py
aa_stripe.migrations.0014_stripecharge_charge_attempt_failed.Migration
class Migration(migrations.Migration): dependencies = [ ('aa_stripe', '0013_stripesubscription_at_period_end'), ] operations = [ migrations.AddField( model_name='stripecharge', name='charge_attempt_failed', field=models.BooleanField(default=False), ), ]
class Migration(migrations.Migration): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
13
2
11
3
10
0
3
3
2
0
1
0
0
6,323
ArabellaTech/aa-stripe
ArabellaTech_aa-stripe/aa_stripe/exceptions.py
aa_stripe.exceptions.StripeWebhookParseError
class StripeWebhookParseError(Exception): details = _("Unable to parse webhook")
class StripeWebhookParseError(Exception): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
10
2
0
2
2
1
0
2
2
1
0
3
0
0
6,324
ArabellaTech/aa-stripe
ArabellaTech_aa-stripe/aa_stripe/exceptions.py
aa_stripe.exceptions.StripeWebhookAlreadyParsed
class StripeWebhookAlreadyParsed(Exception): details = _("This webhook has already been parsed")
class StripeWebhookAlreadyParsed(Exception): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
10
2
0
2
2
1
0
2
2
1
0
3
0
0
6,325
ArabellaTech/aa-stripe
ArabellaTech_aa-stripe/aa_stripe/exceptions.py
aa_stripe.exceptions.StripeMethodNotAllowed
class StripeMethodNotAllowed(Exception): details = _("Already created at stripe")
class StripeMethodNotAllowed(Exception): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
10
2
0
2
2
1
0
2
2
1
0
3
0
0
6,326
ArabellaTech/aa-stripe
ArabellaTech_aa-stripe/aa_stripe/exceptions.py
aa_stripe.exceptions.StripeInternalError
class StripeInternalError(Exception): details = _("Temporary Stripe API error")
class StripeInternalError(Exception): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
10
2
0
2
2
1
0
2
2
1
0
3
0
0
6,327
ArabellaTech/aa-stripe
ArabellaTech_aa-stripe/aa_stripe/exceptions.py
aa_stripe.exceptions.StripeCouponAlreadyExists
class StripeCouponAlreadyExists(Exception): details = _("Coupon with this coupon_id and creation date already exists")
class StripeCouponAlreadyExists(Exception): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
10
2
0
2
2
1
0
2
2
1
0
3
0
0
6,328
ArabellaTech/aa-stripe
ArabellaTech_aa-stripe/aa_stripe/api.py
aa_stripe.api.WebhookAPI
class WebhookAPI(CreateAPIView): queryset = StripeWebhook.objects.all() serializer_class = StripeWebhookSerializer permission_classes = (AllowAny,) def post(self, request, *args, **kwargs): payload = request.body.decode("utf-8") sig_header = request.META.get("HTTP_STRIPE_SIGNATURE") event = None try: event = stripe.Webhook.construct_event( payload, sig_header, stripe_settings.WEBHOOK_ENDPOINT_SECRET, api_key=stripe_settings.API_KEY, ) except ValueError: # Invalid payload return Response(status=400, data={"message": "invalid payload"}) except stripe.error.SignatureVerificationError as e: # Invalid signature return Response(status=400, data={"message": str(e)}) data = { "raw_data": json.loads(str(event)), "id": event["id"], } try: StripeWebhook.objects.get(pk=event["id"]) return Response(status=400, data={"message": "already received"}) except StripeWebhook.DoesNotExist: # correct, first time. Create webhook webhook = StripeWebhook.objects.create(id=event["id"], raw_data=data["raw_data"]) serializer = self.serializer_class(webhook) return Response(serializer.data, status=status.HTTP_201_CREATED)
class WebhookAPI(CreateAPIView): def post(self, request, *args, **kwargs): pass
2
0
29
3
23
3
4
0.11
1
3
1
0
1
0
1
1
34
4
27
12
25
3
22
11
20
4
1
1
4
6,329
ArabellaTech/aa-stripe
ArabellaTech_aa-stripe/aa_stripe/api.py
aa_stripe.api.CustomersAPI
class CustomersAPI(CreateAPIView): queryset = StripeCustomer.objects.all() serializer_class = StripeCustomerSerializer permission_classes = (IsAuthenticated,)
class CustomersAPI(CreateAPIView): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
4
0
4
4
3
0
4
4
3
0
1
0
0
6,330
ArabellaTech/aa-stripe
ArabellaTech_aa-stripe/aa_stripe/forms.py
aa_stripe.forms.StripeCouponForm
class StripeCouponForm(forms.ModelForm): def clean_currency(self): amount_off = self.cleaned_data.get("amount_off") currency = self.cleaned_data.get("currency") if amount_off and not currency: raise forms.ValidationError(_("Currency is required when amount_off is set")) return currency def clean_coupon_id(self): coupon_id = self.cleaned_data.get("coupon_id") if coupon_id: if StripeCoupon.objects.filter(coupon_id=coupon_id).exists(): raise forms.ValidationError(_("Coupon with this id already exists")) return coupon_id def clean_duration_in_months(self): duration = self.cleaned_data.get("duration") duration_in_months = self.cleaned_data.get("duration_in_months") if duration == StripeCoupon.DURATION_REPEATING and not duration_in_months: raise forms.ValidationError(_("Cannot be empty with when duration is set to repeating")) if duration_in_months and duration != StripeCoupon.DURATION_REPEATING: raise forms.ValidationError(_("Cannot be set when duration is not set to repeating")) return duration_in_months def clean(self): if self.instance.pk: return self.cleaned_data discount_list = [self.cleaned_data.get("amount_off"), self.cleaned_data.get("percent_off")] if not any(discount_list) or all(discount_list): raise forms.ValidationError(_("Coupon must specify amount_off or percent_off")) return self.cleaned_data class Meta: model = StripeCoupon fields = [ "coupon_id", "amount_off", "currency", "duration", "duration_in_months", "livemode", "max_redemptions", "metadata", "percent_off", "redeem_by", "times_redeemed", "valid", "is_deleted" ]
class StripeCouponForm(forms.ModelForm): def clean_currency(self): pass def clean_coupon_id(self): pass def clean_duration_in_months(self): pass def clean_currency(self): pass class Meta:
6
0
8
2
7
0
3
0
1
1
1
0
4
0
4
4
44
10
34
14
28
0
31
14
25
3
1
2
11
6,331
ArabellaTech/aa-stripe
ArabellaTech_aa-stripe/aa_stripe/api.py
aa_stripe.api.CustomerDetailsAPI
class CustomerDetailsAPI(RetrieveUpdateAPIView): queryset = StripeCustomer.objects.all() serializer_class = StripeCustomerDetailsSerializer permission_classes = (IsAuthenticated,) lookup_field = "stripe_customer_id" def get_queryset(self): return super().get_queryset().filter(user=self.request.user)
class CustomerDetailsAPI(RetrieveUpdateAPIView): def get_queryset(self): pass
2
0
2
0
2
0
1
0
1
1
0
0
1
0
1
1
8
1
7
6
5
0
7
6
5
1
1
0
1
6,332
ArabellaTech/aa-stripe
ArabellaTech_aa-stripe/aa_stripe/admin.py
aa_stripe.admin.StripeWebhookAdmin
class StripeWebhookAdmin(ReadOnly): list_display = ("id", "created", "updated", "is_parsed") ordering = ("-created",)
class StripeWebhookAdmin(ReadOnly): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
3
3
0
3
3
2
0
3
3
2
0
3
0
0
6,333
ArabellaTech/aa-stripe
ArabellaTech_aa-stripe/aa_stripe/admin.py
aa_stripe.admin.StripeSubscriptionPlanAdmin
class StripeSubscriptionPlanAdmin(ReadOnly): list_display = ("id", "is_created_at_stripe", "created", "updated", "amount", "interval", "interval_count") ordering = ("-created",)
class StripeSubscriptionPlanAdmin(ReadOnly): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
3
3
0
3
3
2
0
3
3
2
0
3
0
0
6,334
ArabellaTech/aa-stripe
ArabellaTech_aa-stripe/aa_stripe/admin.py
aa_stripe.admin.StripeSubscriptionAdmin
class StripeSubscriptionAdmin(ReadOnly): list_display = ( "id", "stripe_subscription_id", "user", "is_created_at_stripe", "status", "created", "updated", "end_date", "canceled_at") ordering = ("-created",)
class StripeSubscriptionAdmin(ReadOnly): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
3
5
0
5
3
4
0
3
3
2
0
3
0
0
6,335
ArabellaTech/aa-stripe
ArabellaTech_aa-stripe/aa_stripe/admin.py
aa_stripe.admin.StripeCustomerAdmin
class StripeCustomerAdmin(ReadOnly): list_display = ("id", "user", "created", "is_active") ordering = ("-created",)
class StripeCustomerAdmin(ReadOnly): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
3
3
0
3
3
2
0
3
3
2
0
3
0
0
6,336
ArabellaTech/aa-stripe
ArabellaTech_aa-stripe/aa_stripe/admin.py
aa_stripe.admin.StripeCouponAdmin
class StripeCouponAdmin(admin.ModelAdmin): form = StripeCouponForm list_display = ("id", "coupon_id", "amount_off", "percent_off", "currency", "created", "is_deleted", "is_created_at_stripe") list_filter = ("coupon_id", "amount_off", "percent_off", "currency", "created", "is_deleted", "is_created_at_stripe") readonly_fields = ("stripe_response", "created", "updated", "is_deleted") ordering = ("-created",) def get_queryset(self, request): return StripeCoupon.objects.all_with_deleted() def get_readonly_fields(self, request, obj=None): if obj: return [field for field in self.form.Meta.fields if field not in ["metadata"]] return self.readonly_fields
class StripeCouponAdmin(admin.ModelAdmin): def get_queryset(self, request): pass def get_readonly_fields(self, request, obj=None): pass
3
0
4
1
3
0
2
0
1
1
1
0
2
0
2
2
17
3
14
8
11
0
12
8
9
2
1
1
3
6,337
ArabellaTech/aa-stripe
ArabellaTech_aa-stripe/aa_stripe/admin.py
aa_stripe.admin.StripeChargeAdmin
class StripeChargeAdmin(ReadOnly): search_fields = ("user__email", "customer__stripe_customer_id") list_display = ("id", "user", "stripe_customer_id", "created", "updated", "object_id", "is_charged", "amount") list_filter = ("created", "updated", "is_charged") ordering = ("-created",) def stripe_customer_id(self, obj): if obj.customer: return obj.customer.stripe_customer_id
class StripeChargeAdmin(ReadOnly): def stripe_customer_id(self, obj): pass
2
0
3
0
3
0
2
0
1
0
0
0
1
0
1
4
9
1
8
6
6
0
8
6
6
2
3
1
2
6,338
ArabellaTech/aa-stripe
ArabellaTech_aa-stripe/aa_stripe/admin.py
aa_stripe.admin.ReadOnlyBase
class ReadOnlyBase(object): extra = 0 extra_fields = [] def get_readonly_fields(self, request, obj=None): from itertools import chain field_names = list(set(chain.from_iterable( (field.name, field.attname) if hasattr(field, 'attname') else (field.name,) for field in self.model._meta.get_fields() # For complete backwards compatibility, you may want to exclude # GenericForeignKey from the results. # if not (field.many_to_one and field.related_model is None) # remove all related fields because it causes admin to break if not field.one_to_many and not field.one_to_one and not field.auto_created ))) fields = list(self.extra_fields) for field in field_names: if not hasattr(self, "editable_fields") or (field not in self.editable_fields): fields.append(field) return fields def has_add_permission(self, request): return False def has_delete_permission(self, *args, **kwargs): return False
class ReadOnlyBase(object): def get_readonly_fields(self, request, obj=None): pass def has_add_permission(self, request): pass def has_delete_permission(self, *args, **kwargs): pass
4
0
7
0
5
1
2
0.21
1
3
0
1
3
0
3
3
26
3
19
9
14
4
15
9
10
4
1
2
6
6,339
ArabellaTech/aa-stripe
ArabellaTech_aa-stripe/aa_stripe/api.py
aa_stripe.api.CouponDetailsAPI
class CouponDetailsAPI(RetrieveAPIView): queryset = StripeCoupon.objects.all() serializer_class = StripeCouponSerializer permission_classes = (IsAuthenticated,) lookup_field = "coupon_id"
class CouponDetailsAPI(RetrieveAPIView): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
5
0
5
5
4
0
5
5
4
0
1
0
0
6,340
ArabellaTech/aa-stripe
ArabellaTech_aa-stripe/aa_stripe/migrations/0015_auto_20170925_0838.py
aa_stripe.migrations.0015_auto_20170925_0838.Migration
class Migration(migrations.Migration): dependencies = [ ('aa_stripe', '0014_stripecharge_charge_attempt_failed'), ] operations = [ migrations.AlterField( model_name='stripesubscriptionplan', name='amount', field=models.BigIntegerField(help_text='In cents. More: https://stripe.com/docs/api#create_plan-amount'), ), ]
class Migration(migrations.Migration): pass
1
0
0
0
0
0
0
0.09
1
0
0
0
0
0
0
0
13
2
11
3
10
1
3
3
2
0
1
0
0
6,341
ArabellaTech/aa-stripe
ArabellaTech_aa-stripe/aa_stripe/management/commands/charge_stripe.py
aa_stripe.management.commands.charge_stripe.Command
class Command(BaseCommand): help = "Charge stripe" def handle(self, *args, **options): charges = StripeCharge.objects.filter(is_charged=False, charge_attempt_failed=False, is_manual_charge=False) stripe.api_key = stripe_settings.API_KEY exceptions = [] for c in charges: try: c.charge() sleep(0.25) # 4 requests per second tops except Exception: exc_type, exc_value, exc_traceback = sys.exc_info() try: if client.is_enabled(): client.captureException() else: raise except NameError: exceptions.append({ "obj": c, "exc_type": exc_type, "exc_value": exc_value, "exc_traceback": exc_traceback, }) for e in exceptions: print("Exception happened") print("Charge id: {obj.id}".format(obj=e["obj"])) traceback.print_exception(e["exc_type"], e["exc_value"], e["exc_traceback"], file=sys.stdout) if exceptions: sys.exit(1)
class Command(BaseCommand): def handle(self, *args, **options): pass
2
0
29
1
28
1
7
0.03
1
3
1
0
1
0
1
1
32
2
30
8
28
1
24
8
22
7
1
4
7
6,342
ArabellaTech/aa-stripe
ArabellaTech_aa-stripe/aa_stripe/management/commands/check_pending_webhooks.py
aa_stripe.management.commands.check_pending_webhooks.StripePendingWebooksLimitExceeded
class StripePendingWebooksLimitExceeded(Exception): def __init__(self, pending_webhooks, site): self.message = "Pending webhooks threshold limit exceeded, current threshold is {}".format( stripe_settings.PENDING_WEBHOOKS_THRESHOLD) # send email to admins server_env = getattr(settings, "ENV_PREFIX", None) email_message = "Pending webhooks for {domain} at {now}:\n\n{webhooks}".format( domain=site.domain, now=now(), webhooks="\n".join(webhook["id"] for webhook in pending_webhooks) ) if server_env: email_message += "\n\nServer environment: {}".format(server_env) mail_admins("Stripe webhooks pending threshold exceeded", email_message) super(StripePendingWebooksLimitExceeded, self).__init__(self.message)
class StripePendingWebooksLimitExceeded(Exception): def __init__(self, pending_webhooks, site): pass
2
0
13
1
11
1
2
0.08
1
1
0
0
1
1
1
11
14
1
12
5
10
1
9
5
7
2
3
1
2
6,343
ArabellaTech/aa-stripe
ArabellaTech_aa-stripe/aa_stripe/migrations/0013_stripesubscription_at_period_end.py
aa_stripe.migrations.0013_stripesubscription_at_period_end.Migration
class Migration(migrations.Migration): dependencies = [ ('aa_stripe', '0012_auto_20170908_1150'), ] operations = [ migrations.AddField( model_name='stripesubscription', name='at_period_end', field=models.BooleanField(default=False), ), ]
class Migration(migrations.Migration): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
13
2
11
3
10
0
3
3
2
0
1
0
0
6,344
ArabellaTech/aa-stripe
ArabellaTech_aa-stripe/aa_stripe/migrations/0012_auto_20170908_1150.py
aa_stripe.migrations.0012_auto_20170908_1150.Migration
class Migration(migrations.Migration): dependencies = [ ('aa_stripe', '0011_auto_20170907_1201'), ] operations = [ migrations.AlterModelOptions( name='stripewebhook', options={'ordering': ['-created']}, ), migrations.AlterField( model_name='stripecoupon', name='amount_off', field=models.DecimalField(blank=True, decimal_places=2, help_text='Amount (in the currency specified) that will be taken off the subtotal of any invoices for thiscustomer.', max_digits=10, null=True), ), migrations.AlterField( model_name='stripecoupon', name='currency', field=models.CharField(blank=True, choices=[('usd', 'USD'), ('aed', 'AED'), ('afn', 'AFN'), ('all', 'ALL'), ('amd', 'AMD'), ('ang', 'ANG'), ('aoa', 'AOA'), ('ars', 'ARS'), ('aud', 'AUD'), ('awg', 'AWG'), ('azn', 'AZN'), ('bam', 'BAM'), ('bbd', 'BBD'), ('bdt', 'BDT'), ('bgn', 'BGN'), ('bif', 'BIF'), ('bmd', 'BMD'), ('bnd', 'BND'), ('bob', 'BOB'), ('brl', 'BRL'), ('bsd', 'BSD'), ('bwp', 'BWP'), ('bzd', 'BZD'), ('cad', 'CAD'), ('cdf', 'CDF'), ('chf', 'CHF'), ('clp', 'CLP'), ('cny', 'CNY'), ('cop', 'COP'), ('crc', 'CRC'), ('cve', 'CVE'), ('czk', 'CZK'), ('djf', 'DJF'), ('dkk', 'DKK'), ('dop', 'DOP'), ('dzd', 'DZD'), ('egp', 'EGP'), ('etb', 'ETB'), ('eur', 'EUR'), ('fjd', 'FJD'), ('fkp', 'FKP'), ('gbp', 'GBP'), ('gel', 'GEL'), ('gip', 'GIP'), ('gmd', 'GMD'), ('gnf', 'GNF'), ('gtq', 'GTQ'), ('gyd', 'GYD'), ('hkd', 'HKD'), ('hnl', 'HNL'), ('hrk', 'HRK'), ('htg', 'HTG'), ('huf', 'HUF'), ('idr', 'IDR'), ('ils', 'ILS'), ('inr', 'INR'), ('isk', 'ISK'), ('jmd', 'JMD'), ('jpy', 'JPY'), ('kes', 'KES'), ('kgs', 'KGS'), ('khr', 'KHR'), ('kmf', 'KMF'), ('krw', 'KRW'), ('kyd', 'KYD'), ('kzt', 'KZT'), ('lak', 'LAK'), ('lbp', 'LBP'), ('lkr', 'LKR'), ('lrd', 'LRD'), ('lsl', 'LSL'), ('mad', 'MAD'), ('mdl', 'MDL'), ('mga', 'MGA'), ('mkd', 'MKD'), ('mmk', 'MMK'), ('mnt', 'MNT'), ('mop', 'MOP'), ('mro', 'MRO'), ('mur', 'MUR'), ('mvr', 'MVR'), ('mwk', 'MWK'), ('mxn', 'MXN'), ('myr', 'MYR'), ('mzn', 'MZN'), ('nad', 'NAD'), ('ngn', 'NGN'), ('nio', 'NIO'), ('nok', 'NOK'), ('npr', 'NPR'), ('nzd', 'NZD'), ('pab', 'PAB'), ('pen', 'PEN'), ('pgk', 'PGK'), ('php', 'PHP'), ('pkr', 'PKR'), ('pln', 'PLN'), ('pyg', 'PYG'), ('qar', 'QAR'), ('ron', 'RON'), ('rsd', 'RSD'), ('rub', 'RUB'), ('rwf', 'RWF'), ('sar', 'SAR'), ('sbd', 'SBD'), ('scr', 'SCR'), ('sek', 'SEK'), ('sgd', 'SGD'), ('shp', 'SHP'), ('sll', 'SLL'), ('sos', 'SOS'), ('srd', 'SRD'), ('std', 'STD'), ('svc', 'SVC'), ('szl', 'SZL'), ('thb', 'THB'), ('tjs', 'TJS'), ('top', 'TOP'), ('try', 'TRY'), ('ttd', 'TTD'), ('twd', 'TWD'), ('tzs', 'TZS'), ('uah', 'UAH'), ('ugx', 'UGX'), ('uyu', 'UYU'), ('uzs', 'UZS'), ('vnd', 'VND'), ('vuv', 'VUV'), ('wst', 'WST'), ('xaf', 'XAF'), ('xcd', 'XCD'), ('xof', 'XOF'), ('xpf', 'XPF'), ('yer', 'YER'), ('zar', 'ZAR'), ('zmw', 'ZMW')], help_text='If amount_off has been set, the three-letter ISO code for the currency of the amount to take off.', max_length=3, null=True), ), migrations.AlterField( model_name='stripecoupon', name='duration_in_months', field=models.PositiveIntegerField(blank=True, help_text='If duration is repeating, the number of months the coupon applies. Null if coupon duration is forever or once.', null=True), ), migrations.AlterField( model_name='stripecoupon', name='metadata', field=django_extensions.db.fields.json.JSONField(default=dict, help_text='Set of key/value pairs that you can attach to an object. It can be useful for storing additional information about the object in a structured format.'), ), migrations.AlterField( model_name='stripecoupon', name='percent_off', field=models.PositiveIntegerField(blank=True, help_text='Percent that will be taken off the subtotal of any invoicesfor this customer for the duration of the coupon. For example, a coupon with percent_off of 50 will make a $100 invoice $50 instead.', null=True), ), ]
class Migration(migrations.Migration): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
37
2
35
3
34
0
3
3
2
0
1
0
0
6,345
ArabellaTech/aa-stripe
ArabellaTech_aa-stripe/aa_stripe/migrations/0011_auto_20170907_1201.py
aa_stripe.migrations.0011_auto_20170907_1201.Migration
class Migration(migrations.Migration): dependencies = [ ('aa_stripe', '0010_auto_20170822_1004'), ] operations = [ migrations.AddField( model_name='stripewebhook', name='parse_error', field=models.TextField(blank=True), ), ]
class Migration(migrations.Migration): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
13
2
11
3
10
0
3
3
2
0
1
0
0
6,346
ArabellaTech/aa-stripe
ArabellaTech_aa-stripe/tests/test_subscription_plans.py
tests.test_subscription_plans.TestSubscriptionsPlans
class TestSubscriptionsPlans(TestCase): def setUp(self): self.user = UserModel.objects.create(email="foo@bar.bar", username="foo", password="dump-password") def test_plan_creation(self): self.assertEqual(StripeSubscriptionPlan.objects.count(), 0) plan = StripeSubscriptionPlan.objects.create( source={"a": "b"}, amount=5000, name="gold-basic", interval=StripeSubscriptionPlan.INTERVAL_MONTH, interval_count=3, ) self.assertFalse(plan.is_created_at_stripe) with requests_mock.Mocker() as m: m.register_uri('POST', 'https://api.stripe.com/v1/plans', [{'text': json.dumps({ "id": plan.id, "object": "plan", "amount": 5000, "created": 1496921795, "currency": "usd", "interval": "month", "interval_count": 3, "livemode": False, "metadata": {}, "name": "Gold basic", "statement_descriptor": None, "trial_period_days": None })}]) plan.create_at_stripe() self.assertTrue(plan.is_created_at_stripe) self.assertEqual(plan.stripe_response["id"], plan.id) self.assertEqual(plan.stripe_response["amount"], 5000)
class TestSubscriptionsPlans(TestCase): def setUp(self): pass def test_plan_creation(self): pass
3
0
16
0
16
0
1
0
1
1
1
0
2
1
2
2
33
1
32
6
29
0
13
5
10
1
1
1
2
6,347
ArabellaTech/aa-stripe
ArabellaTech_aa-stripe/aa_stripe/migrations/0009_auto_20170725_1205.py
aa_stripe.migrations.0009_auto_20170725_1205.Migration
class Migration(migrations.Migration): dependencies = [ ('aa_stripe', '0008_auto_20170630_0734'), ] operations = [ migrations.AlterField( model_name='stripecharge', name='created', field=models.DateTimeField(auto_now_add=True), ), migrations.AlterField( model_name='stripecustomer', name='created', field=models.DateTimeField(auto_now_add=True), ), migrations.AlterField( model_name='stripesubscription', name='created', field=models.DateTimeField(auto_now_add=True), ), migrations.AlterField( model_name='stripesubscriptionplan', name='created', field=models.DateTimeField(auto_now_add=True), ), migrations.AlterField( model_name='stripewebhook', name='created', field=models.DateTimeField(auto_now_add=True), ), ]
class Migration(migrations.Migration): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
33
2
31
3
30
0
3
3
2
0
1
0
0
6,348
ArabellaTech/aa-stripe
ArabellaTech_aa-stripe/aa_stripe/migrations/0008_auto_20170630_0734.py
aa_stripe.migrations.0008_auto_20170630_0734.Migration
class Migration(migrations.Migration): dependencies = [ ('contenttypes', '0002_remove_content_type_name'), ('aa_stripe', '0007_auto_20170630_0557'), ] operations = [ migrations.AddField( model_name='stripecharge', name='content_type', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='contenttypes.ContentType'), ), migrations.AddField( model_name='stripecharge', name='object_id', field=models.PositiveIntegerField(db_index=True, null=True), ), ]
class Migration(migrations.Migration): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
19
2
17
3
16
0
3
3
2
0
1
0
0
6,349
ArabellaTech/aa-stripe
ArabellaTech_aa-stripe/aa_stripe/migrations/0007_auto_20170630_0557.py
aa_stripe.migrations.0007_auto_20170630_0557.Migration
class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(USER_MODEL), ('aa_stripe', '0006_subscription_end_cancel'), ] operations = [ migrations.AlterField( model_name='stripecharge', name='user', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='stripe_charges', to=USER_MODEL), ), migrations.AlterField( model_name='stripecustomer', name='user', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='stripe_customers', to=USER_MODEL), ), migrations.AlterField( model_name='stripesubscription', name='user', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='stripe_subscriptions', to=USER_MODEL), ), ]
class Migration(migrations.Migration): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
27
2
25
3
24
0
3
3
2
0
1
0
0
6,350
ArabellaTech/aa-stripe
ArabellaTech_aa-stripe/aa_stripe/management/commands/check_pending_webhooks.py
aa_stripe.management.commands.check_pending_webhooks.Command
class Command(BaseCommand): help = "Check pending webhooks at Stripe API" def add_arguments(self, parser): parser.add_argument( "--site", help="Site id to use while running the command. First site in the database will be used if not provided." ) def handle(self, *args, **options): stripe.api_key = stripe_settings.API_KEY site_id = options.get("site") site = Site.objects.get(pk=site_id) if site_id else Site.objects.all()[0] pending_webhooks = [] last_event = StripeWebhook.objects.first() last_event_id = last_event.id if last_event else None try: if last_event: stripe.Event.retrieve(last_event_id) except stripe.error.InvalidRequestError: last_event_id = None while True: event_list = stripe.Event.list(ending_before=last_event_id, limit=100) # 100 is the maximum pending_webhooks += event_list["data"] if len(pending_webhooks) > stripe_settings.PENDING_WEBHOOKS_THRESHOLD: raise StripePendingWebooksLimitExceeded(pending_webhooks, site) if not event_list["has_more"]: break else: last_event_id = event_list["data"][-1]["id"]
class Command(BaseCommand): def add_arguments(self, parser): pass def handle(self, *args, **options): pass
3
0
15
2
13
1
5
0.04
1
2
2
0
2
0
2
2
34
6
28
10
25
1
24
10
21
8
1
2
9
6,351
ArabellaTech/aa-stripe
ArabellaTech_aa-stripe/aa_stripe/migrations/0006_subscription_end_cancel.py
aa_stripe.migrations.0006_subscription_end_cancel.Migration
class Migration(migrations.Migration): dependencies = [ ('aa_stripe', '0005_auto_20170613_0614'), ] operations = [ migrations.AddField( model_name='stripesubscription', name='end_date', field=models.DateField(null=True, blank=True, db_index=True), ), migrations.AddField( model_name='stripesubscription', name='canceled_at', field=models.DateTimeField(null=True, blank=True, db_index=True), ), ]
class Migration(migrations.Migration): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
18
2
16
3
15
0
3
3
2
0
1
0
0
6,352
ArabellaTech/aa-stripe
ArabellaTech_aa-stripe/aa_stripe/migrations/0004_auto_20170613_0419.py
aa_stripe.migrations.0004_auto_20170613_0419.Migration
class Migration(migrations.Migration): dependencies = [ ('aa_stripe', '0003_auto_20170608_1103'), ] operations = [ migrations.RemoveField( model_name='stripesubscription', name='application_fee_percent', ), migrations.AlterField( model_name='stripesubscriptionplan', name='currency', field=models.CharField(default='USD', help_text='3 letter ISO code, default USD, https://stripe.com/docs/api#create_plan-currency', max_length=3), ), ]
class Migration(migrations.Migration): pass
1
0
0
0
0
0
0
0.07
1
0
0
0
0
0
0
0
17
2
15
3
14
1
3
3
2
0
1
0
0
6,353
ArabellaTech/aa-stripe
ArabellaTech_aa-stripe/aa_stripe/migrations/0003_auto_20170608_1103.py
aa_stripe.migrations.0003_auto_20170608_1103.Migration
class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), migrations.swappable_dependency(USER_MODEL), ('aa_stripe', '0002_auto_20170607_0714'), ] operations = [ migrations.CreateModel( name='StripeCustomer', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('created', models.DateField(auto_now_add=True)), ('updated', models.DateTimeField(auto_now=True)), ('stripe_response', django_extensions.db.fields.json.JSONField(default=dict)), ('stripe_js_response', django_extensions.db.fields.json.JSONField(default=dict)), ('stripe_customer_id', models.CharField(max_length=255)), ('is_active', models.BooleanField(default=True)), ('is_created_at_stripe', models.BooleanField(default=False)), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='stripe_customers', to=USER_MODEL)), ], options={ 'ordering': ['id'], }, ), migrations.CreateModel( name='StripeSubscription', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('created', models.DateField(auto_now_add=True)), ('updated', models.DateTimeField(auto_now=True)), ('stripe_response', django_extensions.db.fields.json.JSONField(default=dict)), ('stripe_subscription_id', models.CharField(blank=True, max_length=255)), ('is_created_at_stripe', models.BooleanField(default=False)), ('status', models.CharField(blank=True, choices=[('trialing', 'trialing'), ('active', 'active'), ('past_due', 'past_due'), ('canceled', 'canceled'), ('unpaid', 'unpaid')], help_text='https://stripe.com/docs/api/python#subscription_object-status, empty if not sent created at stripe', max_length=255)), ('metadata', django_extensions.db.fields.json.JSONField(default=dict, help_text='https://stripe.com/docs/api/python#create_subscription-metadata')), ('tax_percent', models.DecimalField(decimal_places=2, default=0, help_text='https://stripe.com/docs/api/python#subscription_object-tax_percent', max_digits=3, validators=[django.core.validators.MinValueValidator(0), django.core.validators.MaxValueValidator(100)])), ('application_fee_percent', models.DecimalField(decimal_places=2, default=0, help_text='https://stripe.com/docs/api/python#create_subscription-application_fee_percent', max_digits=3, validators=[django.core.validators.MinValueValidator(0), django.core.validators.MaxValueValidator(100)])), ('coupon', models.CharField(blank=True, help_text='https://stripe.com/docs/api/python#create_subscription-coupon', max_length=255)), ('customer', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='aa_stripe.StripeCustomer')), ], options={ 'abstract': False, }, ), migrations.CreateModel( name='StripeSubscriptionPlan', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('created', models.DateField(auto_now_add=True)), ('updated', models.DateTimeField(auto_now=True)), ('stripe_response', django_extensions.db.fields.json.JSONField(default=dict)), ('is_created_at_stripe', models.BooleanField(default=False)), ('source', django_extensions.db.fields.json.JSONField(blank=True, default=dict, help_text='Source of the plan, ie: {"prescription": 1}')), ('amount', models.IntegerField(help_text='In cents. More: https://stripe.com/docs/api#create_plan-amount')), ('currency', models.CharField(default='USD', help_text='3 letter ISO code, default USD, , https://stripe.com/docs/api#create_plan-currency', max_length=3)), ('name', models.CharField(help_text='Name of the plan, to be displayed on invoices and in the web interface.', max_length=255)), ('interval', models.CharField(choices=[('day', 'day'), ('week', 'week'), ('month', 'month'), ('year', 'year')], help_text='Specifies billing frequency. Either day, week, month or year.', max_length=10)), ('interval_count', models.IntegerField(default=1, validators=[django.core.validators.MinValueValidator(1)])), ('metadata', django_extensions.db.fields.json.JSONField(default=dict, help_text='A set of key/value pairs that you can attach to a plan object. It can be useful for storing additional information about the plan in a structured format.')), ('statement_descriptor', models.CharField(blank=True, help_text='An arbitrary string to be displayed on your customer’s credit card statement.', max_length=22)), ('trial_period_days', models.IntegerField(default=0, help_text='Specifies a trial period in (an integer number of) days. If you include a trial period, the customer won’t be billed for the first time until the trial period ends. If the customer cancels before the trial period is over, she’ll never be billed at all.', validators=[django.core.validators.MinValueValidator(0)])), ], options={ 'abstract': False, }, ), migrations.CreateModel( name='StripeWebhook', fields=[ ('id', models.CharField(max_length=255, primary_key=True, serialize=False)), ('created', models.DateField(auto_now_add=True)), ('updated', models.DateTimeField(auto_now=True)), ('is_parsed', models.BooleanField(default=False)), ('raw_data', django_extensions.db.fields.json.JSONField(default=dict)), ], ), migrations.RemoveField( model_name='stripetoken', name='user', ), migrations.RemoveField( model_name='stripecharge', name='token', ), migrations.AddField( model_name='stripecharge', name='stripe_response', field=django_extensions.db.fields.json.JSONField(default=dict), ), migrations.DeleteModel( name='StripeToken', ), migrations.AddField( model_name='stripesubscription', name='plan', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='aa_stripe.StripeSubscriptionPlan'), ), migrations.AddField( model_name='stripesubscription', name='user', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='stripe_subscriptions', to=USER_MODEL), ), migrations.AddField( model_name='stripecharge', name='customer', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='aa_stripe.StripeCustomer'), ), ]
class Migration(migrations.Migration): pass
1
0
0
0
0
0
0
0.06
1
0
0
0
0
0
0
0
112
2
110
3
109
7
3
3
2
0
1
0
0
6,354
ArabellaTech/aa-stripe
ArabellaTech_aa-stripe/aa_stripe/migrations/0002_auto_20170607_0714.py
aa_stripe.migrations.0002_auto_20170607_0714.Migration
class Migration(migrations.Migration): dependencies = [ ('aa_stripe', '0001_initial'), ] operations = [ migrations.RenameField( model_name='stripetoken', old_name='content', new_name='stripe_js_response', ), migrations.AlterField( model_name='stripecharge', name='user', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='stripe_charges', to=settings.AUTH_USER_MODEL), ), migrations.AlterField( model_name='stripetoken', name='user', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='stripe_tokens', to=settings.AUTH_USER_MODEL), ), ]
class Migration(migrations.Migration): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
23
2
21
3
20
0
3
3
2
0
1
0
0
6,355
ArabellaTech/aa-stripe
ArabellaTech_aa-stripe/aa_stripe/migrations/0001_initial.py
aa_stripe.migrations.0001_initial.Migration
class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(USER_MODEL), ] operations = [ migrations.CreateModel( name='StripeCharge', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('created', models.DateField(auto_now_add=True)), ('updated', models.DateTimeField(auto_now=True)), ('amount', models.IntegerField(help_text='in cents', null=True)), ('is_charged', models.BooleanField(default=False)), ('stripe_charge_id', models.CharField(blank=True, max_length=255)), ('description', models.CharField(help_text='Description sent to Stripe', max_length=255)), ('comment', models.CharField(help_text='Comment for internal information', max_length=255)), ], ), migrations.CreateModel( name='StripeToken', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('created', models.DateField(auto_now_add=True)), ('updated', models.DateTimeField(auto_now=True)), ('content', django_extensions.db.fields.json.JSONField(default=dict)), ('customer_id', models.CharField(max_length=255)), ('is_active', models.BooleanField(default=True)), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=USER_MODEL)), ], options={ 'ordering': ['id'], }, ), migrations.AddField( model_name='stripecharge', name='token', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='aa_stripe.StripeToken'), ), migrations.AddField( model_name='stripecharge', name='user', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=USER_MODEL), ), ]
class Migration(migrations.Migration): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
49
3
46
4
45
0
4
4
3
0
1
0
0
6,356
ArabellaTech/aa-stripe
ArabellaTech_aa-stripe/aa_stripe/management/commands/refresh_customers.py
aa_stripe.management.commands.refresh_customers.Command
class Command(BaseCommand): help = "Update customers card data from Stripe API" def handle(self, *args, **options): stripe.api_key = stripe_settings.API_KEY last_customer = None retry_count = 0 updated_count = 0 start_time = timezone.now() verbose = options["verbosity"] >= 2 if verbose: print("Began refreshing customers") while True: try: response = stripe.Customer.list(limit=100, starting_after=last_customer) except stripe.error.StripeError: if retry_count > 5: raise retry_count += 1 continue else: retry_count = 0 for stripe_customer in response["data"]: updated_count += StripeCustomer.objects.filter(stripe_customer_id=stripe_customer["id"]).update( sources=stripe_customer["sources"]["data"], default_source=stripe_customer["default_source"] ) if not response["has_more"]: break if verbose: sys.stdout.write(".") # indicate that the command did not hung up sys.stdout.flush() last_customer = response["data"][-1] if verbose: if updated_count: print("\nCustomers updated: {} (took {:2f}s)".format( updated_count, (timezone.now() - start_time).total_seconds())) else: print("No customers were updated.")
class Command(BaseCommand): def handle(self, *args, **options): pass
2
0
40
5
35
1
10
0.03
1
1
1
0
1
0
1
1
43
6
37
10
35
1
33
10
31
10
1
3
10
6,357
ArabellaTech/aa-stripe
ArabellaTech_aa-stripe/aa_stripe/management/commands/refresh_coupons.py
aa_stripe.management.commands.refresh_coupons.Command
class Command(BaseCommand): help = "Update the coupon list from Stripe API" def handle(self, *args, **options): stripe.api_key = stripe_settings.API_KEY counts = { "created": 0, "updated": 0, "deleted": 0 } active_coupons_ids = [] last_stripe_coupon = None while True: stripe_coupon_list = stripe.Coupon.list(starting_after=last_stripe_coupon) for stripe_coupon in stripe_coupon_list["data"]: try: coupon = StripeCoupon.objects.get( coupon_id=stripe_coupon.id, created=timestamp_to_timezone_aware_date(stripe_coupon["created"]), is_deleted=False) counts["updated"] += coupon.update_from_stripe_data(stripe_coupon) except StripeCoupon.DoesNotExist: # already have the data - we do not need to call Stripe API again coupon = StripeCoupon(coupon_id=stripe_coupon.id) coupon.update_from_stripe_data(stripe_coupon, commit=False) super(StripeCoupon, coupon).save() counts["created"] += 1 # indicate which coupons should have is_deleted=False active_coupons_ids.append(coupon.pk) if not stripe_coupon_list["has_more"]: break else: last_stripe_coupon = stripe_coupon_list["data"][-1] # update can be used here, because those coupons does not exist in the Stripe API anymore coupons_to_delete = StripeCoupon.objects.exclude(pk__in=active_coupons_ids) for coupon in coupons_to_delete: coupon.is_deleted = True super(StripeCoupon, coupon).save() # make sure pre/post save signals are triggered without calling API counts["deleted"] += coupons_to_delete.count() if options.get("verbosity") > 1: print("Coupons created: {created}, updated: {updated}, deleted: {deleted}".format(**counts))
class Command(BaseCommand): def handle(self, *args, **options): pass
2
0
42
5
34
4
7
0.11
1
2
1
0
1
0
1
1
45
6
36
10
34
4
29
10
27
7
1
3
7
6,358
ArabellaTech/aa-stripe
ArabellaTech_aa-stripe/aa_stripe/management/commands/end_subscriptions.py
aa_stripe.management.commands.end_subscriptions.Command
class Command(BaseCommand): """ Terminates outdated subscriptions at period end. Should be run hourly. Exceptions are queued and returned at the end. """ help = "Terminate outdated subscriptions" def handle(self, *args, **options): subscriptions = StripeSubscription.get_subcriptions_for_cancel() exceptions = [] for subscription in subscriptions: try: subscription.cancel(at_period_end=True) sleep(0.25) # 4 requests per second tops except Exception: exc_type, exc_value, exc_traceback = sys.exc_info() try: if client.is_enabled(): client.captureException() else: raise except NameError: exceptions.append({ "obj": subscription, "exc_type": exc_type, "exc_value": exc_value, "exc_traceback": exc_traceback, }) for e in exceptions: print("Exception happened") print("Subscription id: {obj.id}".format(obj=e["obj"])) traceback.print_exception(e["exc_type"], e["exc_value"], e["exc_traceback"], file=sys.stdout) if exceptions: sys.exit(1)
class Command(BaseCommand): ''' Terminates outdated subscriptions at period end. Should be run hourly. Exceptions are queued and returned at the end. ''' def handle(self, *args, **options): pass
2
1
28
1
27
1
7
0.21
1
3
1
0
1
0
1
1
38
4
29
8
27
6
23
8
21
7
1
4
7
6,359
ArabellaTech/aa-stripe
ArabellaTech_aa-stripe/aa_stripe/migrations/0005_auto_20170613_0614.py
aa_stripe.migrations.0005_auto_20170613_0614.Migration
class Migration(migrations.Migration): dependencies = [ ('aa_stripe', '0004_auto_20170613_0419'), ] operations = [ migrations.AlterField( model_name='stripecharge', name='stripe_charge_id', field=models.CharField(blank=True, db_index=True, max_length=255), ), migrations.AlterField( model_name='stripecustomer', name='stripe_customer_id', field=models.CharField(db_index=True, max_length=255), ), migrations.AlterField( model_name='stripesubscription', name='stripe_subscription_id', field=models.CharField(blank=True, db_index=True, max_length=255), ), ]
class Migration(migrations.Migration): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
23
2
21
3
20
0
3
3
2
0
1
0
0
6,360
ArabellaTech/django-basic-cms
ArabellaTech_django-basic-cms/basic_cms/test_runner.py
basic_cms.test_runner.PageTestSuiteRunner
class PageTestSuiteRunner(DiscoverRunner): def run_tests(self, test_labels=('basic_cms',), extra_tests=None): if coverage: cov = coverage() cov.erase() cov.use_cache(0) cov.start() results = DiscoverRunner.run_tests(self, test_labels, extra_tests) if coverage: cov.stop() app = get_app('basic_cms') modules = get_all_coverage_modules(app) cov.html_report(modules, directory='coverage') sys.exit(results)
class PageTestSuiteRunner(DiscoverRunner): def run_tests(self, test_labels=('basic_cms',), extra_tests=None): pass
2
0
17
4
13
0
3
0
1
0
0
0
1
0
1
1
19
5
14
6
12
0
14
6
12
3
1
1
3
6,361
ArabellaTech/django-basic-cms
ArabellaTech_django-basic-cms/basic_cms/managers.py
basic_cms.managers.ContentManager
class ContentManager(models.Manager): """:class:`Content <pages.models.Content>` manager methods""" PAGE_CONTENT_DICT_KEY = "page_content_dict_%d_%s_%d" def sanitize(self, content): """Sanitize a string in order to avoid possible XSS using ``html5lib``.""" import html5lib from html5lib import sanitizer p = html5lib.HTMLParser(tokenizer=sanitizer.HTMLSanitizer) dom_tree = p.parseFragment(content) return dom_tree.text def set_or_create_content(self, page, language, ctype, body): """Set or create a :class:`Content <pages.models.Content>` for a particular page and language. :param page: the concerned page object. :param language: the wanted language. :param ctype: the content type. :param body: the content of the Content object. """ if settings.PAGE_SANITIZE_USER_INPUT: body = self.sanitize(body) try: content = self.filter(page=page, language=language, type=ctype).latest('creation_date') content.body = body except self.model.DoesNotExist: content = self.model(page=page, language=language, body=body, type=ctype) content.save() return content def create_content_if_changed(self, page, language, ctype, body): """Create a :class:`Content <pages.models.Content>` for a particular page and language only if the content has changed from the last time. :param page: the concerned page object. :param language: the wanted language. :param ctype: the content type. :param body: the content of the Content object. """ if settings.PAGE_SANITIZE_USER_INPUT: body = self.sanitize(body) try: content = self.filter(page=page, language=language, type=ctype).latest('creation_date') if content.body == body: return content except self.model.DoesNotExist: pass content = self.create(page=page, language=language, body=body, type=ctype) # Delete old revisions if settings.PAGE_CONTENT_REVISION_DEPTH: oldest_content = self.filter(page=page, language=language, type=ctype).order_by('-creation_date')[settings.PAGE_CONTENT_REVISION_DEPTH:] for c in oldest_content: c.delete() return content def get_content_object(self, page, language, ctype): """Gets the latest published :class:`Content <pages.models.Content>` for a particular page, language and placeholder type.""" params = { 'language': language, 'type': ctype, 'page': page } if page.freeze_date: params['creation_date__lte'] = page.freeze_date return self.filter(**params).latest() def get_content(self, page, language, ctype, language_fallback=False): """Gets the latest content string for a particular page, language and placeholder. :param page: the concerned page object. :param language: the wanted language. :param ctype: the content type. :param language_fallback: fallback to another language if ``True``. """ if not language: language = settings.PAGE_DEFAULT_LANGUAGE frozen = int(bool(page.freeze_date)) key = self.PAGE_CONTENT_DICT_KEY % (page.id, ctype, frozen) if page._content_dict is None: page._content_dict = dict() if page._content_dict.get(key, None): content_dict = page._content_dict.get(key) else: content_dict = cache.get(key) # fill a dict object for each language, that will create # P * L queries. # L == number of language, P == number of placeholder in the page. # Once generated the result is cached. if not content_dict: content_dict = {} for lang in settings.PAGE_LANGUAGES: try: content = self.get_content_object(page, lang[0], ctype) content_dict[lang[0]] = content.body except self.model.DoesNotExist: content_dict[lang[0]] = '' page._content_dict[key] = content_dict cache.set(key, content_dict) if language in content_dict and content_dict[language]: return content_dict[language] if language_fallback: for lang in settings.PAGE_LANGUAGES: if lang[0] in content_dict and content_dict[lang[0]]: return content_dict[lang[0]] return '' def get_content_slug_by_slug(self, slug): """Returns the latest :class:`Content <pages.models.Content>` slug object that match the given slug for the current site domain. :param slug: the wanted slug. """ content = self.filter(type='slug', body=slug) if settings.PAGE_USE_SITE_ID: content = content.filter(page__sites__id=settings.SITE_ID) try: content = content.latest('creation_date') except self.model.DoesNotExist: return None else: return content def get_page_ids_by_slug(self, slug): """Return all page's id matching the given slug. This function also returns pages that have an old slug that match. :param slug: the wanted slug. """ ids = self.filter(type='slug', body=slug).values('page_id').annotate( max_creation_date=Max('creation_date') ) return [content['page_id'] for content in ids]
class ContentManager(models.Manager): ''':class:`Content <pages.models.Content>` manager methods''' def sanitize(self, content): '''Sanitize a string in order to avoid possible XSS using ``html5lib``.''' pass def set_or_create_content(self, page, language, ctype, body): '''Set or create a :class:`Content <pages.models.Content>` for a particular page and language. :param page: the concerned page object. :param language: the wanted language. :param ctype: the content type. :param body: the content of the Content object. ''' pass def create_content_if_changed(self, page, language, ctype, body): '''Create a :class:`Content <pages.models.Content>` for a particular page and language only if the content has changed from the last time. :param page: the concerned page object. :param language: the wanted language. :param ctype: the content type. :param body: the content of the Content object. ''' pass def get_content_object(self, page, language, ctype): '''Gets the latest published :class:`Content <pages.models.Content>` for a particular page, language and placeholder type.''' pass def get_content_object(self, page, language, ctype): '''Gets the latest content string for a particular page, language and placeholder. :param page: the concerned page object. :param language: the wanted language. :param ctype: the content type. :param language_fallback: fallback to another language if ``True``. ''' pass def get_content_slug_by_slug(self, slug): '''Returns the latest :class:`Content <pages.models.Content>` slug object that match the given slug for the current site domain. :param slug: the wanted slug. ''' pass def get_page_ids_by_slug(self, slug): '''Return all page's id matching the given slug. This function also returns pages that have an old slug that match. :param slug: the wanted slug. ''' pass
8
8
20
2
13
6
4
0.46
1
4
0
0
7
0
7
7
151
20
90
25
80
41
78
25
68
11
1
3
27
6,362
ArabellaTech/django-basic-cms
ArabellaTech_django-basic-cms/basic_cms/widgets.py
basic_cms.widgets.markItUpHTML
class markItUpHTML(Textarea): """markItUpHTML widget.""" class Media: js = [join(PAGES_MEDIA_URL, path) for path in ( 'javascript/jquery.js', 'markitup/jquery.markitup.js', 'markitup/sets/default/set.js', )] css = { 'all': [join(PAGES_MEDIA_URL, path) for path in ( 'markitup/skins/simple/style.css', 'markitup/sets/default/style.css', )] } def render(self, name, value, attrs=None, **kwargs): rendered = super(markItUpHTML, self).render(name, value, attrs) context = { 'name': name, } return rendered + mark_safe(render_to_string( 'pages/widgets/markituphtml.html', context))
class markItUpHTML(Textarea): '''markItUpHTML widget.''' class Media: def render(self, name, value, attrs=None, **kwargs): pass
3
1
7
0
7
0
1
0.05
1
1
0
0
1
0
1
1
23
2
20
7
17
1
8
7
5
1
1
0
1
6,363
ArabellaTech/django-basic-cms
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/ArabellaTech_django-basic-cms/basic_cms/widgets.py
basic_cms.widgets.markItUpMarkdown.Media
class Media: js = [join(PAGES_MEDIA_URL, path) for path in ( 'javascript/jquery.js', 'markitup/jquery.markitup.js', 'markitup/sets/markdown/set.js', )] css = { 'all': [join(PAGES_MEDIA_URL, path) for path in ( 'markitup/skins/simple/style.css', 'markitup/sets/markdown/style.css', )] }
class Media: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
12
0
12
3
11
0
3
3
2
0
0
0
0
6,364
ArabellaTech/django-basic-cms
ArabellaTech_django-basic-cms/basic_cms/widgets.py
basic_cms.widgets.markItUpRest
class markItUpRest(Textarea): """markItUpRest widget.""" class Media: js = [join(PAGES_MEDIA_URL, path) for path in ( 'javascript/jquery.js', 'markitup/jquery.markitup.js', 'markitup/sets/rst/set.js', )] css = { 'all': [join(PAGES_MEDIA_URL, path) for path in ( 'markitup/skins/simple/style.css', 'markitup/sets/rst/style.css', )] } def render(self, name, value, attrs=None, **kwargs): rendered = super(markItUpRest, self).render(name, value, attrs) context = { 'name': name, } return rendered + mark_safe(render_to_string( 'pages/widgets/markituprest.html', context))
class markItUpRest(Textarea): '''markItUpRest widget.''' class Media: def render(self, name, value, attrs=None, **kwargs): pass
3
1
7
0
7
0
1
0.05
1
1
0
0
1
0
1
1
23
2
20
7
17
1
8
7
5
1
1
0
1
6,365
ArabellaTech/django-basic-cms
ArabellaTech_django-basic-cms/basic_cms/widgets.py
basic_cms.widgets.markItUpMarkdown
class markItUpMarkdown(Textarea): """markItUpMarkdown widget.""" class Media: js = [join(PAGES_MEDIA_URL, path) for path in ( 'javascript/jquery.js', 'markitup/jquery.markitup.js', 'markitup/sets/markdown/set.js', )] css = { 'all': [join(PAGES_MEDIA_URL, path) for path in ( 'markitup/skins/simple/style.css', 'markitup/sets/markdown/style.css', )] } def render(self, name, value, attrs=None, **kwargs): rendered = super(markItUpMarkdown, self).render(name, value, attrs) context = { 'name': name, } return rendered + mark_safe(render_to_string( 'pages/widgets/markitupmarkdown.html', context))
class markItUpMarkdown(Textarea): '''markItUpMarkdown widget.''' class Media: def render(self, name, value, attrs=None, **kwargs): pass
3
1
7
0
7
0
1
0.05
1
1
0
0
1
0
1
1
23
2
20
7
17
1
8
7
5
1
1
0
1
6,366
ArabellaTech/django-basic-cms
ArabellaTech_django-basic-cms/basic_cms/tests/test_regression.py
basic_cms.tests.test_regression.RegressionTestCase
class RegressionTestCase(TestCase): """Django page CMS test suite class""" def test_calculated_status_bug(self): """ Test the issue 100 http://code.google.com/p/django-page-cms/issues/detail?id=100 """ self.set_setting("PAGE_SHOW_START_DATE", True) c = self.get_admin_client() c.login(username= 'batiste', password='b') page_data = self.get_new_page_data() page_data['slug'] = 'page1' # create a page for the example otherwise you will get a Http404 error response = c.post('/admin/basic_cms/page/add/', page_data) page1 = Content.objects.get_content_slug_by_slug('page1').page page1.status = Page.DRAFT page1.save() self.assertEqual(page1.calculated_status, Page.DRAFT) def test_slug_bug(self): """ Test the issue 97 http://code.google.com/p/django-page-cms/issues/detail?id=97 """ c = self.get_admin_client() c.login(username= 'batiste', password='b') page_data = self.get_new_page_data() page_data['slug'] = 'page1' # create a page for the example otherwise you will get a Http404 error response = c.post('/admin/basic_cms/page/add/', page_data) response = c.get('/pages/page1/') self.assertEqual(response.status_code, 200) try: response = c.get(self.get_page_url('toto/page1/')) except TemplateDoesNotExist as e: if e.args != ('404.html',): raise def test_bug_152(self): """Test bug 152 http://code.google.com/p/django-page-cms/issues/detail?id=152""" from basic_cms.utils import get_placeholders self.assertEqual( str(get_placeholders('pages/tests/test1.html')), "[<Placeholder Node: body>]" ) def test_bug_162(self): """Test bug 162 http://code.google.com/p/django-page-cms/issues/detail?id=162""" c = self.get_admin_client() c.login(username= 'batiste', password='b') page_data = self.get_new_page_data() page_data['title'] = 'test-162-title' page_data['slug'] = 'test-162-slug' response = c.post('/admin/basic_cms/page/add/', page_data) self.assertRedirects(response, '/admin/basic_cms/page/') from basic_cms.http import get_request_mock request = get_request_mock() temp = loader.get_template('pages/tests/test2.html') render = temp.render(RequestContext(request, {})) self.assertTrue('test-162-slug' in render) def test_bug_172(self): """Test bug 167 http://code.google.com/p/django-page-cms/issues/detail?id=172""" c = self.get_admin_client() c.login(username= 'batiste', password='b') page_data = self.get_new_page_data() page_data['title'] = 'title-en-us' page_data['slug'] = 'slug' response = c.post('/admin/basic_cms/page/add/', page_data) page = Content.objects.get_content_slug_by_slug('slug').page Content(page=page, type='title', language='fr-ch', body="title-fr-ch").save() from basic_cms.http import get_request_mock request = get_request_mock() temp = loader.get_template('pages/tests/test3.html') render = temp.render(RequestContext(request, {'page':page})) self.assertTrue('title-en-us' in render) render = temp.render(RequestContext( request, {'page':page, 'lang':'fr-ch'} )) self.assertTrue('title-fr-ch' in render) def test_page_id_in_template(self): """Get a page in the templates via the page id.""" page = self.create_new_page() from basic_cms.http import get_request_mock request = get_request_mock() temp = loader.get_template('pages/tests/test4.html') render = temp.render(RequestContext(request, {})) self.assertTrue(page.title() in render) def test_bug_178(self): """http://code.google.com/p/django-page-cms/issues/detail?id=178""" from basic_cms.http import get_request_mock request = get_request_mock() temp = loader.get_template('pages/tests/test5.html') render = temp.render(RequestContext(request, {'page':None})) def test_language_fallback_bug(self): """Language fallback doesn't work properly.""" page = self.create_new_page() c = Content(page=page, type='new_type', body='toto', language='en-us') c.save() self.assertEqual( Content.objects.get_content(page, 'en-us', 'new_type'), 'toto' ) self.assertEqual( Content.objects.get_content(page, 'fr-ch', 'new_type'), '' ) self.assertEqual( Content.objects.get_content(page, 'fr-ch', 'new_type', True), 'toto' ) def test_bug_156(self): c = self.get_admin_client() c.login(username= 'batiste', password='b') page_data = self.get_new_page_data() page_data['slug'] = 'page1' page_data['title'] = 'title &' response = c.post('/admin/basic_cms/page/add/', page_data) page1 = Content.objects.get_content_slug_by_slug('page1').page page1.invalidate() c = Content.objects.get_content(page1, 'en-us', 'title') self.assertEqual(c, page_data['title']) def test_bug_181(self): c = self.get_admin_client() c.login(username= 'batiste', password='b') page_data = self.get_new_page_data(draft=True) page_data['slug'] = 'page1' # create a draft page and ensure we can view it response = c.post('/admin/basic_cms/page/add/', page_data) response = c.get(self.get_page_url('page1/')) self.assertEqual(response.status_code, 200) # logout and we should get a 404 c.logout() def func(): return c.get(self.get_page_url('page1/')) self.assert404(func) # login as a non staff user and we should get a 404 c.login(username= 'nonstaff', password='b') def func(): return c.get(self.get_page_url('page1/')) self.assert404(func) def test_urls_in_templates(self): """Test different ways of displaying urls in templates.""" page = self.create_new_page() from basic_cms.http import get_request_mock request = get_request_mock() temp = loader.get_template('pages/tests/test7.html') temp = loader.get_template('pages/tests/test6.html') render = temp.render(RequestContext(request, {'current_page':page})) self.assertTrue('t1_'+page.get_url_path() in render) self.assertTrue('t2_'+page.get_url_path() in render) self.assertTrue('t3_'+page.get_url_path() in render) self.assertTrue('t4_'+page.slug() in render) self.assertTrue('t5_'+page.slug() in render) def test_placeholder_cache_bug(self): """There was an bad bug caused when the page cache was filled the first time.""" from basic_cms.placeholders import PlaceholderNode page = self.new_page() placeholder = PlaceholderNode('test', page=page) placeholder.save(page, 'fr-ch', 'fr', True) placeholder.save(page, 'en-us', 'en', True) self.assertEqual( Content.objects.get_content(page, 'fr-ch', 'test'), 'fr' ) def test_pages_dynamic_tree_menu_bug(self): """ Test a bug with the dynamic tree template tag doesn't occur anymore. http://code.google.com/p/django-page-cms/issues/detail?id=209 """ page = self.new_page() context = Context({'current_page': page, 'lang':'en-us'}) pl1 = """{% load pages_tags %}{% pages_dynamic_tree_menu "wrong-slug" %}""" template = get_template_from_string(pl1) self.assertEqual(template.render(context), u'\n') def test_placeholder_bug(self): """Test placeholder with django template inheritance works prepoerly. http://code.google.com/p/django-page-cms/issues/detail?id=210 """ p1 = self.new_page(content={'slug':'test', 'one':'one', 'two': 'two'}) template = django.template.loader.get_template('pages/tests/extends.html') context = Context({'current_page': p1, 'lang':'en-us'}) renderer = template.render(context) self.assertTrue('one' in renderer) self.assertTrue('two' in renderer) from basic_cms.utils import get_placeholders self.assertEqual( str(get_placeholders('pages/tests/extends.html')), '[<Placeholder Node: one>, <Placeholder Node: two>]')
class RegressionTestCase(TestCase): '''Django page CMS test suite class''' def test_calculated_status_bug(self): ''' Test the issue 100 http://code.google.com/p/django-page-cms/issues/detail?id=100 ''' pass def test_slug_bug(self): ''' Test the issue 97 http://code.google.com/p/django-page-cms/issues/detail?id=97 ''' pass def test_bug_152(self): '''Test bug 152 http://code.google.com/p/django-page-cms/issues/detail?id=152''' pass def test_bug_162(self): '''Test bug 162 http://code.google.com/p/django-page-cms/issues/detail?id=162''' pass def test_bug_172(self): '''Test bug 167 http://code.google.com/p/django-page-cms/issues/detail?id=172''' pass def test_page_id_in_template(self): '''Get a page in the templates via the page id.''' pass def test_bug_178(self): '''http://code.google.com/p/django-page-cms/issues/detail?id=178''' pass def test_language_fallback_bug(self): '''Language fallback doesn't work properly.''' pass def test_bug_156(self): pass def test_bug_181(self): pass def func(): pass def func(): pass def test_urls_in_templates(self): '''Test different ways of displaying urls in templates.''' pass def test_placeholder_cache_bug(self): '''There was an bad bug caused when the page cache was filled the first time.''' pass def test_pages_dynamic_tree_menu_bug(self): ''' Test a bug with the dynamic tree template tag doesn't occur anymore. http://code.google.com/p/django-page-cms/issues/detail?id=209 ''' pass def test_placeholder_bug(self): '''Test placeholder with django template inheritance works prepoerly. http://code.google.com/p/django-page-cms/issues/detail?id=210 ''' pass
17
13
13
1
10
2
1
0.21
1
4
3
0
14
0
14
24
222
31
158
76
133
33
137
75
112
3
1
2
18
6,367
ArabellaTech/django-basic-cms
ArabellaTech_django-basic-cms/basic_cms/widgets.py
basic_cms.widgets.WYMEditor
class WYMEditor(Textarea): """WYMEditor widget.""" class Media: js = [join(PAGES_MEDIA_URL, path) for path in ( 'javascript/jquery.js', 'javascript/jquery.ui.js', 'javascript/jquery.ui.resizable.js', 'wymeditor/jquery.wymeditor.js', 'wymeditor/plugins/resizable/jquery.wymeditor.resizable.js', )] if "filebrowser" in getattr(settings, 'INSTALLED_APPS', []): js.append(join(PAGES_MEDIA_URL, 'wymeditor/plugins/filebrowser/jquery.wymeditor.filebrowser.js')) def __init__(self, language=None, attrs=None, **kwargs): self.language = language or getattr(settings, 'LANGUAGE_CODE') self.attrs = {'class': 'wymeditor'} if attrs: self.attrs.update(attrs) super(WYMEditor, self).__init__(attrs) def render(self, name, value, attrs=None, **kwargs): rendered = super(WYMEditor, self).render(name, value, attrs) context = { 'name': name, 'lang': self.language[:2], 'language': self.language, 'PAGES_MEDIA_URL': PAGES_MEDIA_URL, } context['page_link_wymeditor'] = 1 context['page_list'] = Page.objects.all().order_by('tree_id', 'lft') context['filebrowser'] = 0 if "filebrowser" in getattr(settings, 'INSTALLED_APPS', []): context['filebrowser'] = 1 return rendered + mark_safe(render_to_string( 'pages/widgets/wymeditor.html', context))
class WYMEditor(Textarea): '''WYMEditor widget.''' class Media: def __init__(self, language=None, attrs=None, **kwargs): pass def render(self, name, value, attrs=None, **kwargs): pass
4
1
12
1
11
0
2
0.03
1
2
1
0
2
2
2
2
40
6
33
9
29
1
20
9
16
2
1
1
4
6,368
ArabellaTech/django-basic-cms
ArabellaTech_django-basic-cms/basic_cms/migrations/0002_auto_20151221_0338.py
basic_cms.migrations.0002_auto_20151221_0338.Migration
class Migration(migrations.Migration): dependencies = [ ('basic_cms', '0001_initial'), ] operations = [ migrations.AlterModelOptions( name='page', options={'ordering': ['tree_id', 'lft'], 'get_latest_by': 'publication_date', 'verbose_name': 'page', 'verbose_name_plural': 'pages', 'permissions': [('can_freeze', 'Can freeze page'), ('can_publish', 'Can publish page'), ('can_manage_en_gb', 'Manage Base'), ('can_manage_en', 'Manage English')]}, ), ]
class Migration(migrations.Migration): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
12
2
10
3
9
0
3
3
2
0
1
0
0
6,369
ArabellaTech/django-basic-cms
ArabellaTech_django-basic-cms/basic_cms/models.py
basic_cms.models.Content
class Content(models.Model): """A block of content, tied to a :class:`Page <pages.models.Page>`, for a particular language""" # languages could have five characters : Brazilian Portuguese is pt-br language = models.CharField(_('language'), max_length=5, blank=False) body = models.TextField(_('body')) type = models.CharField(_('type'), max_length=100, blank=False, db_index=True) page = models.ForeignKey(Page, verbose_name=_('page')) creation_date = models.DateTimeField(_('creation date'), editable=False, default=now_utc) objects = ContentManager() class Meta: get_latest_by = 'creation_date' verbose_name = _('content') verbose_name_plural = _('contents') def __unicode__(self): return u"%s :: %s" % (self.page.slug(), self.body[0:15])
class Content(models.Model): '''A block of content, tied to a :class:`Page <pages.models.Page>`, for a particular language''' class Meta: def __unicode__(self): pass
3
1
2
0
2
0
1
0.2
1
0
0
0
1
0
1
1
22
4
15
12
12
3
13
12
10
1
1
0
1
6,370
ArabellaTech/django-basic-cms
ArabellaTech_django-basic-cms/basic_cms/models.py
basic_cms.models.Page
class Page(MPTTModel): """ This model contain the status, dates, author, template. The real content of the page can be found in the :class:`Content <pages.models.Content>` model. .. attribute:: creation_date When the page has been created. .. attribute:: publication_date When the page should be visible. .. attribute:: publication_end_date When the publication of this page end. .. attribute:: last_modification_date Last time this page has been modified. .. attribute:: status The current status of the page. Could be DRAFT, PUBLISHED, EXPIRED or HIDDEN. You should the property :attr:`calculated_status` if you want that the dates are taken in account. .. attribute:: template A string containing the name of the template file for this page. """ # some class constants to refer to, e.g. Page.DRAFT DRAFT = 0 PUBLISHED = 1 EXPIRED = 2 HIDDEN = 3 STATUSES = ( (PUBLISHED, _('Published')), (HIDDEN, _('Hidden')), (DRAFT, _('Draft')), ) PAGE_LANGUAGES_KEY = "page_%d_languages" PAGE_URL_KEY = "page_%d_url" PAGE_BROKEN_LINK_KEY = "page_broken_link_%s" author = models.ForeignKey(settings.PAGE_USER_MODEL, verbose_name=_('author'), related_name='pages') parent = models.ForeignKey('self', null=True, blank=True, related_name='children', verbose_name=_('parent')) creation_date = models.DateTimeField(_('creation date'), editable=False, default=now_utc) publication_date = models.DateTimeField(_('publication date'), null=True, blank=True, help_text=_('''When the page should go live. Status must be "Published" for page to go live.''')) publication_end_date = models.DateTimeField(_('publication end date'), null=True, blank=True, help_text=_('''When to expire the page. Leave empty to never expire.''')) last_modification_date = models.DateTimeField(_('last modification date')) status = models.IntegerField(_('status'), choices=STATUSES, default=DRAFT) template = models.CharField(_('template'), max_length=100, null=True, blank=True) delegate_to = models.CharField(_('delegate to'), max_length=100, null=True, blank=True) freeze_date = models.DateTimeField(_('freeze date'), null=True, blank=True, help_text=_('''Don't publish any content after this date.''')) if settings.PAGE_USE_SITE_ID: sites = models.ManyToManyField(Site, default=[settings.SITE_ID], help_text=_('The site(s) the page is accessible at.'), verbose_name=_('sites'), related_name='pages') redirect_to_url = models.CharField(max_length=200, null=True, blank=True) redirect_to = models.ForeignKey('self', null=True, blank=True, related_name='redirected_pages') tags = TaggableManager(blank=True) # Managers objects = PageManager() class Meta: """Make sure the default page ordering is correct.""" ordering = ['tree_id', 'lft'] get_latest_by = "publication_date" verbose_name = _('page') verbose_name_plural = _('pages') permissions = settings.PAGE_EXTRA_PERMISSIONS def __init__(self, *args, **kwargs): """Instanciate the page object.""" # per instance cache self._languages = None self._complete_slug = None self._content_dict = None self._is_first_root = None super(Page, self).__init__(*args, **kwargs) def save(self, *args, **kwargs): """Override the default ``save`` method.""" if not self.status: self.status = self.DRAFT # Published pages should always have a publication date if self.publication_date is None and self.status == self.PUBLISHED: self.publication_date = now_utc() # Drafts should not, unless they have been set to the future if self.status == self.DRAFT: if settings.PAGE_SHOW_START_DATE: if (self.publication_date and self.publication_date <= now_utc()): self.publication_date = None else: self.publication_date = None self.last_modification_date = now_utc() # let's assume there is no more broken links after a save cache.delete(self.PAGE_BROKEN_LINK_KEY % self.id) super(Page, self).save(*args, **kwargs) # fix sites many-to-many link when the're hidden from the form if settings.PAGE_HIDE_SITES and self.sites.count() == 0: self.sites.add(Site.objects.get(pk=settings.SITE_ID)) def _get_calculated_status(self): """Get the calculated status of the page based on :attr:`Page.publication_date`, :attr:`Page.publication_end_date`, and :attr:`Page.status`.""" if settings.PAGE_SHOW_START_DATE and self.publication_date: if self.publication_date > now_utc(): return self.DRAFT if settings.PAGE_SHOW_END_DATE and self.publication_end_date: if self.publication_end_date < now_utc(): return self.EXPIRED return self.status calculated_status = property(_get_calculated_status) def _visible(self): """Return True if the page is visible on the frontend.""" return self.calculated_status in (self.PUBLISHED, self.HIDDEN) visible = property(_visible) def get_children_for_frontend(self): """Return a :class:`QuerySet` of published children page""" return Page.objects.filter_published(self.get_children()) def get_date_ordered_children_for_frontend(self): """Return a :class:`QuerySet` of published children page ordered by publication date.""" return self.get_children_for_frontend().order_by('-publication_date') def invalidate(self): """Invalidate cached data for this page.""" cache.delete(self.PAGE_LANGUAGES_KEY % (self.id)) cache.delete('PAGE_FIRST_ROOT_ID') self._languages = None self._complete_slug = None self._content_dict = dict() p_names = [p.name for p in get_placeholders(self.get_template())] if 'slug' not in p_names: p_names.append('slug') if 'title' not in p_names: p_names.append('title') # delete content cache, frozen or not for name in p_names: # frozen cache.delete(PAGE_CONTENT_DICT_KEY % (self.id, name, 1)) # not frozen cache.delete(PAGE_CONTENT_DICT_KEY % (self.id, name, 0)) cache.delete(self.PAGE_URL_KEY % (self.id)) def get_languages(self): """ Return a list of all used languages for this page. """ if self._languages: return self._languages self._languages = cache.get(self.PAGE_LANGUAGES_KEY % (self.id)) if self._languages is not None: return self._languages languages = [c['language'] for c in Content.objects.filter(page=self, type="slug").values('language')] # remove duplicates languages = list(set(languages)) languages.sort() cache.set(self.PAGE_LANGUAGES_KEY % (self.id), languages) self._languages = languages return languages def is_first_root(self): """Return ``True`` if this page is the first root pages.""" if self.parent: return False if self._is_first_root is not None: return self._is_first_root first_root_id = cache.get('PAGE_FIRST_ROOT_ID') if first_root_id is not None: self._is_first_root = first_root_id == self.id return self._is_first_root try: first_root_id = Page.objects.root().values('id')[0]['id'] except IndexError: first_root_id = None if first_root_id is not None: cache.set('PAGE_FIRST_ROOT_ID', first_root_id) self._is_first_root = self.id == first_root_id return self._is_first_root def get_url_path(self, language=None): """Return the URL's path component. Add the language prefix if ``PAGE_USE_LANGUAGE_PREFIX`` setting is set to ``True``. :param language: the wanted url language. """ if self.is_first_root(): # this is used to allow users to change URL of the root # page. The language prefix is not usable here. try: return reverse('pages-root') except Exception: pass url = self.get_complete_slug(language) if not language: language = settings.PAGE_DEFAULT_LANGUAGE if settings.PAGE_USE_LANGUAGE_PREFIX: return reverse('pages-details-by-path', args=[language, url]) else: return reverse('pages-details-by-path', args=[url]) def get_absolute_url(self, language=None): """Alias for `get_url_path`. This method is only there for backward compatibility and will be removed in a near futur. :param language: the wanted url language. """ return self.get_url_path(language=language) def get_complete_slug(self, language=None, hideroot=True): """Return the complete slug of this page by concatenating all parent's slugs. :param language: the wanted slug language.""" if not language: language = settings.PAGE_DEFAULT_LANGUAGE if self._complete_slug and language in self._complete_slug: return self._complete_slug[language] self._complete_slug = cache.get(self.PAGE_URL_KEY % (self.id)) if self._complete_slug is None: self._complete_slug = {} elif language in self._complete_slug: return self._complete_slug[language] if hideroot and settings.PAGE_HIDE_ROOT_SLUG and self.is_first_root(): url = u'' else: url = u'%s' % self.slug(language) for ancestor in self.get_ancestors(ascending=True): url = ancestor.slug(language) + u'/' + url self._complete_slug[language] = url cache.set(self.PAGE_URL_KEY % (self.id), self._complete_slug) return url def get_url(self, language=None): """Alias for `get_complete_slug`. This method is only there for backward compatibility and will be removed in a near futur. :param language: the wanted url language. """ return self.get_complete_slug(language=language) def slug(self, language=None, fallback=True): """ Return the slug of the page depending on the given language. :param language: wanted language, if not defined default is used. :param fallback: if ``True``, the slug will also be searched in other \ languages. """ slug = self.get_content(language, 'slug', language_fallback=fallback) return slug def title(self, language=None, fallback=True): """ Return the title of the page depending on the given language. :param language: wanted language, if not defined default is used. :param fallback: if ``True``, the slug will also be searched in \ other languages. """ if not language: language = settings.PAGE_DEFAULT_LANGUAGE return self.get_content(language, 'title', language_fallback=fallback) def get_content(self, language, ctype, language_fallback=False): """Shortcut method for retrieving a piece of page content :param language: wanted language, if not defined default is used. :param ctype: the type of content. :param fallback: if ``True``, the content will also be searched in \ other languages. """ return Content.objects.get_content(self, language, ctype, language_fallback) def expose_content(self): """Return all the current content of this page into a `string`. This is used by the haystack framework to build the search index.""" placeholders = get_placeholders(self.get_template()) exposed_content = [] for lang in self.get_languages(): for ctype in [p.name for p in placeholders]: content = self.get_content(lang, ctype, False) if content: exposed_content.append(content) return u"\r\n".join(exposed_content) def content_by_language(self, language): """ Return a list of latest published :class:`Content <pages.models.Content>` for a particluar language. :param language: wanted language, """ placeholders = get_placeholders(self.get_template()) content_list = [] for ctype in [p.name for p in placeholders]: try: content = Content.objects.get_content_object(self, language, ctype) content_list.append(content) except Content.DoesNotExist: pass return content_list def get_template(self): """ Get the :attr:`template <Page.template>` of this page if defined or the closer parent's one if defined or :attr:`pages.settings.PAGE_DEFAULT_TEMPLATE` otherwise. """ if self.template: return self.template template = None for p in self.get_ancestors(ascending=True): if p.template: template = p.template break if not template: template = settings.PAGE_DEFAULT_TEMPLATE return template def get_template_name(self): """ Get the template name of this page if defined or if a closer parent has a defined template or :data:`pages.settings.PAGE_DEFAULT_TEMPLATE` otherwise. """ template = self.get_template() page_templates = settings.get_page_templates() for t in page_templates: if t[0] == template: return t[1] return template def has_broken_link(self): """ Return ``True`` if the page have broken links to other pages into the content. """ return cache.get(self.PAGE_BROKEN_LINK_KEY % self.id) def valid_targets(self): """Return a :class:`QuerySet` of valid targets for moving a page into the tree. :param perms: the level of permission of the concerned user. """ exclude_list = [self.id] for p in self.get_descendants(): exclude_list.append(p.id) return Page.objects.exclude(id__in=exclude_list) def slug_with_level(self, language=None): """Display the slug of the page prepended with insecable spaces equal to simluate the level of page in the hierarchy.""" level = '' if self.level: for n in range(0, self.level): level += '&nbsp;&nbsp;&nbsp;' return mark_safe(level + self.slug(language)) def margin_level(self): """Used in the admin menu to create the left margin.""" return self.level * 2 def dump_json_data(self, get_children=False): """ Return a python dict representation of this page for use as part of a JSON export. """ def content_langs_ordered(): """ Return a list of languages ordered by the page content with the latest creation date in each. This will be used to maintain the state of the language_up_to_date template tag when a page is restored or imported into another site. """ params = {'page': self} if self.freeze_date: params['creation_date__lte'] = self.freeze_date cqs = Content.objects.filter(**params) cqs = cqs.values('language').annotate(latest=Max('creation_date')) return [c['language'] for c in cqs.order_by('latest')] languages = content_langs_ordered() def language_content(ctype): return dict( (lang, self.get_content(lang, ctype, language_fallback=False)) for lang in languages) def placeholder_content(): """Return content of each placeholder in each language.""" out = {} for p in get_placeholders(self.get_template()): if p.name in ('title', 'slug'): continue # these were already included out[p.name] = language_content(p.name) for p in Content.objects.filter(type__in=['meta_title', 'meta_description', 'meta_keywords', 'meta_author', 'fb_page_type', 'fb_image']): out[p.type] = language_content(p.type) return out def isoformat(d): return None if d is None else d.strftime(ISODATE_FORMAT) def custom_email(user): """Allow a user's profile to return an email for the user.""" try: profile = user.get_profile() except (ObjectDoesNotExist, AttributeError): return user.email get_email = getattr(profile, 'get_email', None) return get_email() if get_email else user.email tags = [tag.name for tag in self.tags.all()] children = [] if get_children: for c in self.children.filter(status__in=[self.PUBLISHED, self.HIDDEN]): children.append(c.dump_json_data()) return { 'complete_slug': dict( (lang, self.get_complete_slug(lang, hideroot=False)) for lang in languages), 'title': language_content('title'), 'author_email': custom_email(self.author), 'creation_date': isoformat(self.creation_date), 'publication_date': isoformat(self.publication_date), 'publication_end_date': isoformat(self.publication_end_date), 'last_modification_date': isoformat(self.last_modification_date), 'status': { Page.PUBLISHED: 'published', Page.HIDDEN: 'hidden', Page.DRAFT: 'draft'}[self.status], 'template': self.template, 'sites': ( [site.domain for site in self.sites.all()] if settings.PAGE_USE_SITE_ID else []), 'redirect_to_url': self.redirect_to_url, 'redirect_to_complete_slug': dict( (lang, self.redirect_to.get_complete_slug( lang, hideroot=False)) for lang in self.redirect_to.get_languages() ) if self.redirect_to is not None else None, 'content': placeholder_content(), 'content_language_updated_order': languages, 'tags': tags, 'children': children } def update_redirect_to_from_json(self, redirect_to_complete_slugs): """ The second pass of PageManager.create_and_update_from_json_data used to update the redirect_to field. Returns a messages list to be appended to the messages from the first pass. """ messages = [] s = '' for lang, s in redirect_to_complete_slugs.items(): r = Page.objects.from_path(s, lang, exclude_drafts=False) if r: self.redirect_to = r self.save() break else: messages.append(_("Could not find page for redirect-to field" " '%s'") % (s,)) return messages def __str__(self): """Representation of the page, saved or not.""" return self.__unicode__() def __unicode__(self): """Representation of the page, saved or not.""" if self.id: # without ID a slug cannot be retrieved slug = self.slug() if slug: return slug return u"Page %d" % self.id return u"Page without id"
class Page(MPTTModel): ''' This model contain the status, dates, author, template. The real content of the page can be found in the :class:`Content <pages.models.Content>` model. .. attribute:: creation_date When the page has been created. .. attribute:: publication_date When the page should be visible. .. attribute:: publication_end_date When the publication of this page end. .. attribute:: last_modification_date Last time this page has been modified. .. attribute:: status The current status of the page. Could be DRAFT, PUBLISHED, EXPIRED or HIDDEN. You should the property :attr:`calculated_status` if you want that the dates are taken in account. .. attribute:: template A string containing the name of the template file for this page. ''' class Meta: '''Make sure the default page ordering is correct.''' def __init__(self, *args, **kwargs): '''Instanciate the page object.''' pass def save(self, *args, **kwargs): '''Override the default ``save`` method.''' pass def _get_calculated_status(self): '''Get the calculated status of the page based on :attr:`Page.publication_date`, :attr:`Page.publication_end_date`, and :attr:`Page.status`.''' pass def _visible(self): '''Return True if the page is visible on the frontend.''' pass def get_children_for_frontend(self): '''Return a :class:`QuerySet` of published children page''' pass def get_date_ordered_children_for_frontend(self): '''Return a :class:`QuerySet` of published children page ordered by publication date.''' pass def invalidate(self): '''Invalidate cached data for this page.''' pass def get_languages(self): ''' Return a list of all used languages for this page. ''' pass def is_first_root(self): '''Return ``True`` if this page is the first root pages.''' pass def get_url_path(self, language=None): '''Return the URL's path component. Add the language prefix if ``PAGE_USE_LANGUAGE_PREFIX`` setting is set to ``True``. :param language: the wanted url language. ''' pass def get_absolute_url(self, language=None): '''Alias for `get_url_path`. This method is only there for backward compatibility and will be removed in a near futur. :param language: the wanted url language. ''' pass def get_complete_slug(self, language=None, hideroot=True): '''Return the complete slug of this page by concatenating all parent's slugs. :param language: the wanted slug language.''' pass def get_url_path(self, language=None): '''Alias for `get_complete_slug`. This method is only there for backward compatibility and will be removed in a near futur. :param language: the wanted url language. ''' pass def slug(self, language=None, fallback=True): ''' Return the slug of the page depending on the given language. :param language: wanted language, if not defined default is used. :param fallback: if ``True``, the slug will also be searched in other languages. ''' pass def title(self, language=None, fallback=True): ''' Return the title of the page depending on the given language. :param language: wanted language, if not defined default is used. :param fallback: if ``True``, the slug will also be searched in other languages. ''' pass def get_content(self, language, ctype, language_fallback=False): '''Shortcut method for retrieving a piece of page content :param language: wanted language, if not defined default is used. :param ctype: the type of content. :param fallback: if ``True``, the content will also be searched in other languages. ''' pass def expose_content(self): '''Return all the current content of this page into a `string`. This is used by the haystack framework to build the search index.''' pass def content_by_language(self, language): ''' Return a list of latest published :class:`Content <pages.models.Content>` for a particluar language. :param language: wanted language, ''' pass def get_template(self): ''' Get the :attr:`template <Page.template>` of this page if defined or the closer parent's one if defined or :attr:`pages.settings.PAGE_DEFAULT_TEMPLATE` otherwise. ''' pass def get_template_name(self): ''' Get the template name of this page if defined or if a closer parent has a defined template or :data:`pages.settings.PAGE_DEFAULT_TEMPLATE` otherwise. ''' pass def has_broken_link(self): ''' Return ``True`` if the page have broken links to other pages into the content. ''' pass def valid_targets(self): '''Return a :class:`QuerySet` of valid targets for moving a page into the tree. :param perms: the level of permission of the concerned user. ''' pass def slug_with_level(self, language=None): '''Display the slug of the page prepended with insecable spaces equal to simluate the level of page in the hierarchy.''' pass def margin_level(self): '''Used in the admin menu to create the left margin.''' pass def dump_json_data(self, get_children=False): ''' Return a python dict representation of this page for use as part of a JSON export. ''' pass def content_langs_ordered(): ''' Return a list of languages ordered by the page content with the latest creation date in each. This will be used to maintain the state of the language_up_to_date template tag when a page is restored or imported into another site. ''' pass def language_content(ctype): pass def placeholder_content(): '''Return content of each placeholder in each language.''' pass def isoformat(d): pass def custom_email(user): '''Allow a user's profile to return an email for the user.''' pass def update_redirect_to_from_json(self, redirect_to_complete_slugs): ''' The second pass of PageManager.create_and_update_from_json_data used to update the redirect_to field. Returns a messages list to be appended to the messages from the first pass. ''' pass def __str__(self): '''Representation of the page, saved or not.''' pass def __unicode__(self): '''Representation of the page, saved or not.''' pass
35
33
14
1
9
4
3
0.42
1
9
1
0
28
4
28
28
538
85
320
110
285
134
262
110
227
7
1
3
93
6,371
ArabellaTech/django-basic-cms
ArabellaTech_django-basic-cms/basic_cms/models.py
basic_cms.models.PageAlias
class PageAlias(models.Model): """URL alias for a :class:`Page <pages.models.Page>`""" page = models.ForeignKey(Page, null=True, blank=True, verbose_name=_('page'), **page_alias_keywords) url = models.CharField(max_length=255, unique=True) objects = PageAliasManager() class Meta: verbose_name_plural = _('Aliases') def save(self, *args, **kwargs): # normalize url self.url = normalize_url(self.url) super(PageAlias, self).save(*args, **kwargs) def __unicode__(self): return u"%s :: %s" % (self.url, self.page.get_complete_slug())
class PageAlias(models.Model): '''URL alias for a :class:`Page <pages.models.Page>`''' class Meta: def save(self, *args, **kwargs): pass def __unicode__(self): pass
4
1
3
0
3
1
1
0.17
1
1
0
0
2
0
2
2
17
3
12
8
8
2
11
8
7
1
1
0
2
6,372
ArabellaTech/django-basic-cms
ArabellaTech_django-basic-cms/basic_cms/permissions.py
basic_cms.permissions.PagePermission
class PagePermission(authority.permissions.BasePermission): """Handle the :class:`Page <pages.models.Page>` permissions.""" label = 'page_permission' checks = permission_checks def check(self, action, page=None, lang=None, method=None): """Return ``True`` if the current user has permission on the page.""" if self.user.is_superuser: return True if action == 'change': return self.has_change_permission(page, lang, method) if action == 'delete': if not self.delete_page(): return False return True if action == 'add': if not self.add_page(): return False return True if action == 'freeze': perm = self.user.has_perm('pages.can_freeze') if perm: return True return False if action == 'publish': perm = self.user.has_perm('pages.can_publish') if perm: return True return False return False def has_change_permission(self, page, lang, method=None): """Return ``True`` if the current user has permission to change the page.""" # the user has always the right to look at a page content # if he doesn't try to modify it. if method != 'POST': return True # right to change all the pages if self.change_page(): return True if lang: # try the global language permission first perm = self.user.has_perm( 'pages.can_manage_%s' % lang.replace('-', '_') ) if perm: return True # then per object permission perm_func = getattr(self, 'manage (%s)_page' % lang) if perm_func(page): return True # last hierarchic permissions because it's more expensive perm_func = getattr(self, 'manage hierarchy_page') if perm_func(page): return True else: for ancestor in page.get_ancestors(): if perm_func(ancestor): return True # everything else failed, no permissions return False
class PagePermission(authority.permissions.BasePermission): '''Handle the :class:`Page <pages.models.Page>` permissions.''' def check(self, action, page=None, lang=None, method=None): '''Return ``True`` if the current user has permission on the page.''' pass def has_change_permission(self, page, lang, method=None): '''Return ``True`` if the current user has permission to change the page.''' pass
3
3
31
3
23
5
10
0.22
1
0
0
0
2
0
2
2
68
8
49
9
46
11
46
9
43
11
1
3
20
6,373
ArabellaTech/django-basic-cms
ArabellaTech_django-basic-cms/basic_cms/placeholders.py
basic_cms.placeholders.ContactForm
class ContactForm(forms.Form): email = forms.EmailField(label=_('Your email')) subject = forms.CharField(label=_('Subject'), max_length=150) message = forms.CharField(widget=forms.Textarea(), label=_('Your message'))
class ContactForm(forms.Form): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
7
1
6
4
5
0
4
4
3
0
1
0
0
6,374
ArabellaTech/django-basic-cms
ArabellaTech_django-basic-cms/basic_cms/placeholders.py
basic_cms.placeholders.ContactPlaceholderNode
class ContactPlaceholderNode(PlaceholderNode): """A contact `PlaceholderNode` example.""" def render(self, context): content = self.get_content_from_context(context) request = context.get('request', None) if not request: raise ValueError('request no available in the context.') if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): data = form.cleaned_data recipients = [adm[1] for adm in global_settings.ADMINS] try: send_mail(data['subject'], data['message'], data['email'], recipients, fail_silently=False) return _("Your email has been sent. Thank you.") except: return _("An error as occured: your email has not been sent.") else: form = ContactForm() renderer = render_to_string('pages/contact.html', {'form':form}) return mark_safe(renderer)
class ContactPlaceholderNode(PlaceholderNode): '''A contact `PlaceholderNode` example.''' def render(self, context): pass
2
1
20
0
20
0
5
0.05
1
2
1
0
1
0
1
10
23
1
21
8
19
1
19
8
17
5
2
3
5
6,375
ArabellaTech/django-basic-cms
ArabellaTech_django-basic-cms/basic_cms/placeholders.py
basic_cms.placeholders.FilePlaceholderNode
class FilePlaceholderNode(PlaceholderNode): """A `PlaceholderNode` that saves one file on disk. `PAGE_UPLOAD_ROOT` setting define where to save the file. """ def get_field(self, page, language, initial=None): help_text = "" widget = FileInput(page, language) return FileField( widget=widget, initial=initial, help_text=help_text, required=False ) def save(self, page, language, data, change, extra_data=None): if 'delete' in extra_data: return super(FilePlaceholderNode, self).save( page, language, "", change ) filename = '' if change and data: # the image URL is posted if not changed if type(data) is unicode: return filename = get_filename(page, self, data) filename = default_storage.save(filename, data) return super(FilePlaceholderNode, self).save( page, language, filename, change )
class FilePlaceholderNode(PlaceholderNode): '''A `PlaceholderNode` that saves one file on disk. `PAGE_UPLOAD_ROOT` setting define where to save the file. ''' def get_field(self, page, language, initial=None): pass def save(self, page, language, data, change, extra_data=None): pass
3
1
16
1
15
1
3
0.13
1
2
0
0
2
0
2
11
38
4
30
6
27
4
15
6
12
4
2
2
5
6,376
ArabellaTech/django-basic-cms
ArabellaTech_django-basic-cms/basic_cms/placeholders.py
basic_cms.placeholders.ImagePlaceholderNode
class ImagePlaceholderNode(PlaceholderNode): """A `PlaceholderNode` that saves one image on disk. `PAGE_UPLOAD_ROOT` setting define where to save the image. """ def get_field(self, page, language, initial=None): help_text = "" widget = ImageInput(page, language) return ImageField( widget=widget, initial=initial, help_text=help_text, required=False ) def save(self, page, language, data, change, extra_data=None): if 'delete' in extra_data: return super(ImagePlaceholderNode, self).save( page, language, "", change ) filename = '' if change and data: # the image URL is posted if not changed if type(data) is unicode: return filename = get_filename(page, self, data) filename = default_storage.save(filename, data) return super(ImagePlaceholderNode, self).save( page, language, filename, change )
class ImagePlaceholderNode(PlaceholderNode): '''A `PlaceholderNode` that saves one image on disk. `PAGE_UPLOAD_ROOT` setting define where to save the image. ''' def get_field(self, page, language, initial=None): pass def save(self, page, language, data, change, extra_data=None): pass
3
1
16
1
15
1
3
0.13
1
3
1
0
2
0
2
11
38
4
30
6
27
4
15
6
12
4
2
2
5
6,377
ArabellaTech/django-basic-cms
ArabellaTech_django-basic-cms/basic_cms/placeholders.py
basic_cms.placeholders.PlaceholderNode
class PlaceholderNode(template.Node): """This template node is used to output and save page content and dynamically generate input fields in the admin. :param name: the name of the placeholder you want to show/create :param page: the optional page object :param widget: the widget you want to use in the admin interface. Take a look into :mod:`basic_cms.widgets` to see which widgets are available. :param parsed: if the ``parsed`` word is given, the content of the placeholder is evaluated as template code, within the current context. :param as_varname: if ``as_varname`` is defined, no value will be returned. A variable will be created in the context with the defined name. :param inherited: inherit content from parent's pages. :param untranslated: the placeholder's content is the same for every language. """ field = CharField widget = TextInput def __init__(self, name, page=None, widget=None, parsed=False, as_varname=None, inherited=False, untranslated=False): """Gather parameters for the `PlaceholderNode`. These values should be thread safe and don't change between calls.""" self.page = page or 'current_page' self.name = name if widget: self.widget = widget self.parsed = parsed self.inherited = inherited self.untranslated = untranslated self.as_varname = as_varname self.found_in_block = None def get_widget(self, page, language, fallback=Textarea): """Given the name of a placeholder return a `Widget` subclass like Textarea or TextInput.""" import sys PY3 = sys.version > '3' is_string = type(self.widget) == type(str()) if not PY3: is_string = type(self.widget) == type(str()) or type(self.widget) == type(unicode()) if is_string: widget = get_widget(self.widget) else: widget = self.widget try: return widget(page=page, language=language) except: pass return widget() def get_extra_data(self, data): """Get eventual extra data for this placeholder from the admin form. This method is called when the Page is saved in the admin and passed to the placeholder save method.""" result = {} for key in data.keys(): if key.startswith(self.name + '-'): new_key = key.replace(self.name + '-', '') result[new_key] = data[key] return result def get_field(self, page, language, initial=None): """The field that will be shown within the admin.""" if self.parsed: help_text = _('Note: This field is evaluated as template code.') else: help_text = '' widget = self.get_widget(page, language) return self.field(widget=widget, initial=initial, help_text=help_text, required=False) def save(self, page, language, data, change, extra_data=None): """Actually save the placeholder data into the Content object.""" # if this placeholder is untranslated, we save everything # in the default language if self.untranslated: language = settings.PAGE_DEFAULT_LANGUAGE # the page is being changed if change: # we need create a new content if revision is enabled if(settings.PAGE_CONTENT_REVISION and self.name not in settings.PAGE_CONTENT_REVISION_EXCLUDE_LIST): Content.objects.create_content_if_changed( page, language, self.name, data ) else: Content.objects.set_or_create_content( page, language, self.name, data ) # the page is being added else: Content.objects.set_or_create_content( page, language, self.name, data ) def get_content(self, page_obj, lang, lang_fallback=True): if self.untranslated: lang = settings.PAGE_DEFAULT_LANGUAGE lang_fallback = False content = Content.objects.get_content(page_obj, lang, self.name, lang_fallback) if self.inherited and not content: for ancestor in page_obj.get_ancestors(): content = Content.objects.get_content(ancestor, lang, self.name, lang_fallback) if content: break return content def get_content_from_context(self, context): if not self.page in context: return '' # current_page can be set to None if not context[self.page]: return '' if self.untranslated: lang_fallback = False lang = settings.PAGE_DEFAULT_LANGUAGE else: lang_fallback = True lang = context.get('lang', settings.PAGE_DEFAULT_LANGUAGE) return self.get_content(context[self.page], lang, lang_fallback) def render(self, context): """Output the content of the `PlaceholdeNode` in the template.""" content = mark_safe(self.get_content_from_context(context)) if not content: return '' if self.parsed: try: t = template.Template(content, name=self.name) content = mark_safe(t.render(context)) except TemplateSyntaxError as error: if global_settings.DEBUG: content = PLACEHOLDER_ERROR % { 'name': self.name, 'error': error, } else: content = '' if self.as_varname is None: return content context[self.as_varname] = content return '' def __repr__(self): return "<Placeholder Node: %s>" % self.name
class PlaceholderNode(template.Node): '''This template node is used to output and save page content and dynamically generate input fields in the admin. :param name: the name of the placeholder you want to show/create :param page: the optional page object :param widget: the widget you want to use in the admin interface. Take a look into :mod:`basic_cms.widgets` to see which widgets are available. :param parsed: if the ``parsed`` word is given, the content of the placeholder is evaluated as template code, within the current context. :param as_varname: if ``as_varname`` is defined, no value will be returned. A variable will be created in the context with the defined name. :param inherited: inherit content from parent's pages. :param untranslated: the placeholder's content is the same for every language. ''' def __init__(self, name, page=None, widget=None, parsed=False, as_varname=None, inherited=False, untranslated=False): '''Gather parameters for the `PlaceholderNode`. These values should be thread safe and don't change between calls.''' pass def get_widget(self, page, language, fallback=Textarea): '''Given the name of a placeholder return a `Widget` subclass like Textarea or TextInput.''' pass def get_extra_data(self, data): '''Get eventual extra data for this placeholder from the admin form. This method is called when the Page is saved in the admin and passed to the placeholder save method.''' pass def get_field(self, page, language, initial=None): '''The field that will be shown within the admin.''' pass def save(self, page, language, data, change, extra_data=None): '''Actually save the placeholder data into the Content object.''' pass def get_content(self, page_obj, lang, lang_fallback=True): pass def get_content_from_context(self, context): pass def render(self, context): '''Output the content of the `PlaceholdeNode` in the template.''' pass def __repr__(self): pass
10
7
15
0
13
2
3
0.29
1
3
1
4
9
7
9
9
166
15
117
36
105
34
88
34
77
6
1
3
31
6,378
ArabellaTech/django-basic-cms
ArabellaTech_django-basic-cms/basic_cms/placeholders.py
basic_cms.placeholders.VideoPlaceholderNode
class VideoPlaceholderNode(PlaceholderNode): """A youtube `PlaceholderNode`, just here as an example.""" widget = VideoWidget def render(self, context): content = self.get_content_from_context(context) if not content: return '' if content: video_url, w, h = content.split('\\') m = re.search('youtube\.com\/watch\?v=([^&]+)', content) if m: video_url = 'http://www.youtube.com/v/' + m.group(1) if not w: w = 425 if not h: h = 344 context = {'video_url': video_url, 'w': w, 'h': h} renderer = render_to_string('pages/embed.html', context) return mark_safe(renderer) return ''
class VideoPlaceholderNode(PlaceholderNode): '''A youtube `PlaceholderNode`, just here as an example.''' def render(self, context): pass
2
1
17
0
17
0
6
0.05
1
0
0
0
1
0
1
10
22
2
19
7
17
1
19
7
17
6
2
2
6
6,379
ArabellaTech/django-basic-cms
ArabellaTech_django-basic-cms/basic_cms/search_indexes.py
basic_cms.search_indexes.PageIndex
class PageIndex(SearchIndex, Indexable): """Search index for pages content.""" text = CharField(document=True, use_template=True) title = CharField(model_attr='title') url = CharField(model_attr='get_absolute_url') publication_date = DateTimeField(model_attr='publication_date') def index_queryset(self, using=None): return self.get_model().objects.published() def should_update(self, instance, **kwargs): return instance.status == Page.PUBLISHED def get_model(self): return Page
class PageIndex(SearchIndex, Indexable): '''Search index for pages content.''' def index_queryset(self, using=None): pass def should_update(self, instance, **kwargs): pass def get_model(self): pass
4
1
2
0
2
0
1
0.09
2
1
1
0
3
0
3
3
15
3
11
8
7
1
11
8
7
1
1
0
3
6,380
ArabellaTech/django-basic-cms
ArabellaTech_django-basic-cms/basic_cms/templatetags/pages_tags.py
basic_cms.templatetags.pages_tags.FakeCSRFNode
class FakeCSRFNode(template.Node): """Fake CSRF node for django 1.1.1""" def render(self, context): return ''
class FakeCSRFNode(template.Node): '''Fake CSRF node for django 1.1.1''' def render(self, context): pass
2
1
2
0
2
0
1
0.33
1
0
0
0
1
0
1
1
4
0
3
2
1
1
3
2
1
1
1
0
1
6,381
ArabellaTech/django-basic-cms
ArabellaTech_django-basic-cms/basic_cms/templatetags/pages_tags.py
basic_cms.templatetags.pages_tags.GetPagesWithTagNode
class GetPagesWithTagNode(template.Node): """Get Pages with given tag node""" def __init__(self, tag, varname): self.tag = tag self.varname = varname def render(self, context): tag = self.tag.resolve(context) pages = Page.objects.filter(tags__name__in=[tag]) context[self.varname] = pages return ''
class GetPagesWithTagNode(template.Node): '''Get Pages with given tag node''' def __init__(self, tag, varname): pass def render(self, context): pass
3
1
4
0
4
0
1
0.11
1
1
1
0
2
2
2
2
11
1
9
7
6
1
9
7
6
1
1
0
2
6,382
ArabellaTech/django-basic-cms
ArabellaTech_django-basic-cms/basic_cms/widgets.py
basic_cms.widgets.VideoWidget
class VideoWidget(MultiWidget): '''A youtube `Widget` for the admin.''' def __init__(self, attrs=None, page=None, language=None, video_url=None, weight=None, height=None): widgets = [ TextInput(attrs=attrs), TextInput(attrs=attrs), TextInput(attrs=attrs) ] super(VideoWidget, self).__init__(widgets, attrs) def decompress(self, value): # backslashes are forbidden in URLs if value: return value.split('\\') return (None, None, None) def value_from_datadict(self, data, files, name): value = [u'', u'', u''] for da in filter(lambda x: x.startswith(name), data): index = int(da[len(name) + 1:]) value[index] = data[da] if value[0] == value[1] == value[2] == u'': return None return u'%s\\%s\\%s' % tuple(value) def _has_changed(self, initial, data): """Need to be reimplemented to be correct.""" if data == initial: return False return bool(initial) != bool(data) def format_output(self, rendered_widgets): """ Given a list of rendered widgets (as strings), it inserts an HTML linebreak between them. Returns a Unicode string representing the HTML for the whole lot. """ return u"""<table> <tr><td>url</td><td>%s</td></tr> <tr><td>width</td><td>%s</td></tr> <tr><td>weight</td><td>%s</td></tr> </table>""" % tuple(rendered_widgets)
class VideoWidget(MultiWidget): '''A youtube `Widget` for the admin.''' def __init__(self, attrs=None, page=None, language=None, video_url=None, weight=None, height=None): pass def decompress(self, value): pass def value_from_datadict(self, data, files, name): pass def _has_changed(self, initial, data): '''Need to be reimplemented to be correct.''' pass def format_output(self, rendered_widgets): ''' Given a list of rendered widgets (as strings), it inserts an HTML linebreak between them. Returns a Unicode string representing the HTML for the whole lot. ''' pass
6
3
8
0
6
1
2
0.26
1
5
0
0
5
0
5
5
44
5
31
11
24
8
22
10
16
3
1
1
9
6,383
ArabellaTech/django-basic-cms
ArabellaTech_django-basic-cms/basic_cms/widgets.py
basic_cms.widgets.RichTextarea
class RichTextarea(Textarea): """A RichTextarea widget.""" class Media: js = [join(PAGES_MEDIA_URL, path) for path in ( 'javascript/jquery.js', )] css = { 'all': [join(PAGES_MEDIA_URL, path) for path in ( 'css/rte.css', )] } def __init__(self, language=None, attrs=None, **kwargs): attrs = {'class': 'rte'} self.language = language super(RichTextarea, self).__init__(attrs) def render(self, name, value, attrs=None, **kwargs): rendered = super(RichTextarea, self).render(name, value, attrs) context = { 'name': name, 'PAGES_MEDIA_URL': PAGES_MEDIA_URL, } return rendered + mark_safe(render_to_string( 'pages/widgets/richtextarea.html', context))
class RichTextarea(Textarea): '''A RichTextarea widget.''' class Media: def __init__(self, language=None, attrs=None, **kwargs): pass def render(self, name, value, attrs=None, **kwargs): pass
4
1
6
0
6
0
1
0.05
1
1
0
0
2
1
2
2
25
2
22
9
18
1
12
9
8
1
1
0
2
6,384
ArabellaTech/django-basic-cms
ArabellaTech_django-basic-cms/basic_cms/widgets.py
basic_cms.widgets.ImageInput
class ImageInput(FileInput): def __init__(self, page=None, language=None, attrs=None, **kwargs): self.language = language self.page = page super(ImageInput, self).__init__(attrs) def render(self, name, value, attrs=None, **kwargs): if not self.page: field_content = _('Please save the page to show the image field') else: field_content = '' if value: field_content += _('Current file: %s<br/>') % value field_content += super(ImageInput, self).render(name, attrs) if value: field_content += '''<br><label for="%s-delete">%s</label> <input name="%s-delete" id="%s-delete" type="checkbox" value="true"> ''' % (name, _('Delete image'), name, name) return mark_safe(field_content)
class ImageInput(FileInput): def __init__(self, page=None, language=None, attrs=None, **kwargs): pass def render(self, name, value, attrs=None, **kwargs): pass
3
0
9
0
9
0
3
0
1
1
0
0
2
2
2
2
21
2
19
6
16
0
15
6
12
4
1
2
5
6,385
ArabellaTech/django-basic-cms
ArabellaTech_django-basic-cms/basic_cms/widgets.py
basic_cms.widgets.FileInput
class FileInput(FileInput): def __init__(self, page=None, language=None, attrs=None, **kwargs): self.language = language self.page = page super(FileInput, self).__init__(attrs) def render(self, name, value, attrs=None, **kwargs): if not self.page: field_content = _('Please save the page to show the file field') else: field_content = '' if value: field_content += _('Current file: %s<br/>') % value field_content += super(FileInput, self).render(name, attrs) if value: field_content += '''<br><label for="%s-delete">%s</label> <input name="%s-delete" id="%s-delete" type="checkbox" value="true"> ''' % (name, _('Delete file'), name, name) return mark_safe(field_content)
class FileInput(FileInput): def __init__(self, page=None, language=None, attrs=None, **kwargs): pass def render(self, name, value, attrs=None, **kwargs): pass
3
0
9
0
9
0
3
0
0
1
0
0
2
2
2
2
21
2
19
6
16
0
15
6
12
4
0
2
5
6,386
ArabellaTech/django-basic-cms
ArabellaTech_django-basic-cms/basic_cms/widgets.py
basic_cms.widgets.EditArea
class EditArea(Textarea): """EditArea is a html syntax coloured widget.""" class Media: js = [join(PAGES_MEDIA_URL, path) for path in ( 'edit_area/edit_area_full.js', )] def __init__(self, language=None, attrs=None, **kwargs): self.language = language self.attrs = {'class': 'editarea'} if attrs: self.attrs.update(attrs) super(EditArea, self).__init__(attrs) def render(self, name, value, attrs=None, **kwargs): rendered = super(EditArea, self).render(name, value, attrs) context = { 'name': name, 'language': self.language, 'PAGES_MEDIA_URL': PAGES_MEDIA_URL, } return rendered + mark_safe(render_to_string( 'pages/widgets/editarea.html', context))
class EditArea(Textarea): '''EditArea is a html syntax coloured widget.''' class Media: def __init__(self, language=None, attrs=None, **kwargs): pass def render(self, name, value, attrs=None, **kwargs): pass
4
1
8
0
8
0
2
0.05
1
1
0
0
2
2
2
2
23
2
20
9
16
1
13
9
9
2
1
1
3
6,387
ArabellaTech/django-basic-cms
ArabellaTech_django-basic-cms/basic_cms/widgets.py
basic_cms.widgets.CKEditor
class CKEditor(Textarea): """CKEditor widget.""" class Media: js = [join(PAGES_MEDIA_URL, 'ckeditor/ckeditor.js'), join(settings.MEDIA_URL, 'filebrowser/js/FB_CKEditor.js'), ] def __init__(self, language=None, attrs=None, **kwargs): self.language = language self.filebrowser = "filebrowser" in getattr(settings, 'INSTALLED_APPS', []) self.attrs = {'class': 'ckeditor'} if attrs: self.attrs.update(attrs) super(CKEditor, self).__init__(attrs) def render(self, name, value, attrs=None, **kwargs): rendered = super(CKEditor, self).render(name, value, attrs) context = { 'name': name, 'filebrowser': self.filebrowser, } return rendered + mark_safe(render_to_string( 'pages/widgets/ckeditor.html', context))
class CKEditor(Textarea): '''CKEditor widget.''' class Media: def __init__(self, language=None, attrs=None, **kwargs): pass def render(self, name, value, attrs=None, **kwargs): pass
4
1
8
0
8
0
2
0.05
1
1
0
0
2
3
2
2
25
3
21
10
17
1
14
10
10
2
1
1
3
6,388
ArabellaTech/django-basic-cms
ArabellaTech_django-basic-cms/basic_cms/views.py
basic_cms.views.Details
class Details(object): """ This class based view get the root pages for navigation and the current page to display if there is any. All is rendered with the current page's template. """ def __call__(self, request, path=None, lang=None, delegation=True, **kwargs): current_page = False if path is None: raise ValueError( "basic_cms.views.Details class view requires the path argument. " "Check your urls.py file.") # for the ones that might have forgotten to pass the language # the language is now removed from the page path if settings.PAGE_USE_LANGUAGE_PREFIX and lang is None: maybe_lang = path.split("/")[0] if maybe_lang in LANGUAGE_KEYS: lang = maybe_lang path = path[(len(lang) + 1):] lang = self.choose_language(lang, request) pages_navigation = self.get_navigation(request, path, lang) context = { 'path': path, 'pages_navigation': pages_navigation, 'lang': lang, } is_staff = self.is_user_staff(request) current_page = self.resolve_page(request, context, is_staff) if current_page and not current_page.is_first_root(): url = current_page.get_absolute_url(language=lang) slug = current_page.get_complete_slug(language=lang) current_url = request.get_full_path() if url != path and url + '/' != current_url and slug != path: return HttpResponsePermanentRedirect(url) # if no pages has been found, we will try to find it via an Alias if not current_page: redirection = self.resolve_alias(request, path, lang) if redirection: return redirection else: context['current_page'] = current_page # If unauthorized to see the pages, raise a 404, That can # happen with expired pages. if not is_staff and not current_page.visible: raise Http404 redirection = self.resolve_redirection(request, context) if redirection: return redirection template_name = self.get_template(request, context) self.extra_context(request, context) if delegation and current_page.delegate_to: answer = self.delegate(request, context, delegation, **kwargs) if answer: return answer if kwargs.get('only_context', False): return context template_name = kwargs.get('template_name', template_name) response = render_to_response(template_name, RequestContext(request, context)) current_page = context['current_page'] # populate_xheaders(request, response, Page, current_page.id) return response def resolve_page(self, request, context, is_staff): """Return the appropriate page according to the path.""" path = context['path'] lang = context['lang'] page = Page.objects.from_path(path, lang, exclude_drafts=(not is_staff)) if page: return page # if the complete path didn't worked out properly # and if didn't used PAGE_USE_STRICT_URL setting we gonna # try to see if it might be a delegation page. # To do that we remove the right part of the url and try again # to find a page that match if not settings.PAGE_USE_STRICT_URL: path = remove_slug(path) while path is not None: page = Page.objects.from_path(path, lang, exclude_drafts=(not is_staff)) # find a match. Is the page delegating? if page: if page.delegate_to: return page path = remove_slug(path) return None def resolve_alias(self, request, path, lang): alias = PageAlias.objects.from_path(request, path, lang) if alias: url = alias.page.get_url_path(lang) return HttpResponsePermanentRedirect(url) raise Http404 def resolve_redirection(self, request, context): """Check for redirections.""" current_page = context['current_page'] lang = context['lang'] if current_page.redirect_to_url: return HttpResponsePermanentRedirect(current_page.redirect_to_url) if current_page.redirect_to: return HttpResponsePermanentRedirect( current_page.redirect_to.get_url_path(lang)) def get_navigation(self, request, path, lang): """Get the pages that are at the root level.""" return Page.objects.navigation().order_by("tree_id") def choose_language(self, lang, request): """Deal with the multiple corner case of choosing the language.""" # Can be an empty string or None if not lang: lang = get_language_from_request(request) # Raise a 404 if the language is not in not in the list if lang not in [key for (key, value) in settings.PAGE_LANGUAGES]: raise Http404 # We're going to serve CMS pages in language lang; # make django gettext use that language too if lang and translation.check_for_language(lang): translation.activate(lang) return lang def get_template(self, request, context): """Just there in case you have special business logic.""" return context['current_page'].get_template() def is_user_staff(self, request): """Return True if the user is staff.""" return request.user.is_authenticated() and request.user.is_staff def extra_context(self, request, context): """Call the PAGE_EXTRA_CONTEXT function if there is one.""" if settings.PAGE_EXTRA_CONTEXT: context.update(settings.PAGE_EXTRA_CONTEXT()) def delegate(self, request, context, delegation=True): # if there is a delegation to another view, # call this view instead. current_page = context['current_page'] path = context['path'] delegate_path = path.replace( current_page.get_complete_slug(hideroot=False), "") # it seems that the urlconf path have to start with a slash if len(delegate_path) == 0: delegate_path = "/" if delegate_path.startswith("//"): delegate_path = delegate_path[1:] urlconf = get_urlconf(current_page.delegate_to) try: result = resolve(delegate_path, urlconf) except Resolver404: raise Http404 if result: view, args, kwargs = result kwargs.update(context) return view(request, *args, **kwargs)
class Details(object): ''' This class based view get the root pages for navigation and the current page to display if there is any. All is rendered with the current page's template. ''' def __call__(self, request, path=None, lang=None, delegation=True, **kwargs): pass def resolve_page(self, request, context, is_staff): '''Return the appropriate page according to the path.''' pass def resolve_alias(self, request, path, lang): pass def resolve_redirection(self, request, context): '''Check for redirections.''' pass def get_navigation(self, request, path, lang): '''Get the pages that are at the root level.''' pass def choose_language(self, lang, request): '''Deal with the multiple corner case of choosing the language.''' pass def get_template(self, request, context): '''Just there in case you have special business logic.''' pass def is_user_staff(self, request): '''Return True if the user is staff.''' pass def extra_context(self, request, context): '''Call the PAGE_EXTRA_CONTEXT function if there is one.''' pass def delegate(self, request, context, delegation=True): pass
11
8
16
2
11
3
4
0.27
1
3
2
0
10
0
10
10
176
31
114
37
103
31
105
36
94
13
1
4
38
6,389
ArabellaTech/django-basic-cms
ArabellaTech_django-basic-cms/basic_cms/tests/testcase.py
basic_cms.tests.testcase.TestCase
class TestCase(TestCase): """Django page CMS test suite class""" fixtures = ['pages_tests.json'] counter = 1 settings_to_reset = {} old_url_conf = None def setUp(self): # useful to make sure the tests will be properly # executed in an exotic project. self.set_setting('PAGE_TEMPLATES', test_settings.PAGE_TEMPLATES) self.set_setting('PAGE_DEFAULT_TEMPLATE', test_settings.PAGE_DEFAULT_TEMPLATE) self.old_url_conf = getattr(settings, 'ROOT_URLCONF') setattr(settings, 'ROOT_URLCONF', 'basic_cms.testproj.urls') clear_url_caches() def tearDown(self): setattr(settings, 'ROOT_URLCONF', self.old_url_conf) for name, value in self.settings_to_reset.items(): setattr(pages_settings, name, value) self.reset_urlconf() self.settings_to_reset = {} def set_setting(self, name, value): old_value = getattr(pages_settings, name) setattr(pages_settings, name, value) if name == 'PAGE_USE_LANGUAGE_PREFIX': self.reset_urlconf() if name not in self.settings_to_reset: self.settings_to_reset[name] = old_value def assert404(self, func): try: response = func() if response.status_code != 404: raise Error404Expected except TemplateDoesNotExist: pass def get_admin_client(self): from django.test.client import Client client = Client() client.login(username='admin', password='b') return client def get_page_url(self, path=''): return reverse('pages-details-by-path', args=[path]) def reset_urlconf(self): url_conf = getattr(settings, 'ROOT_URLCONF', False) if url_conf: try: reload(import_module(url_conf)) except: pass reload(import_module('basic_cms.urls')) reload(import_module('basic_cms.testproj.urls')) clear_url_caches() def get_new_page_data(self, draft=False): """Helper method for creating page datas""" page_data = {'title': 'test page %d' % self.counter, 'slug': 'test-page-%d' % self.counter, 'language':'en-us', 'sites': [1], 'status': Page.DRAFT if draft else Page.PUBLISHED, # used to disable an error with connected models 'document_set-TOTAL_FORMS': 0, 'document_set-INITIAL_FORMS': 0, } self.counter = self.counter + 1 return page_data def new_page(self, content={'title': 'test-page'}, language='en-us'): author = User.objects.all()[0] page = Page.objects.create(author=author, status=Page.PUBLISHED, template='pages/examples/index.html') if pages_settings.PAGE_USE_SITE_ID: page.sites.add(Site.objects.get(id=1)) # necessary to clear old URL cache page.invalidate() for key, value in content.items(): Content(page=page, language='en-us', type=key, body=value).save() return page def create_new_page(self, client=None, draft=False): if not client: client = self.get_admin_client() page_data = self.get_new_page_data(draft=draft) response = client.post('/admin/basic_cms/page/add/', page_data) self.assertRedirects(response, '/admin/basic_cms/page/') slug_content = Content.objects.get_content_slug_by_slug( page_data['slug']) return slug_content.page
class TestCase(TestCase): '''Django page CMS test suite class''' def setUp(self): pass def tearDown(self): pass def set_setting(self, name, value): pass def assert404(self, func): pass def get_admin_client(self): pass def get_page_url(self, path=''): pass def reset_urlconf(self): pass def get_new_page_data(self, draft=False): '''Helper method for creating page datas''' pass def new_page(self, content={'title': 'test-page'}, language='en-us'): pass def create_new_page(self, client=None, draft=False): pass
11
2
8
0
7
1
2
0.08
0
3
3
4
10
0
10
10
97
14
77
28
65
6
69
28
57
3
0
2
21
6,390
ArabellaTech/django-basic-cms
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/ArabellaTech_django-basic-cms/basic_cms/widgets.py
basic_cms.widgets.markItUpRest.Media
class Media: js = [join(PAGES_MEDIA_URL, path) for path in ( 'javascript/jquery.js', 'markitup/jquery.markitup.js', 'markitup/sets/rst/set.js', )] css = { 'all': [join(PAGES_MEDIA_URL, path) for path in ( 'markitup/skins/simple/style.css', 'markitup/sets/rst/style.css', )] }
class Media: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
12
0
12
3
11
0
3
3
2
0
0
0
0
6,391
ArabellaTech/django-basic-cms
ArabellaTech_django-basic-cms/basic_cms/tests/testcase.py
basic_cms.tests.testcase.MockRequest
class MockRequest: REQUEST = {'language': 'en'} GET = {} META = {}
class MockRequest: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
4
0
4
4
3
0
4
4
3
0
0
0
0
6,392
ArabellaTech/django-basic-cms
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/ArabellaTech_django-basic-cms/basic_cms/widgets.py
basic_cms.widgets.RichTextarea.Media
class Media: js = [join(PAGES_MEDIA_URL, path) for path in ( 'javascript/jquery.js', )] css = { 'all': [join(PAGES_MEDIA_URL, path) for path in ( 'css/rte.css', )] }
class Media: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
9
0
9
3
8
0
3
3
2
0
0
0
0
6,393
ArabellaTech/django-basic-cms
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/ArabellaTech_django-basic-cms/basic_cms/widgets.py
basic_cms.widgets.EditArea.Media
class Media: js = [join(PAGES_MEDIA_URL, path) for path in ( 'edit_area/edit_area_full.js', )]
class Media: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
4
0
4
2
3
0
2
2
1
0
0
0
0
6,394
ArabellaTech/django-basic-cms
ArabellaTech_django-basic-cms/basic_cms/testproj/documents/admin.py
basic_cms.testproj.documents.admin.DocumentAdmin
class DocumentAdmin(admin.ModelAdmin): list_display = ('title', 'page',)
class DocumentAdmin(admin.ModelAdmin): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
3
1
2
2
1
0
2
2
1
0
1
0
0
6,395
ArabellaTech/django-basic-cms
ArabellaTech_django-basic-cms/basic_cms/testproj/documents/models.py
basic_cms.testproj.documents.models.Document
class Document(models.Model): "A dummy model used to illsutrate the use of linked models in django-page-cms" title = models.CharField(_('title'), max_length=100, blank=False) text = models.TextField(_('text'), blank=True) # the foreign key _must_ be called page page = models.ForeignKey(Page)
class Document(models.Model): '''A dummy model used to illsutrate the use of linked models in django-page-cms''' pass
1
1
0
0
0
0
0
0.5
1
0
0
0
0
0
0
0
8
2
4
4
3
2
4
4
3
0
1
0
0
6,396
ArabellaTech/django-basic-cms
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/ArabellaTech_django-basic-cms/basic_cms/widgets.py
basic_cms.widgets.TinyMCE
class TinyMCE(tinymce_widgets.TinyMCE): """TinyMCE widget.""" def __init__(self, language=None, attrs=None, mce_attrs=None, **kwargs): self.language = language if mce_attrs is None: mce_attrs = {} self.mce_attrs = mce_attrs self.mce_attrs.update({ 'mode': "exact", 'theme': "advanced", 'width': 640, 'height': 400, 'theme_advanced_toolbar_location': "top", 'theme_advanced_toolbar_align': "left" }) # take into account the default settings, don't allow # the above hard coded ones overriding them self.mce_attrs.update( getattr(settings, 'TINYMCE_DEFAULT_CONFIG', {})) super(TinyMCE, self).__init__(language, attrs, mce_attrs)
class TinyMCE(tinymce_widgets.TinyMCE): '''TinyMCE widget.''' def __init__(self, language=None, attrs=None, mce_attrs=None, **kwargs): pass
2
1
21
2
17
2
2
0.17
1
1
0
0
1
2
1
1
23
2
18
5
15
3
9
4
7
2
1
1
2
6,397
ArabellaTech/django-basic-cms
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/ArabellaTech_django-basic-cms/basic_cms/widgets.py
basic_cms.widgets.WYMEditor.Media
class Media: js = [join(PAGES_MEDIA_URL, path) for path in ( 'javascript/jquery.js', 'javascript/jquery.ui.js', 'javascript/jquery.ui.resizable.js', 'wymeditor/jquery.wymeditor.js', 'wymeditor/plugins/resizable/jquery.wymeditor.resizable.js', )] if "filebrowser" in getattr(settings, 'INSTALLED_APPS', []): js.append(join(PAGES_MEDIA_URL, 'wymeditor/plugins/filebrowser/jquery.wymeditor.filebrowser.js'))
class Media: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
12
1
11
2
10
0
4
2
3
0
0
1
0
6,398
ArabellaTech/django-basic-cms
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/ArabellaTech_django-basic-cms/basic_cms/widgets.py
basic_cms.widgets.markItUpHTML.Media
class Media: js = [join(PAGES_MEDIA_URL, path) for path in ( 'javascript/jquery.js', 'markitup/jquery.markitup.js', 'markitup/sets/default/set.js', )] css = { 'all': [join(PAGES_MEDIA_URL, path) for path in ( 'markitup/skins/simple/style.css', 'markitup/sets/default/style.css', )] }
class Media: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
12
0
12
3
11
0
3
3
2
0
0
0
0
6,399
ArabellaTech/django-basic-cms
ArabellaTech_django-basic-cms/basic_cms/tests/test_api.py
basic_cms.tests.test_api.CMSPagesApiTests
class CMSPagesApiTests(TestCase): maxDiff = None fixtures = ['pages_tests.json', 'api.json'] # def setUp(self): # self.original_data = Page.objects.from_path('terms', 'eng') # self.original_json_data = json.dumps(self.original_data.dump_json_data()) # self.original_html_data = render_to_string(self.original_data.template, # {"current_page": self.original_data}) def tests_basic_cms_api_access(self): from django.test.client import Client self.client = Client() self.original_data = Page.objects.from_path('terms', 'en-us') self.original_json_data = json.dumps(self.original_data.dump_json_data()) self.original_html_data = render_to_string(self.original_data.template, {"current_page": self.original_data}) data = { 'format': 'json' } response = self.client.get(reverse('basic_cms_api', args=['alamakota']), data) self.assertEqual(response.status_code, 404) response = self.client.get(reverse('basic_cms_api', args=['terms']), data) self.assertEqual(response.status_code, 200) self.assertDictEqual(json.loads(self.original_json_data), json.loads(response.content.decode("utf-8"))) # self.assertEqual(self.original_json_data, response.content) response = self.client.get(reverse('basic_cms_api', args=['terms'])) self.assertEqual(response.status_code, 200) self.assertIn('Please read these Terms of Use', response.content.decode("utf-8")) response = self.client.get(reverse('basic_cms_api', args=['coaches']), {'format': 'json'}) self.assertEqual(response.status_code, 200) self.assertEqual(response.data['title']['en-us'], 'coaches') self.assertEqual(len(response.data['children']), 3) self.assertEqual(response.data['children'][0]['title']['en-us'], 'Judith Singer') self.assertEqual(response.data['children'][1]['title']['en-us'], 'Melissa Litwak') self.assertEqual(response.data['children'][2]['title']['en-us'], 'Joanna Schaffler') def test_urls(self): from utils import links_append_domain body = """<a href="http://google.com">google.com</a><a href="foo">foo</a><a href="#a">#a</a><a href="/#a">/#a</a><img src="http://x.com/x.jpg"/><img src="a.jpg"/> """ return_body = """<html><body><a href="http://google.com">google.com</a><a href="http://a.com/foo">foo</a><a href="#a">#a</a><a href="/#a">/#a</a><img src="http://x.com/x.jpg"/><img src="http://a.com/a.jpg"/></body></html> """ self.assertEqual(links_append_domain(body, 'http://a.com').strip(), return_body.strip()) def test_hide_api(self): self.set_setting("PAGE_ADD_API", False) response = self.client.get('/pages/basic-cms-api/foo/') self.assertEqual(response.status_code, 404)
class CMSPagesApiTests(TestCase): def tests_basic_cms_api_access(self): pass def test_urls(self): pass def test_hide_api(self): pass
4
0
13
1
12
1
1
0.21
1
1
1
0
3
4
3
13
53
8
39
17
33
8
34
17
28
1
1
0
3