Exemplo n.º 1
0
 def setUp(self):
     with patch(
             "stripe.Product.retrieve",
             return_value=deepcopy(FAKE_PRODUCT),
             autospec=True,
     ):
         self.stripe_product = Product(id=FAKE_PRODUCT["id"]).api_retrieve()
Exemplo n.º 2
0
    def test_extend(
        self,
        customer_retrieve_mock,
        subscription_retrieve_mock,
        product_retrieve_mock,
        plan_retrieve_mock,
    ):
        subscription_fake = deepcopy(FAKE_SUBSCRIPTION)
        subscription_fake["current_period_end"] = datetime_to_unix(
            timezone.now() - timezone.timedelta(days=20))

        subscription_retrieve_mock.return_value = subscription_fake

        subscription = Subscription.sync_from_stripe_data(subscription_fake)
        self.assertFalse(subscription in self.customer.active_subscriptions)
        self.assertEqual(self.customer.active_subscriptions.count(), 0)

        delta = timezone.timedelta(days=30)
        extended_subscription = subscription.extend(delta)
        product = Product.sync_from_stripe_data(deepcopy(FAKE_PRODUCT))

        self.assertNotEqual(None, extended_subscription.trial_end)
        self.assertTrue(self.customer.has_active_subscription())
        self.assertTrue(self.customer.is_subscribed_to(product))
        self.assertTrue(self.customer.has_any_active_subscription())

        self.assert_fks(subscription,
                        expected_blank_fks=self.default_expected_blank_fks)
Exemplo n.º 3
0
def setup_remote_product(name: str, description: str) -> stripe.Product:
    product_to_save = {}
    create = True

    for remote_product in Product.api_list():
        if remote_product['name'] == name:
            product_to_save = remote_product
            create = False

    product_to_save['name'] = name
    product_to_save['type'] = 'service'
    product_to_save['statement_descriptor'] = name.upper()
    product_to_save['description'] = description

    if create:
        return stripe.Product.create(
            api_key=djstripe_settings.STRIPE_SECRET_KEY, **product_to_save)

    for k in ('object', 'created', 'livemode', 'type', 'updated'):
        if k in product_to_save:  # These keys might come back from server but can't be written
            del product_to_save[k]

    sid = product_to_save['id']
    del product_to_save['id']

    return stripe.Product.modify(sid,
                                 api_key=djstripe_settings.STRIPE_SECRET_KEY,
                                 **product_to_save)
Exemplo n.º 4
0
    def test___str__(self, count, monkeypatch):
        def mock_price_get(*args, **kwargs):
            return random_price_data

        # monkeypatch stripe.Product.retrieve and stripe.Price.retrieve calls to return
        # the desired json response.
        monkeypatch.setattr(stripe.Product, "retrieve", self.mock_product_get)
        monkeypatch.setattr(stripe.Price, "retrieve", mock_price_get)

        product = Product.sync_from_stripe_data(deepcopy(FAKE_PRODUCT))

        PRICE_DATA_OPTIONS = [
            deepcopy(FAKE_PRICE),
            deepcopy(FAKE_PRICE_TIER),
            deepcopy(FAKE_PRICE_METERED),
            deepcopy(FAKE_PRICE_ONETIME),
        ]
        for _ in range(count):
            random_price_data = PRICE_DATA_OPTIONS.pop()
            price = Price.sync_from_stripe_data(random_price_data)

        if count > 1:
            assert f"{FAKE_PRODUCT['name']} ({count} prices)" == str(product)
        else:
            assert f"{FAKE_PRODUCT['name']} ({price.human_readable_price})" == str(
                product)
Exemplo n.º 5
0
def get_or_create_starter_price():
    try:
        product = Product.objects.get(
            metadata__djstripe_example="example_subscription")
    except Product.DoesNotExist:
        print(
            "Could not find a subscription product to use. Will create one for you."
        )
        stripe_product = stripe.Product.create(
            name="Starter",
            metadata={"djstripe_example": "example_subscription"})
        product = Product.sync_from_stripe_data(stripe_product)

    try:
        return Price.objects.get(metadata__djstripe_example="starter_price")
    except Price.DoesNotExist:
        print(
            "Could not find a subscription price to use. Will create one for you."
        )
        stripe_price = stripe.Price.create(
            currency="usd",
            unit_amount="1200",
            recurring={"interval": "month"},
            product=product.id,
            metadata={"djstripe_example": "starter_price"},
        )
        return Price.sync_from_stripe_data(stripe_price)
Exemplo n.º 6
0
    def test_sync_from_stripe_data(self, monkeypatch):

        # monkeypatch stripe.Product.retrieve call to return
        # the desired json response.
        monkeypatch.setattr(stripe.Product, "retrieve", self.mock_product_get)
        product = Product.sync_from_stripe_data(deepcopy(FAKE_PRODUCT))

        assert product.id == FAKE_PRODUCT["id"]
        assert product.name == FAKE_PRODUCT["name"]
        assert product.type == FAKE_PRODUCT["type"]
Exemplo n.º 7
0
	def test_create_from_djstripe_product(self, plan_create_mock, product_retrieve_mock):
		fake_plan = deepcopy(FAKE_PLAN)
		fake_plan["product"] = Product.sync_from_stripe_data(self.stripe_product)
		fake_plan["amount"] = fake_plan["amount"] / 100
		self.assertIsInstance(fake_plan["product"], Product)

		plan = Plan.create(**fake_plan)

		plan_create_mock.assert_called_once_with(api_key=STRIPE_SECRET_KEY, **FAKE_PLAN)

		self.assert_fks(plan, expected_blank_fks={"djstripe.Customer.coupon"})
Exemplo n.º 8
0
def remote_product_cleanup():
    """Go through remote Products and remove those that are not in the local list of products."""
    for remote_product in Product.api_list():
        if remote_product['name'] in PRODUCT_NAMES:
            active = True
        else:
            active = False

        stripe.Product.modify(remote_product['id'],
                              api_key=djstripe_settings.STRIPE_SECRET_KEY,
                              active=active)
        LOGGER.info('Remote Product %s made %s', remote_product['name'],
                    'active' if active else 'inactive')
Exemplo n.º 9
0
    def test_create_from_djstripe_product(self, plan_create_mock,
                                          product_retrieve_mock):
        fake_plan = deepcopy(FAKE_PLAN)
        fake_plan["product"] = Product.sync_from_stripe_data(
            self.stripe_product)
        fake_plan["amount"] = fake_plan["amount"] / 100
        self.assertIsInstance(fake_plan["product"], Product)

        plan = Plan.create(**fake_plan)

        plan_create_mock.assert_called_once_with(api_key=STRIPE_SECRET_KEY,
                                                 **FAKE_PLAN)

        self.assert_fks(plan, expected_blank_fks={"djstripe.Customer.coupon"})
Exemplo n.º 10
0
    def test_create_from_djstripe_product(self, price_create_mock,
                                          product_retrieve_mock):
        fake_price = deepcopy(FAKE_PRICE)
        fake_price["product"] = Product.sync_from_stripe_data(
            self.stripe_product)
        fake_price["unit_amount"] /= 100
        assert isinstance(fake_price["product"], Product)

        price = Price.create(**fake_price)

        price_create_mock.assert_called_once_with(api_key=STRIPE_SECRET_KEY,
                                                  **FAKE_PRICE)

        self.assert_fks(price, expected_blank_fks={"djstripe.Customer.coupon"})
Exemplo n.º 11
0
    def test_is_status_temporarily_current(
        self, customer_retrieve_mock, product_retrieve_mock, plan_retrieve_mock
    ):
        product = Product.sync_from_stripe_data(deepcopy(FAKE_PRODUCT))
        subscription_fake = deepcopy(FAKE_SUBSCRIPTION)
        subscription = Subscription.sync_from_stripe_data(subscription_fake)
        subscription.canceled_at = timezone.now() + timezone.timedelta(days=7)
        subscription.current_period_end = timezone.now() + timezone.timedelta(days=7)
        subscription.cancel_at_period_end = True
        subscription.save()

        self.assertTrue(subscription.is_status_current())
        self.assertTrue(subscription.is_status_temporarily_current())
        self.assertTrue(subscription.is_valid())
        self.assertTrue(subscription in self.customer.active_subscriptions)
        self.assertTrue(self.customer.is_subscribed_to(product))
        self.assertTrue(self.customer.has_any_active_subscription())

        self.assert_fks(
            subscription, expected_blank_fks=self.default_expected_blank_fks
        )
Exemplo n.º 12
0
def plan_setup():
    remote_plan_cleanup()
    remote_product_cleanup()
    local_plan_cleanup()
    local_product_cleanup()
    for plan_definition in PLAN_DEFINITIONS:
        stripe_product = setup_remote_product(
            plan_definition[PlanDefinitionKey.NAME].value,
            plan_definition[PlanDefinitionKey.DESCRIPTION])
        stripe_plan = setup_remote_plan(stripe_product, plan_definition)

        product = Product.sync_from_stripe_data(stripe_product)
        Plan.sync_from_stripe_data(stripe_plan)

        try:
            pe = ProductExtension.objects.get(product=product)
        except ProductExtension.DoesNotExist:
            pe = ProductExtension(product=product)

        pe.allowances = json.dumps(plan_definition[PlanDefinitionKey.QUOTA])
        pe.tag_line = plan_definition[PlanDefinitionKey.TAG_LINE]
        pe.is_purchasable = plan_definition[PlanDefinitionKey.IS_PURCHASABLE]
        pe.save()
Exemplo n.º 13
0
 def setUp(self):
     product_data = deepcopy(FAKE_PRODUCT)
     self.stripe_product = Product.sync_from_stripe_data(product_data)