Esempio n. 1
0
 def setUp(self):
     #init users
     self.user1 = User('John')
     self.user2 = User('Paul')
     #init bids
     self.bid1 = Bid(10, self.user1)
     self.bid2 = Bid(6, self.user2)
     #init items
     self.item1 = Item('Item1')
     self.item1.new_bid(self.bid1, self.bid2)
     self.item2 = Item('Item2')
Esempio n. 2
0
	def save_item(self, item_data, update_max_id=False, front_page=False):
		"""
		Compile and save item to the database
		Each item is committed separately for better fault tolerance
		"""
		
		item = None
		# If item was lost
		if isinstance(item_data, LostItem):
			if not item_data.id:
				return None
			item = item_data
			db.session.add(item)
			debug_print("Lost %s because %s" % (item_data.id, item_data.reason), '\n')
		else:
			if 'id' not in item_data:
				debug_print('Skipping item because empty id', '\n')
				return None
			if item_data.get('type', None) in ('story', 'comment', 'poll', 'job', None):
				debug_print("Saving %d" % item_data['id'], '\n')
				compiled_data = self.compile_item_data(item_data, front_page)
				item = Item.create_or_update(compiled_data)
			else:
				debug_print("Skipping %s %d" % (item_data['type'], item_data['id']), '\n')
		
		if update_max_id:
			Status.set_max_item_id(item_data.id if isinstance(item_data, LostItem) else item_data['id'])
		
		db.session.commit()
		
		return item
Esempio n. 3
0
class TestItem(unittest.TestCase):
    def setUp(self):
        #init users
        self.user1 = User('John')
        self.user2 = User('Paul')
        #init bids
        self.bid1 = Bid(10, self.user1)
        self.bid2 = Bid(6, self.user2)
        #init items
        self.item1 = Item('Item1')
        self.item1.new_bid(self.bid1, self.bid2)
        self.item2 = Item('Item2')

    def test_init(self):
        self.assertEqual(self.item1.name, 'Item1', 'incorrect name for item')

    def test_new_bid(self):
        self.bid3 = Bid(12,self.user1)
        self.item2.new_bid(self.bid3)
        self.assertEqual(len(self.item2.bids), 1, 'invalid number of bids')

    def test_get_max_bid(self):
        self.assertEqual(self.item1.get_winning_bid().value, 10, 'incorrect max bid when not None')
        self.assertEqual(self.item2.get_winning_bid(), None, 'incorrect max bid when None')
Esempio n. 4
0
 def __post_init__(self):
     self.item = Item.get_by_id(self.item_id)
Esempio n. 5
0
 def get(self, name):
     item = Item.find_by_name(name)
     return item.json(), 200 if item else {
         'error': True,
         'message': 'Not found'
     }, 404
Esempio n. 6
0
def index():
    items = Item.find_all()
    return render_template("items/index.html", items=items)
Esempio n. 7
0
from decimal import Decimal

from expects import *
from mamba import *

from actions.checkout import Checkout
from models.item import Item
from models.pricing_rules import PricingRules, VoucherRule, TShirtRule

with description('Checkout'):
    with it('calculates the total amount considering only the one product scanned'
            ):
        item = Item('VOUCHER', 'Gift Card', Decimal(5.00))

        checkout = Checkout(PricingRules({}))
        checkout.scan(item)

        expect(checkout.calculate_total()).to(equal(item.price))

    with it('calculates correct total amount when pricing rules do not exist'):
        voucher = Item('VOUCHER', 'Gift Card', Decimal(5.00))
        t_shirt = Item('TSHIRT', 'Summer T-Shirt', Decimal(20.00))
        pants = Item('PANTS', 'Summer Pants', Decimal(7.50))

        checkout = Checkout(PricingRules({}))

        checkout.scan(voucher)
        checkout.scan(t_shirt)
        checkout.scan(pants)

        expect(checkout.calculate_total()).to(equal(Decimal(32.50)))
Esempio n. 8
0
import json

from flask import jsonify
from models.item import Item

items = {
    Item("Fresh out the oven", 1, "Freshly Baked Bread", 5),
    Item("Fresh out the stream", 2, "Rockscale Cod", 25)
}

# How the JSON should look
json_items = [{
    "description": "Fresh out the oven",
    "itemid": "1",
    "name": "Freshly Baked Bread",
    "price": "5"
}, {
    "description": "Fresh out the stream",
    "itemid": "2",
    "name": "Rockscale Cod",
    "price": "25"
}]


def get_inventory():
    json_string = {item.toJSON() for item in items}
    return json_string, 200


def get_item(itemid):
    for item in items:
def run_bot(type=Type.SUBMISSION,
            use_gac=False,
            reply_to_item=True,
            save_to_database=True):
    # Get the stream instance (contains session, type and data)
    s = stream.get_stream(type)
    log.info("Set up new stream")

    # Start the stream
    for submission in s.praw_session.subreddit("all").stream.submissions():
        # Generate an item with all the relevant data
        i = Item(type=type,
                 id=submission.name,
                 subreddit=submission.subreddit,
                 author=submission.author,
                 body=get_submission_body(submission))

        # Check if the item meets the criteria
        meets_criteria, result_code = check_criteria(
            item=i,
            data=s,
            history_err=s.submissions_err,
            history_ok=s.submissions_ok,
            mustBeAMP=True,
            mustBeNew=True,
            mustNotBeBannedInSubreddit=True,
            mustNotHaveFailed=True,
            mustNotBeMine=True,
            mustNotBeOptedOut=True)

        # If it meets the criteria, try to find the canonicals and make a reply
        if meets_criteria:
            log.info(f"{i.id} in r/{i.subreddit} meets criteria")
            # Get the urls from the body and try to find the canonicals
            urls = get_urls(i.body)
            i.links = get_urls_info(urls, use_gac)

            # If a canonical was found, generate a reply, otherwise log a warning
            if any(link.canonical
                   for link in i.links) or any(link.amp_canonical
                                               for link in i.links):
                # Generate a reply
                reply_text, reply_canonical_text = generate_reply(
                    links=i.links,
                    stream_type=s.type,
                    np_subreddits=s.np_subreddits,
                    item_type=i.type,
                    subreddit=i.subreddit)

                # Try to post the reply
                if reply_to_item:
                    try:
                        reply = submission.reply(reply_text)
                        log.info(f"Replied to {i.id} with {reply.name}")
                        update_local_data("submissions_ok", i.id)
                        s.submissions_ok.append(i.id)

                    except (Forbidden, Exception):
                        log.warning("Couldn't post reply!")
                        log.error(traceback.format_exc())
                        update_local_data("submissions_err", i.id)
                        s.submissions_err.append(i.id)

            # If no canonicals were found, log the failed attempt
            else:
                log.warning("No canonicals found")
                update_local_data("submissions_err", i.id)
                s.submissions_err.append(i.id)

            save_entry(save_to_database=save_to_database,
                       entry_type=type.value,
                       links=i.links)
Esempio n. 10
0
def run_bot(type=Type.MENTION,
            guess_and_check=True,
            reply_to_item=True,
            write_to_database=True):
    # Get the stream instance (contains session, type and data)
    s = stream.get_stream(type)
    log.info("Set up new stream")

    # Start the stream
    for message in s.praw_session.inbox.stream():
        # Mark the item as read
        message.mark_read()

        # Log the message type and id
        log.info(f"New message: {message.type}: {message.fullname}")

        # If the message is a comment_reply, ignore it
        if message.type == "comment_reply":
            continue
        # If the message is an username_mention, start summon process
        if message.type == "username_mention":
            parent = message.parent()
            i = Item(type=Type.MENTION,
                     id=parent.name,
                     subreddit=parent.subreddit,
                     author=parent.author,
                     context=message.context,
                     summoner=message.author,
                     parent_link=parent.permalink)

            # Check if the parent is a comment or submission
            if isinstance(parent, praw.models.Comment):
                i.body = parent.body
                i.parent_type = Type.COMMENT
            elif isinstance(parent, praw.models.Submission):
                i.body = get_submission_body(parent)
                i.parent_type = Type.SUBMISSION
            else:
                log.warning("Unknown parent instance")

            # Check if the item meets the criteria
            meets_criteria, result_code = check_criteria(
                item=i,
                data=s,
                history_failed=s.mentions_failed,
                history_success=s.mentions_success,
                mustBeAMP=True,
                mustBeNew=True,
                mustNotBeDisallowedSubreddit=True,
                mustNotHaveFailed=True,
                mustNotBeMine=True,
                mustNotBeOptedOut=True,
                mustNotHaveDisallowedMods=True)

            # If it meets the criteria, try to find the canonicals and make a reply
            if result_code != ResultCode.ERROR_NO_AMP:
                log.info(
                    f"{i.id} in r/{i.subreddit} is AMP, result_code={result_code.value}"
                )
                # Get the urls from the body and try to find the canonicals
                urls = get_urls(i.body)
                i.links = get_urls_info(urls, guess_and_check)

                # If a canonical was found, generate a reply, otherwise log a warning
                if any(link.canonical
                       for link in i.links) or any(link.amp_canonical
                                                   for link in i.links):
                    # Generate a reply
                    reply_text, reply_canonical_text = generate_reply(
                        stream_type=s.type,
                        np_subreddits=s.np_subreddits,
                        item_type=i.parent_type,
                        subreddit=i.subreddit,
                        links=i.links,
                        summoned_link=i.context)

                    # Send a DM if AmputatorBot can't reply because it's disallowed by a subreddit, mod or user
                    if result_code == ResultCode.ERROR_DISALLOWED_SUBREDDIT \
                            or result_code == ResultCode.ERROR_DISALLOWED_MOD \
                            or result_code == ResultCode.ERROR_USER_OPTED_OUT:

                        # Generate and send an error DM dynamically based on the error
                        subject, message = dm_generator(
                            result_code=result_code,
                            parent_link=i.parent_link,
                            parent_subreddit=i.subreddit,
                            parent_type=i.parent_type.value,
                            first_amp_url=i.links[0].url_clean,
                            canonical_text=reply_canonical_text)
                        s.praw_session.redditor(str(i.summoner)).message(
                            subject, message)
                        log.info(f"Send summoner DM of type {result_code}")

                    # Try to post the reply, send a DM to the summoner
                    elif reply_to_item:
                        try:
                            reply = parent.reply(reply_text)
                            log.info(f"Replied to {i.id} with {reply.name}")
                            update_local_data("mentions_success", i.id)
                            s.mentions_success.append(i.id)

                            # Generate and send a SUCCESS DM to the summoner
                            result_code = ResultCode.SUCCESS
                            subject, message = dm_generator(
                                result_code=result_code,
                                reply_link=reply.permalink,
                                parent_subreddit=i.subreddit,
                                parent_type=i.parent_type.value,
                                parent_link=i.parent_link,
                                first_amp_url=i.links[0].url_clean,
                                canonical_text=reply_canonical_text)
                            s.praw_session.redditor(str(i.summoner)).message(
                                subject, message)
                            log.info(f"Send summoner DM of type {result_code}")

                        except (Forbidden, Exception):
                            log.warning("Couldn't post reply!")
                            log.error(traceback.format_exc())
                            update_local_data("mentions_failed", i.id)
                            s.mentions_failed.append(i.id)

                            # Check if AmputatorBot is banned in the subreddit
                            is_banned = check_if_banned(i.subreddit)
                            if is_banned:
                                update_local_data("disallowed_subreddits",
                                                  i.subreddit)
                                s.disallowed_subreddits.append(i.subreddit)

                            # Generate and send an ERROR_REPLY_FAILED DM to the summoner
                            result_code = ResultCode.ERROR_REPLY_FAILED
                            subject, message = dm_generator(
                                result_code=result_code,
                                parent_type=i.parent_type.value,
                                parent_link=i.parent_link,
                                first_amp_url=i.links[0].url_clean,
                                canonical_text=reply_canonical_text)
                            s.praw_session.redditor(str(i.summoner)).message(
                                subject, message)
                            log.info(f"Send summoner DM of type {result_code}")

                # If no canonicals were found, log the failed attempt
                else:
                    log.warning("No canonicals found")
                    update_local_data("mentions_failed", i.id)
                    s.mentions_failed.append(i.id)

                    # Check if the domain is problematic (meaning it's raising frequent errors)
                    if any(link.domain in s.problematic_domains
                           for link in i.links):
                        result_code = ResultCode.ERROR_PROBLEMATIC_DOMAIN
                    else:
                        result_code = ResultCode.ERROR_NO_CANONICALS

                    # Generate and send an
                    subject, message = dm_generator(
                        result_code=result_code,
                        parent_type=i.parent_type.value,
                        parent_link=i.parent_link,
                        first_amp_url=i.links[0].url_clean)

                    s.praw_session.redditor(str(i.summoner)).message(
                        subject, message)

                # If write_to_database is enabled, make a new entry for every URL
                if write_to_database:
                    for link in i.links:
                        if link.is_amp:
                            add_data(session=get_engine_session(),
                                     entry_type=type.value,
                                     handled_utc=datetime.now().strftime(
                                         '%Y-%m-%d %H:%M:%S'),
                                     original_url=link.url_clean,
                                     canonical_url=link.canonical)

        # If the message is a DM / message, check for opt-out and opt-back-in requests
        elif message.type == "unknown":
            subject = message.subject.lower()
            if subject == "opt me out of amputatorbot":
                try:
                    author = message.author.name
                    log.info(f"New opt-out request by {author}")

                    # If the user is already opted out, notify the user
                    if author.casefold() in list(
                            user.casefold() for user in s.disallowed_users):
                        log.warning("User has already opted out!")
                        s.praw_session.redditor(author).message(
                            subject=
                            "You have already opted out of AmputatorBot",
                            message=
                            "You have already opted out, so AmputatorBot won't reply to your comments "
                            "and submissions anymore. You will still be able to see AmputatorBot's replies to "
                            "other people's content. Block u/AmputatorBot if you don't want that either. "
                            "Cheers!")

                    # If the user hasn't been opted out yet, add user to the list and notify the user
                    else:
                        log.info("User has not opted out yet")
                        update_local_data("disallowed_users", author)
                        s.disallowed_users.append(author)
                        s.praw_session.redditor(author).message(
                            subject=
                            "You have successfully opted out of AmputatorBot",
                            message=
                            "You have successfully opted out of AmputatorBot. AmputatorBot won't reply to your "
                            "comments and submissions anymore (although it can take up to 24 hours to fully "
                            "process your opt-out request). You will still be able to see AmputatorBot's "
                            "replies to other people's content. Block u/AmputatorBot if you don't want that "
                            "either. Cheers!")

                except (RedditAPIException, Forbidden, Exception):
                    log.error(traceback.format_exc())
                    log.warning(
                        f"Something went wrong while processing opt-out request {message.fullname}"
                    )

            elif subject == "opt me back in again of amputatorbot":
                try:
                    author = message.author.name
                    log.info(f"New opt-back-in request by {author}")

                    # If the user is not opted out, notify the user
                    if author.casefold() not in list(
                            user.casefold() for user in s.disallowed_users):
                        log.warning("User is not opted out!")
                        s.praw_session.redditor(author).message(
                            subject="You don't have to opt in of AmputatorBot",
                            message=
                            "This opt-back-in feature is meant only for users who choose to opt-out earlier "
                            "but now regret it. At no point did you opt out of AmputatorBot so there's no "
                            "need to opt back in. Cheers!")

                    # If the user has opted out, remove user from the list and notify the user
                    else:
                        log.info("User is currently opted out")
                        remove_local_data("disallowed_users", author)
                        s.disallowed_users.remove(author)
                        s.praw_session.redditor(author).message(
                            subject=
                            "You have successfully opted back in of AmputatorBot",
                            message=
                            "You have successfully opted back in of AmputatorBot, meaning AmputatorBot can "
                            "reply to your comments and submissions again (although it can take up to 24 hours "
                            "to fully process your opt-back-in request). Thank you! Cheers!"
                        )

                except (RedditAPIException, Forbidden, Exception):
                    log.error(traceback.format_exc())
                    log.warning(
                        f"Something went wrong while processing opt-back-in request {message.fullname}"
                    )

            elif "you've been permanently banned from participating in" in subject:
                subreddit = message.subreddit
                if subreddit:
                    log.info(f"New ban issued by r/{subreddit}")
                    is_banned = check_if_banned(subreddit)
                    if is_banned:
                        update_local_data("disallowed_subreddits", subreddit)
                        s.disallowed_subreddits.append(subreddit)
                        log.info(f"Added {subreddit} to disallowed_subreddits")
                else:
                    log.warning(
                        f"Message wasn't send by a subreddit, but by {message.author.name}"
                    )

        else:
            log.warning(f"Unknown message type: {message.type}")
            continue
        log.info("\n")
Esempio n. 11
0
def index():
    items = Item.all()
    return render_template('items/index.html', items=items)
Esempio n. 12
0
category1 = Category(name="Shoes")

session.add(category1)
session.commit()

category2 = Category(name="Toys")

session.add(category2)
session.commit()

#Add Items
item1 = Item(name="yeezy boost 350 v2 zebra",
             description="""The Adidas Yeezy Boost 350 V2 Zebra is easily one \
																		of the most coveted and hyped sneakers on the market to date. \
																		It has a striking black and white pattern that can make any outfit stand out from the rest. \
																		Aside from all the aesthetics, its utmost comfort is one of the main factors why many \
																		consumers have always wanted a pair of these hard-to-get kicks. It is undoubtedly an expensive, \
																		hard to acquire shoe like any other Yeezys, but such characteristics make it even \
																		more desirable to a huge number of consumers.""",
             category=category1,
             user_id=1)

session.add(item1)
session.commit()

item2 = Item(
    name="NERF N-Strike Elite Sonic Ice",
    description=
    """Take your N-Strike battling to the next level with the Rampage blaster! With a 25-dart drum, \
																			  the Rampage blaster gives you an incredible rapid-fire blitz, firing revolutionary Elite Darts at a range of 75 feet. \
																			  Release a storm of darts at your target by sliding the slam fire handle repeatedly while you hold down the trigger! \
																			  The drum works with other Clip System blasters (sold separately), and the Elite Darts work with any Elite blaster \
Esempio n. 13
0
def predict_item(item: Item):
    model = get_model()
    x, _ = item.to_vec()
    y = model.predict(np.array([x]))
    return float(y[0])
 def get_item(self, item_name: str) -> Item:
     snapshot = self.firestore_db.collection(
         self.item_coll_name).document(item_name).get()
     return Item.from_dict(snapshot.to_dict())
Esempio n. 15
0
def _populate_items(db_engine):
    session_maker = sessionmaker(bind=db_engine)
    session = session_maker()
    session.query(Item).delete()
    session.add(
        Item(id=1, name='stone', forage_drop_chance=90, mine_drop_chance=120))
    session.add(Item(id=2, name='iron ore', mine_drop_chance=15))
    session.add(Item(id=3, name='gold ore', mine_drop_chance=5))
    session.add(Item(id=4, name='copper ore', mine_drop_chance=10))
    session.add(Item(id=5, name='lead ore', mine_drop_chance=10))
    session.add(Item(id=6, name='nickel ore', mine_drop_chance=7))
    session.add(Item(id=7, name='tin ore', mine_drop_chance=8))
    session.add(Item(id=8, name='silver ore', mine_drop_chance=3))
    session.add(Item(id=9, name='platinum ore', mine_drop_chance=1))
    session.add(Item(id=10, name='zinc ore', mine_drop_chance=7))

    session.add(Item(id=11, name='unrefined diamond', mine_drop_chance=1))
    session.add(Item(id=12, name='unrefined ruby', mine_drop_chance=2))
    session.add(Item(id=13, name='unrefined topaz', mine_drop_chance=2))
    session.add(Item(id=14, name='unrefined sapphire', mine_drop_chance=2))
    session.add(Item(id=15, name='unrefined jade', mine_drop_chance=2))
    session.add(Item(id=16, name='unrefined amber', mine_drop_chance=2))
    session.add(Item(id=17, name='unrefined lapis lazuli', mine_drop_chance=2))
    session.add(Item(id=18, name='unrefined turquoise', mine_drop_chance=2))
    session.add(Item(id=19, name='unrefined amethyst', mine_drop_chance=2))
    session.add(Item(id=20, name='unrefined emerald', mine_drop_chance=2))
    session.add(Item(id=21, name='unrefined opal', mine_drop_chance=2))
    session.add(Item(id=22, name='unrefined quartz', mine_drop_chance=2))
    session.add(Item(id=23, name='unrefined peridot', mine_drop_chance=2))
    session.add(Item(id=24, name='unrefined onyx', mine_drop_chance=2))

    session.add(Item(id=25, name='stick', forage_drop_chance=90))
    session.add(Item(id=26, name='leaf', forage_drop_chance=20))
    session.add(Item(id=27, name='pine needle', forage_drop_chance=20))
    session.add(Item(id=28, name='brown mushroom', forage_drop_chance=5))
    session.add(
        Item(id=29,
             name='cucumber',
             forage_drop_chance=10,
             edible=True,
             hunger_satisfaction=5))
    session.add(
        Item(id=30,
             name='blueberry',
             forage_drop_chance=10,
             edible=True,
             hunger_satisfaction=1))
    session.add(
        Item(id=31,
             name='cherry',
             forage_drop_chance=10,
             edible=True,
             hunger_satisfaction=1))
    session.add(
        Item(id=32,
             name='banana',
             forage_drop_chance=10,
             edible=True,
             hunger_satisfaction=2))
    session.add(
        Item(id=33,
             name='orange',
             forage_drop_chance=10,
             edible=True,
             hunger_satisfaction=2))
    session.add(
        Item(id=34,
             name='pear',
             forage_drop_chance=10,
             edible=True,
             hunger_satisfaction=2))
    session.add(
        Item(id=35,
             name='carrot',
             forage_drop_chance=10,
             edible=True,
             hunger_satisfaction=2))
    session.commit()
Esempio n. 16
0
 def get(self, name):
     user = Item.find_by_name(name)
     if not user:
         return {'message': "User does not exist"}, 404
     return user.json()
Esempio n. 17
0
from models.item import Item

ipad = Item(
    "https://www.johnlewis.com/2018-apple-ipad-pro-12-9-inch-a12x-bionic-ios-wi-fi-cellular-512gb/space-grey/p3834614",
    "p", {"class": "price price--large"})

print(ipad.load_price())
Esempio n. 18
0
def get_items(catalog_id):
    catalog = Catalog.find_by_id(catalog_id)
    if not catalog:
        return jsonify({'message': 'Catalog not found'}), 404
    items = Item.find_by_catalog_id(catalog_id)
    return jsonify({'items': [item.serializer for item in items]}), 200
Esempio n. 19
0
from models.item import Item

items = {Item("Nike", "Running Shoes", 0), Item("Adidas", "Sneakers", 0)}
Esempio n. 20
0
 def get(self, _id):
     item = Item.find_by_id(_id)
     if item:
         return item.json(), 200
     return {'message': 'Item {} not found'.format(_id)}, 404
Esempio n. 21
0
class TestItem(TestCase):
    _item = Item()
    _note = Note()
    _task = Task()
    _db = SqlitePersistence(":memory:")

    def setUp(self):
        self._item.rig = "X01"
        self._item.description = "Something to handover"
        self._item.case = "CAS-12345"
        self._db.save(self._item)

        self._note.description = "Some update"
        self._note.item_id = 1
        self._db.save(self._note)

        self._task.description = "Some update"
        self._task.item_id = 1
        self._db.save(self._task)

    def test_an_item_has_a_rig(self):
        self.assertEqual(self._item.rig, "X01")

    def test_an_item_has_a_description(self):
        self.assertEqual(self._item.description, "Something to handover")

    def test_an_item_has_a_case(self):
        self.assertEqual(self._item.case, "CAS-12345")

    def test_a_saved_item_has_a_created_at_timestamp(self):
        item = self._db.find(Item, 1)
        self.assertIsNotNone(item.created_at)

    def test_a_saved_item_has_an_updated_at_timestamp(self):
        item = self._db.find(Item, 1)
        self.assertIsNotNone(item.updated_at)

    def test_a_saved_item_has_a_created_by(self):
        item = self._db.find(Item, 1)
        self.assertEqual(item.created_by, os.getlogin())

    def test_a_saved_item_that_is_not_complete_does_not_have_a_completed_at_timestamp(
            self):
        item = self._db.find(Item, 1)
        self._db.incomplete(Item, item.id)

        item = self._db.find(Item, item.id)

        self.assertIsNone(item.completed_at)

    def test_a_saved_item_that_is_completed_has_a_completed_at_timestamp(self):
        item = self._db.find(Item, 1)
        self._db.complete(Item, item.id)

        item = self._db.find(Item, item.id)
        self.assertIsNotNone(item.completed_at)
        self.assertEqual(item.updated_at, item.completed_at)
        self.assertEqual(item.updated_by, os.getlogin())

    def test_an_item_has_notes(self):
        note = self._db.find(Note, 1)
        item = self._db.find(Item, 1)

        self.assertEqual(item.notes[0].description, note.description)

    def test_an_item_has_tasks(self):
        task = self._db.find(Task, 1)
        item = self._db.find(Item, 1)

        self.assertEqual(item.tasks[0].description, task.description)

    def test_an_item_can_be_edited(self):
        item = self._db.find(Item, 1)

        data = {
            "rig": "X03",
            "description": "something else",
            "case": "123456"
        }
        self._db.edit(Item, item.id, data)
        edited = self._db.find(Item, 1)

        self.assertEqual(data["rig"], edited.rig)
        self.assertEqual(data["description"], edited.description)
        self.assertEqual(data["case"], edited.case)

    def test_created_updated_and_completed_properties_cannot_be_directly_edited(
            self):
        item = self._db.find(Item, 1)

        data = {
            "completed_at":
            datetime.datetime.now() - datetime.timedelta(minutes=1),
            "updated_at":
            datetime.datetime.now() - datetime.timedelta(minutes=1),
            "created_at":
            datetime.datetime.now() - datetime.timedelta(minutes=1),
            "created_by": "foo",
            "updated_by": "bar"
        }
        self._db.edit(Item, item.id, data)
        edited = self._db.find(Item, 1)

        self.assertNotEqual(data["completed_at"], edited.completed_at)
        self.assertNotEqual(data["updated_at"], edited.updated_at)
        self.assertNotEqual(data["created_at"], edited.created_at)
        self.assertNotEqual(data["created_by"], edited.created_by)
        self.assertNotEqual(data["updated_by"], edited.updated_by)
Esempio n. 22
0
 def __post_init__(self):
     """
     run after __init__ method, can access self., you've got above value s stored in self, you can do self.item_id
     """
     self.item = Item.get_by_id(self.item_id)
     self.user = User.find_by_email(self.user_email)
class TestSqlitePersistence(TestCase):
    _item = Item()
    _note = Note()
    _task = Task()
    _db = SqlitePersistence(":memory:")


    def setUp(self):
        self._db.reset_session()
        self._db.truncate_all_tables()
        item = Item()
        note = Note()
        task = Task()

        self._item.rig = item.rig = "X01"
        self._item.description = item.description = "Something to handover"
        self._item.case = item.case = "CAS-12345"
        item_saved = self._db.save(item)

        self._note.description = note.description = "Some update"
        self._note.item_id = note.item_id = 1
        note_saved = self._db.save(note)

        self._task.description = task.description = "Some update"
        self._task.item_id = task.item_id = 1
        task_saved = self._db.save(task)

    def test_save(self):
        self._db.reset_session()
        self._db.truncate_all_tables()
        self._db.save(self._item)
        self._db.save(self._note)
        self._db.save(self._task)

        items = self._db.session.query(Item).all()

        item_count = len(items)
        note_count = len(self._db.session.query(Note).all())
        task_count = len(self._db.session.query(Task).all())

        self.assertEqual(1, item_count)
        self.assertEqual(1, note_count)
        self.assertEqual(1, task_count)




    def test_find(self):
        items = self._db.session.query(Item).all()
        print(items)
        item_found = self._db.find(Item, 1)
        note_found = self._db.find(Note, 1)
        task_found = self._db.find(Task, 1)

        self.assertEqual(self._item.description, item_found.description)
        self.assertEqual(self._note.description, note_found.description)
        self.assertEqual(self._task.description, task_found.description)

        self.assertRaises(Exception, self._db.find(Item, 50))



    def test_get_incomplete_items(self):
        item2 = Item()
        item2.rig = "X02"
        item2.description = "Another description"
        item2.case = "CAS-23456"
        self._db.save(item2)
        self._db.complete(Item, 2)

        incomplete_items = self._db.get_incomplete_items()

        self.assertEqual(1, len(incomplete_items))
        self.assertEqual(self._item.rig, incomplete_items[0].rig)


    def test_edit(self):
        item = self._db.find(Item, 1)

        data = {"rig": "X03",
                "description": "something else",
                "case": "123456"}
        self._db.edit(Item, item.id, data)
        edited = self._db.find(Item, 1)

        self.assertEqual(data["rig"], edited.rig)
        self.assertEqual(data["description"], edited.description)
        self.assertEqual(data["case"], edited.case)

        note = self._db.find(Note, 1)
        data = {"description": "another note"}
        self._db.edit(Note, note.id, data)
        edited = self._db.find(Note, note.id)

        self.assertEqual(data["description"], edited.description)

        task = self._db.find(Task, 1)
        self._db.edit(Task, task.id, data)
        edited = self._db.find(Task, task.id)

        self.assertEqual(data["description"], edited.description)

    def test_complete(self):
        item = self._db.find(Item, 1)
        self.assertIsNone(item.completed_at)

        self._db.complete(Item, item.id)

        completed_item = self._db.find(Item, 1)

        self.assertIsNotNone(completed_item.completed_at)

    def test_incomplete(self):
        item = self._db.find(Item, 1)
        self.assertIsNone(item.completed_at)
        self._db.complete(Item, item.id)
        completed_item = self._db.find(Item, 1)
        self.assertIsNotNone(completed_item.completed_at)
        self._db.incomplete(Item, completed_item.id)
        incomplete_item = self._db.find(Item, 1)
        self.assertIsNone(incomplete_item.completed_at)

    def test_get_items_completed_in_past_day(self):
        item2 = Item()
        item2.rig = "X02"
        item2.description = "Another description"
        item2.case = "CAS-23456"
        item2.completed_at = datetime.datetime.now() - datetime.timedelta(days=1)
        self._db.save(item2)
        self._db.complete(Item, 2)

        item1 = self._db.find(Item, 1)
        self._db.find(Item, item1.id)

        complete_items = self._db.get_items_completed_in_past_day()

        self.assertEqual(1, complete_items.count())

    def test_get_items_completed_in_past_day(self):
        item2 = Item()
        item2.rig = "X02"
        item2.description = "Another description"
        item2.case = "CAS-23456"
        item2.completed_at = datetime.datetime.now() - datetime.timedelta(days=6)
        self._db.save(item2)
        self._db.complete(Item, 2)

        item1 = self._db.find(Item, 1)
        self._db.find(Item, item1.id)

        complete_items = self._db.get_items_completed_in_past_day()

        self.assertEqual(1, complete_items.count())

    def prep_db(self):
        db = SqlitePersistence(":memory:")
        db.session.rollback()
        db.save(self._item)
        db.save(self._note)
        db.save(self._task)
        return db
Esempio n. 24
0
def run_bot(type=Type.SUBMISSION,
            guess_and_check=False,
            reply_to_item=True,
            write_to_database=True):
    # Get the stream instance (contains session, type and data)
    s = stream.get_stream(type)
    log.info("Set up new stream")

    # Start the stream
    for submission in s.praw_session.subreddit("+".join(
            s.allowed_subreddits)).stream.submissions():
        # Generate an item with all the relevant data
        i = Item(type=type,
                 id=submission.name,
                 subreddit=submission.subreddit,
                 author=submission.author,
                 body=get_submission_body(submission))

        # Check if the item meets the criteria
        meets_criteria, result_code = check_criteria(
            item=i,
            data=s,
            history_failed=s.submissions_failed,
            history_success=s.submissions_success,
            mustBeAMP=True,
            mustBeNew=True,
            mustNotBeDisallowedSubreddit=False,
            mustNotHaveFailed=True,
            mustNotBeMine=True,
            mustNotBeOptedOut=True,
            mustNotHaveDisallowedMods=False)

        # If it meets the criteria, try to find the canonicals and make a reply
        if meets_criteria:
            log.info(f"{i.id} in r/{i.subreddit} meets criteria")
            # Get the urls from the body and try to find the canonicals
            urls = get_urls(i.body)
            i.links = get_urls_info(urls, guess_and_check)

            # If a canonical was found, generate a reply, otherwise log a warning
            if any(link.canonical
                   for link in i.links) or any(link.amp_canonical
                                               for link in i.links):
                # Generate a reply
                reply_text, reply_canonical_text = generate_reply(
                    stream_type=s.type,
                    np_subreddits=s.np_subreddits,
                    item_type=i.type,
                    links=i.links,
                    subreddit=i.subreddit)

                # Try to post the reply
                if reply_to_item:
                    try:
                        reply = submission.reply(reply_text)
                        log.info(f"Replied to {i.id} with {reply.name}")
                        update_local_data("submissions_success", i.id)
                        s.submissions_success.append(i.id)

                    except (Forbidden, Exception):
                        log.warning("Couldn't post reply!")
                        log.error(traceback.format_exc())
                        update_local_data("submissions_failed", i.id)
                        s.submissions_failed.append(i.id)

                        # Check if AmputatorBot is banned in the subreddit
                        is_banned = check_if_banned(i.subreddit)
                        if is_banned:
                            update_local_data("disallowed_subreddits",
                                              i.subreddit)
                            s.disallowed_subreddits.append(i.subreddit)

            # If no canonicals were found, log the failed attempt
            else:
                log.warning("No canonicals found")
                update_local_data("submissions_failed", i.id)
                s.submissions_failed.append(i.id)

            # If write_to_database is enabled, make a new entry for every URL
            if write_to_database:
                for link in i.links:
                    if link.is_amp:
                        add_data(session=get_engine_session(),
                                 entry_type=type.value,
                                 handled_utc=datetime.now().strftime(
                                     '%Y-%m-%d %H:%M:%S'),
                                 original_url=link.url_clean,
                                 canonical_url=link.canonical)
Esempio n. 25
0
 def __post_init__(self):
     self.item = Item.get_by_id(self.item_id)
     self.user = User.find_by_email(self.user_email)
from models.item import Item
import psycopg2

item = Item.find_by_id(1)
print(item)
#Item.create_item("Teste 3")
#item2 = Item.find_by_id(8)

item_update = Item.find_by_id(4)
data = ["Update Teste", True]
item_update.update_item(4, data)
#Item.delete_item(10)



Esempio n. 27
0
from models.item import Item

list_items = [
    Item(
        name="Toy Dinosaur",
        typeof="goods",
        category="children",
        description=
        "This is my favourite toy dinosaur and I'm only willing to barter it because I'm middle-aged and my mummy said I had to. A bit chewed but otherwise in good condition.",
        image=
        "https://www.nhmshop.co.uk/media/catalog/product/cache/207e23213cf636ccdef205098cf3c8a3/d/i/dino-roar-61232.jpg",
        listed=True,
        wishlisted=0,
        user=1),
    Item(
        name="House",
        typeof="goods",
        category="home_and_garden",
        description=
        "A lovely farmhouse in Kipling, Saskatchewan. I traded it for a movie role in the film Donna on Demand. Don't ask why anyone would accept that...",
        image=
        "https://upload.wikimedia.org/wikipedia/commons/b/b4/Red-paperclip-news-1.jpg",
        listed=True,
        wishlisted=0,
        user=4),
    Item(
        name="Driver for an two hours",
        typeof="services",
        category="motor",
        description=
        "I don't have any money, but I do have a car. Willing to ferry you about for up to 3 hours, but you have to pay for petrol!",
Esempio n. 28
0
 def __init__(self, item_id: str, price_limit: float, _id: str = None):
     super().__init__()
     self.item_id = item_id
     self.item = Item.get_by_id(item_id)
     self.price_limit = price_limit
     self._id = _id or uuid.uuid4().hex
Esempio n. 29
0
 def __init__(self, item_id: str, price_limit: float, _id: str = None):
     super().__init__(_id)
     self.item_id = item_id
     self.price_limit = price_limit
     self.item = Item.find_by_id(self.item_id)
Esempio n. 30
0
 def get(self, name):
     item = Item.find_by_name(name)
     if item:
         return item.json(), 200
     else:
         return {'message': 'Item not found.'}, 404
Esempio n. 31
0
    def patch(self, id):
        request_data = request.json
        at_risk_user = AtRiskUser.query.filter_by(at_risk_user_id=id).first()
        if at_risk_user is None:
            return {
                'data': {
                    'id': 'shoppinglist',
                    'attributes': {
                        'error': "At risk user #{} not found".format(id)
                    }
                }
            }, 400
        store = at_risk_user.store[0]
        if at_risk_user.shopping_lists == []:
            return {
                'data': {
                    'id': 'shoppinglist',
                    'attributes': {
                        'error': "No shopping list associated with this user"
                    }
                }
            }, 400
        else:
            shopping_list = at_risk_user.shopping_lists[-1]
            shopping_list.status = request_data['status']
            db.session.commit()
            for item in shopping_list.items:
                db.session.delete(item)
                db.session.commit()
            for item in request_data["items"]:
                db.session.add(Item(shopping_list_id=shopping_list.id, **item))
                db.session.commit()

            return {
                'data': {
                    "id": "shoppinglist",
                    "attributes": {
                        "name":
                        store.name,
                        "address":
                        store.address,
                        "city":
                        store.city,
                        "state":
                        store.state,
                        "zipcode":
                        store.zipcode,
                        "storeId":
                        store.location_id,
                        "latitude_longitude":
                        [float(store.latitude),
                         float(store.longitude)],
                        "status":
                        shopping_list.status,
                        "created_date":
                        shopping_list.created_date.strftime(
                            "%d/%m/%Y %H:%M:%S"),
                        "items": [item.json() for item in shopping_list.items]
                    }
                }
            }, 200
Esempio n. 32
0
 def put(self, name):
     data = request.get_json()
     item = Item(name, data['price'], data['store_id'])
     item.save_to_db()
     return item.json()
Esempio n. 33
0
    def put(self, name):
        #data = request.get_json()
        data = ItemResource.parser.parse_args()
        item = Item.find_by_name(name)
        if item is None:
            item = Item(None, name, data['price'], data['store_id'])
            item.set_id(None)
            item.set_name(name)
        else:
            item.price = data['price']
        item.save_to_db()

        return item.json()