class Customer: def __init__(self, name, password, email): self.name = name self.password = password self.email = email self.subscription = None self.websites = list() def __str__(self): return "{}".format(self.name) def add_website(self, website): if self.__can_add_website(): self.websites.append(website) def add_subscription(self, plan, renew_date=datetime.datetime.today().date()): self.subscription = Subscription(plan, renew_date) def change_plan(self, plan): self.subscription.change_plan(plan) def has_active_subscription(self): return self.subscription.is_active() @property def current_plan(self): return self.subscription.plan def __can_add_website(self): return self.has_active_subscription() and self.current_plan.new_website_allowed(len(self.websites))
async def on(self, channel: str, queue: int, func: Callable[[HorseMessage], None], auto_join: bool = True): """ Subscribes to a queue in a channel :param channel: Channel name :param queue: Queue Id :param func: Function that will be called when a message is received :param auto_join: If true and client still not joined to channel, joins :return: """ subs = next((x for x in self.__subscriptions if not x.direct and x.channel == channel and x.content_type == queue), None) if not subs: subs = Subscription() subs.channel = channel subs.content_type = queue subs.direct = False self.__subscriptions.append(subs) subs.actions.append(func) if auto_join: joined = next((x for x in self.__joined_channels if x == channel), None) if not joined: await self.join(channel)
def create_subscriprion(chat_id: int, text: str, region_code: int) -> Subscription: subscription = Subscription(chat_id, text, region_code) subscription.id = subscription.get_subscription_hash() sql = 'INSERT INTO Subscriptions (Id, ChatId, Text, RegionCode, CreatedAt) VALUES (?, ?, ?, ?, ?)' subscription.created_at = datetime.now().strftime(helpers.datetime_format) insert_values = (subscription.id, subscription.chat_id, subscription.text, subscription.region_code, subscription.created_at) dbHelper.insert_or_update(sql, insert_values) return subscription
def parseSubscription(self,message_data): print("Parsing Subscription") text = message_data.get_text() t = text.split()[1] if(t == "weather"): topic = EVENTID_WEATHER_SUBSCRIPTION occ = self.get_time_from_text(text) interval = timedelta(days = 1) sub = Subscription(topic,occ,interval,message_data) sub.post(self.eb)
def subsrcibe_to_plan(self, plan): """ The function to enable user's subscribe to a plan. Parameters: plan (Object): The Plan to be subscribed to. Returns: Object: A subscription object contain details of the subscription. """ self.check_auth() new_sub = Subscription(self, plan) new_sub.save() return new_sub
def main(): res = [] res.append(Subscription("a", "*****@*****.**", "compa")) res.append(Subscription("b", "*****@*****.**", "compa")) res.append(Subscription("c", "*****@*****.**", "compa")) ret = "[" for sub in res: ret = ret + json.dumps(sub.__dict__) + "," ret = ret + "]" with open("demo.json", "wt") as text_file: text_file.write(ret) print(ret)
def delete(self, subscription: Subscription) -> bool: topic = subscription.topic del_ok = False try: self._subscriptions[topic].remove(subscription) subscription.die() del_ok = True # Remove topic if there's no subscribers left. if len(self._subscriptions[topic]) == 0: self._subscriptions[topic].remove(topic) except KeyError: Log.debug(f'Failed to find sub on topic {topic}') return del_ok
def start_subscription(self, target, target_attr, subscripter_attr=None, subscripter_password=None): """Send a subscription request to the object given by parameter.""" try: s = Subscription(target, target_attr, subscripter_attr, subscripter_password) s.subscripter_uri = self.pyro4id t = threading.Thread(target=self.thread_subscriber, args=(s, )) self.workers.append(t) t.start() except Exception: print "[ERROR] start_subscription. Error sending {}".format(target) raise
def test_create_subscription(self): """Test creating subscription object""" with mock.patch('subscription.datetime') as mocked_date: mocked_date.now.return_value = datetime(2019, 1, 1) new_sub = Subscription(self.user, self.plan) self.assertEqual(new_sub.user, self.user) self.assertEqual(new_sub.plan, self.plan) self.assertDictEqual(new_sub.websites, {}) self.assertEqual(new_sub.start_date, datetime(2019, 1, 1)) self.assertEqual(new_sub.get_end_date, datetime(2019, 1, 1) + timedelta(days=365))
def on_direct(self, content_type: int, func: Callable[[HorseMessage], None]): """ Subscribes to all direct messages with specified content type :param content_type: Message content type :param func: Function that will be called when a message is received :return: """ subs = next((x for x in self.__subscriptions if x.direct and x.content_type == content_type), None) if not subs: subs = Subscription() subs.channel = None subs.content_type = content_type subs.direct = True self.__subscriptions.append(subs) subs.actions.append(func)
def subscription(self, name, listener, min_delta=0, read_only=False): # Get a channel from the factory channel = None for regex, factory in self._factory.items(): m = regex.match(name) if m: channel = factory.get_channel(m.group(1)) break assert channel is not None, \ "Failed to find a channel match for {}".format(name) sub = Subscription(channel, listener, min_delta, read_only) return sub
class TestCustomer(unittest.TestCase): def setUp(self): self.single_plan = Plan('Single', 49, 1) self.plus_plan = Plan('Plus', 99, 3) self.renewal_date = datetime.datetime.today().date() self.subscription_1 = Subscription(self.single_plan, self.renewal_date) def test_is_subscription_active(self): self.assertTrue(self.subscription_1.is_active()) def test_is_subscription_not_active(self): self.renewal_date = datetime.datetime.today().date() + relativedelta( years=-1) self.subscription_1 = Subscription(self.single_plan, self.renewal_date) self.assertFalse(self.subscription_1.is_active()) def test_renew_subscription_for_one_year(self): self.subscription_1.renew(self.renewal_date) self.assertGreater(self.subscription_1.renewal_date.year, self.renewal_date.year) def test_plan_change_for_subscription(self): old_price_before_plan_change = self.subscription_1.plan.price self.subscription_1.change_plan(self.plus_plan) new_price_after_plan_change = self.subscription_1.plan.price self.assertNotEqual(old_price_before_plan_change, new_price_after_plan_change)
def get_subscription(self, topic_name, subscription_name): """ 获取Account的一个Subscription对象 @type topic_name: string @param topic_name: 主题名称 @type subscription_name: string @param subscription_name: 订阅名称 @rtype: Subscription object @return: 返回该Account指定Topic的一个Subscription对象 """ return Subscription(topic_name, subscription_name, self.mns_client, self.debug)
def setUp(self): self.single_plan = Plan('Single', 49, 1) self.plus_plan = Plan('Plus', 99, 3) self.renewal_date = datetime.datetime.today().date() self.subscription_1 = Subscription(self.single_plan, self.renewal_date)
def add_subscription(self): new_subscription = Subscription() sid = new_subscription.sid() self._subscriptions[sid] = new_subscription return new_subscription
def get_all_subscriptions() -> List[Subscription]: # последовательность полей в запросе должна быть такой же как последовательность полей в dataclass Subscription sql = 'SELECT ChatId, Text, RegionCode, Id, CreatedAt FROM Subscriptions' rows = dbHelper.select(sql) return [Subscription(*r) for r in rows] if rows else []
def test_repr_method(self): """Test repr method""" new_sub = Subscription(self.user, self.plan) self.assertEqual(f'<Subcription with {self.plan} plan>', str(new_sub))
def setup_funcs(url, func_name): s = Subscription(url) if func_name == 'initialize': return s.initialize(settings.SUBSCRIPTIONS_FILE_FOR_TEST, ut=True) return s.update(settings.SUBSCRIPTIONS_FILE_FOR_TEST, ut=True)
def subscription_info(self, subscription_id): subscription_data = self.find_subscription(subscription_id) customer_data = self.find_customer(subscription_id) trainer_data = self.find_trainer(subscription_id) equipment_data = self.find_equipment(subscription_id) plan_data = self.find_plan(subscription_id) return f"{subscription_data}\n" \ f"{customer_data}\n" \ f"{trainer_data}\n" \ f"{equipment_data}\n" \ f"{plan_data}" customer = Customer("John", "Maple Street", "*****@*****.**") equipment = Equipment("Treadmill") trainer = Trainer("Peter") subscription = Subscription("14.05.2020", 1, 1, 1) plan = ExercisePlan(1, 1, 20) gym = Gym() gym.add_customer(customer) gym.add_equipment(equipment) gym.add_trainer(trainer) gym.add_plan(plan) gym.add_subscription(subscription) print(Customer.get_next_id()) print(gym.subscription_info(1))
def open(self, queue, prefetch_count=1): if not self._connected: raise RuntimeError('Not connected to RabbitMQ') return Subscription(self._connection, queue, prefetch_count)
def test_valid_sub(self): """Test user subscription is still valid""" new_sub = Subscription(self.user, self.plan) new_sub.check_sub() self.assertTrue(new_sub.get_end_date > datetime.now(timezone.utc))
def test_save_sub(self): """Test saving subscription to the database""" new_sub = Subscription(self.user, self.plan) new_sub.save() self.assertEqual(database['subscriptions']['*****@*****.**'], new_sub)
def test_is_subscription_not_active(self): self.renewal_date = datetime.datetime.today().date() + relativedelta( years=-1) self.subscription_1 = Subscription(self.single_plan, self.renewal_date) self.assertFalse(self.subscription_1.is_active())
def get_subscription(self): return Subscription.get_by_id(self.subscription_id)
def test_get_plan(self): """test getting plan associated with a subscription""" new_sub = Subscription(self.user, self.plan) result = new_sub.get_plan() self.assertEqual(result, new_sub.plan)
def add_subscription(self, plan, renew_date=datetime.datetime.today().date()): self.subscription = Subscription(plan, renew_date)