Exemple #1
0
def update_items():
    """
    Update the DB table containing item info from Riot API.
    """
    items = riot_api.static_get_item_list()
    Item.objects.all().delete()

    for k in items['data']:
        # plaintext and group are not present for every item
        if 'plaintext' in items['data'][k]:
            plain_text = items['data'][k]['plaintext']
        else:
            plain_text = None

        if 'group' in items['data'][k]:
            group = items['data'][k]['group']
        else:
            group = None

        item = Item(item_id=items['data'][k]['id'],
                    description=items['data'][k]['description'],
                    name=items['data'][k]['name'],
                    plain_text=plain_text,
                    group=group)
        item.save()
Exemple #2
0
def update_items():
    """
    Update the DB table containing item info from Riot API.
    """
    items = riot_api.static_get_item_list()
    Item.objects.all().delete()

    for k in items['data']:
        # plaintext and group are not present for every item
        if 'plaintext' in items['data'][k]:
            plain_text = items['data'][k]['plaintext']
        else:
            plain_text = None

        if 'group' in items['data'][k]:
            group = items['data'][k]['group']
        else:
            group = None

        item = Item(item_id=items['data'][k]['id'],
                    description=items['data'][k]['description'],
                    name=items['data'][k]['name'],
                    plain_text=plain_text,
                    group=group)
        item.save()
Exemple #3
0
def create_dummy_items(quantity=2):
    items = []
    for x in range(2):
        b = Item(name=f'item_{x}', product_code=f'QQ-{x}-{x*3}')
        b.save()
        items.append(b)
    return items
Exemple #4
0
    def add_item():
        ranking = request.json['ranking']
        category_id = request.json['category_id']
        same_rank_item = Item.query.filter_by(ranking=ranking,
                                              category_id=category_id).first()
        if same_rank_item is not None:
            readjust_ranking(int(ranking),
                             None,
                             int(category_id),
                             is_firsttime=True)
        title = request.json['title']
        des = request.json['description']

        item_meta = request.json['item_meta']

        new_item = Item(title, des, ranking, category_id, item_meta)
        try:
            new_item.save()
        except SQLAlchemyError as e:
            print(e.args[0])
            errorMsg = SERVER_ERROR_MSG
            return jsonify(error=errorMsg),\
                500, {'Content-Type': 'application/json; charset=utf-8'}
        return (item_schema.jsonify(new_item), 201, {
            'Content-Type': 'application/json; charset=utf-8'
        })
Exemple #5
0
 def test_can_create_same_item_from_different_lists(self):
     list1 = TodoList.objects.create()
     list2 = TodoList.objects.create()
     Item.objects.create(todo_list=list1,
                         title="test title",
                         body=" some body :-)")
     item = Item(todo_list=list2, title="test title", body=" some body :-)")
     item.full_clean()
Exemple #6
0
    def add_item(self, order):
        keyword, amount = self.extract_parameters()

        if keyword:
            product = Product.objects.filter(keyword=keyword).first()

            if product:
                item = Item(order=order, product=product, amount=amount)
                item.save()
                return None

            return AnswerService.answer(
                AnswerService.product_not_found(keyword))
        return AnswerService.answer(AnswerService.product_is_required())
Exemple #7
0
def add_location_item(location_id):
    body = request.get_json()

    item = Item(name=body['name'], price=body['price'])
    db.session.add(item)
    db.session.flush()

    item_stock = ItemStock(item_id=item.id,
                           location_id=location_id,
                           quantity=body['quantity'])
    db.session.add(item_stock)
    db.session.commit()

    return jsonify(item.with_stock(item_stock))
Exemple #8
0
def generate_mock_data(num_labels, num_items):
    fake = Faker()
    fake.add_provider(lorem)

    labels = []
    for _ in range(num_labels):
        label = Label(name=fake.word())
        label.save()
        labels.append(label)

    for _ in range(num_items):
        item = Item(title=fake.sentence(),
                    description=fake.paragraph())
        item.save()
        item.labels.add(*random_subset(labels))
Exemple #9
0
def discussion_init(request):
    """
    Given a slug, show its positions.

    :param request: Request
    :return:
    """
    db_issue = request.validated['issue']
    intro = get_translation(_.initialPositionInterest, db_issue.lang)

    bubbles = [
        create_speechbubble_dict(BubbleTypes.SYSTEM,
                                 uid='start',
                                 content=intro,
                                 omit_bubble_url=True,
                                 lang=db_issue.lang)
    ]

    db_positions = DBDiscussionSession.query(Statement).filter(
        Statement.is_disabled == False, Statement.issue_uid == db_issue.uid,
        Statement.is_position == True).all()

    items = [
        Item([pos.get_textversion().content],
             "{}/attitude/{}".format(db_issue.slug, pos.uid))
        for pos in db_positions
    ]

    return {'bubbles': [Bubble(bubble) for bubble in bubbles], 'items': items}
Exemple #10
0
    def __create__random_result(self):
        def rnd():
            return randint(1, 1000)

        suffix = rnd()

        env = Env(name=f'Test Env {suffix}', short_name=f'TE{suffix}')
        component = Component(name=f'Test Component {suffix}')
        item = Item(name=f'Test Item {suffix}', args=f'args {suffix}')
        status = Status(test_status='Passed', priority=suffix)
        platform = Platform(name=f'Test Platform {suffix}')
        os = Os(name=f'Test Os {suffix}')
        run = Run(name=f'Test Run {suffix}', session=f'Test Session {suffix}')

        return Result(
            validation=Validation(
                name=f'Test Validation {suffix}',
                env=env,
                platform=platform,
                os=os,
            ),
            env=env,
            platform=platform,
            os=os,
            component=component,
            item=item,
            status=status,
            run=run,
        )
def add_item():
    print(request.json['name'])
    name = request.json['name']
    category = request.json['category']
    price = request.json['price']
    item = Item(name=name, category=category, price=price)
    db.session.add(item)
    db.session.commit()
    return jsonify({'messege': 'Success'})
Exemple #12
0
def upload(request):
    item = Item( \
        uid=request.POST["uid"], \
        addtime=datetime.datetime.now().strftime("%Y%m%d%H%M%S"), \
        status_remove=0, \
        imgid=(request.POST["imgid"] if "imgid" in request.POST else "" ), \
        iname=(request.POST["iname"] if "iname" in request.POST else "" ), \
        imghdw=(request.POST["imghdw"] if "imghdw" in request.POST else 1 ), \
        itext=(request.POST["itext"] if "itext" in request.POST else "" ), \
        iam=(request.POST["iam"] if "iam" in request.POST else "" ), \
        igps=(request.POST["igps"] if "igps" in request.POST else "" ), \
        igpswhere=(request.POST["igpswhere"] if "igpswhere" in request.POST else "陕西省" ), \
        iwhere=(request.POST["iwhere"] if "iwhere" in request.POST else "" ) \
        )
    item.save()
    return HttpResponse(serializers.serialize('json', [
        item,
    ]))
Exemple #13
0
def create_item_in_bucket_list(id):
    auth_header = request.headers.get('Authorization')
    if auth_header:
        auth_token = auth_header.split(" ")[1]
    else:
        auth_token = ''
    if auth_token:
        decoded_token = User.decode_auth_token(auth_token)
        if not isinstance(decoded_token, str):
            user = User.query.filter_by(id=decoded_token).first()
            bucket_list = BucketList.query.filter_by(id=id,
                                                     user_id=user.id).first()
            if not bucket_list:
                response = jsonify({
                    'status': 'failed',
                    'message': 'Bucket list not found'
                })
                response.status_code = 404
                return response

            data = request.get_json()
            title = data['title']
            description = data['description']
            item = Item(title, description, bucket_list)
            db.session.add(item)
            db.session.commit()
            response = jsonify({
                'status': 'success',
                'message': SUCCESS,
                'data': {
                    'item': item.serialize()
                }
            })
            response.status_code = 201
            return response
        response = jsonify({'status': 'failed', 'message': decoded_token})
        return response
    else:
        response = jsonify({
            'status': 'failed',
            'message': 'Provide a valid auth token.'
        })
        response.status_code = 401
        return response
Exemple #14
0
def collection():
    if not request.json or not request.json.get('email').strip():
        return jsonify({'message': 'email is a required field'}), \
               HTTPStatus.BAD_REQUEST.value
    data = request.json
    if Item.query.filter_by(email=data['email']).first():
        return jsonify({'message': 'email already exists'}), \
               HTTPStatus.BAD_REQUEST.value
    token = request.headers.get('Authorization').replace('Bearer ', '')
    user = User.query.filter_by(token=token).first()
    item = Item(email=data['email'], name=data['name'], user_id=user.id)
    db.session.add(item)
    db.session.commit()
    return jsonify({'id': item.id}), HTTPStatus.CREATED.value
Exemple #15
0
def extract_items_and_bubbles(prepared_discussion: dict) -> Tuple[list, list]:
    """
    The prepared discussion is the result of the core functions from dbas.discussion.core. We need only few data for
    the API, so we extract the data in this function and append it to lists.

    :param prepared_discussion:
    :return:
    """
    items = [
        Item([premise['title'] for premise in item['premises']], item['url'])
        for item in prepared_discussion['items']['elements']
    ]
    bubbles = [
        Bubble(bubble)
        for bubble in prepared_discussion['discussion']['bubbles']
    ]
    return bubbles, items
Exemple #16
0
def insert_items(target, connection, **kwargs):
    # Creating list of dictionaries (items)
    items = [
        {
            "title": "Snickers box",
            "price": 12.99,
            "description":
            "Snickers is a brand name chocolate bar made by the American company Mars, Incorporated, consisting of nougat topped with caramel and peanuts that has been enrobed in milk chocolate.",
            "image_path": "https://imgur.com/Cf2LfAr.jpg",
        },
        {
            "title": "Bounty box",
            "price": 15.99,
            "description":
            "Bounty is a chocolate bar manufactured by Mars, Incorporated. It was introduced in 1951 in the United Kingdom and Canada. Bounty has a coconut filling enrobed with milk chocolate.",
            "image_path": "https://imgur.com/TfGb3t4.jpg",
        },
        {
            "title": "M&M's Chocolate Candies",
            "price": 3.99,
            "description":
            "M&M's are multi-colored button-shaped chocolates, each of which has the letter 'm' printed in lower case in white on one side, consisting of a candy shell surrounding a filling which varies depending upon the variety of M&M's.",
            "image_path": "https://imgur.com/8sMeZLn.jpg",
        },
        {
            "title": "Skittles fruits",
            "price": 4.99,
            "description":
            "Skittles consist of hard sugar shells imprinted with the letter 'S'. The interior consists mainly of sugar, corn syrup, and hydrogenated palm kernel oil along with fruit juice, citric acid, natural and artificial flavors.",
            "image_path": "https://imgur.com/m6jeGJ5.jpg",
        },
    ]

    # Adding items to Item table
    for item in items:
        instance = Item(item["title"], item["price"], item["description"],
                        item["image_path"])
        db.session.add(instance)

    db.session.commit()
Exemple #17
0
def save_objects(data):
    """ Сохранение данных в бд """

    login = data[0]
    name = data[1]
    total = int(data[2])
    quantity = int(data[3])
    spent_money = total * quantity
    date = data[4].replace('\n', '')

    # Сохранение Customer
    try:
        customer = Customer.objects.get(login=login)
    except Customer.DoesNotExist:
        Customer(login=login, spent_money=spent_money).save()
        customer = Customer.objects.get(login=login)

    # Сохранение Item
    try:
        item = Item.objects.get(name=name)
    except Item.DoesNotExist:
        Item(name=name, total=total).save()
        item = Item.objects.get(name=name)

    # Сохранение Даты покупки Customer-ом

    try:
        instance = PurchaseDate.objects.create(date=date)
        instance.customer.add(customer)

    except RuntimeWarning:
        pass
    # Сохранение ItemAndCustomer
    try:
        item_and_customer = ItemAndCustomer.objects.get(customer=customer,
                                                        item=item)
        item_and_customer.quantity += int(quantity)
        item_and_customer.save()
    except ItemAndCustomer.DoesNotExist:
        ItemAndCustomer(quantity=quantity, customer=customer, item=item).save()
Exemple #18
0
    def test_db(self, item, shop):
        """
        This method verifies the database functionalities of the api
        :return: None
        """
        fp = 'results1'
        test_price_obj = TestPrice()
        test_price_obj.test_search(item, shop)

        results = []
        with open(fp) as f:
            for line in f:
                result = eval(line)
                if not result['stars']:
                    result['stars'] = 0.0
                results.append(result)

        it = Item.query.filter_by(itemname=item).first()
        if it:
            it.results.delete()
            db.session.commit()
        else:
            it = Item(itemname=item)
            db.session.add(it)
            db.session.commit()

        for i in range(len(results)):
            result_db = Result(shop=shop.__name__,
                               search_item=it,
                               **results[i])
            db.session.add(result_db)

        db.session.commit()

        it.results.delete()
        it.query.delete()
        db.session.commit()
Exemple #19
0
    def test_db_basic(self):
        """
        This method verifies the database functionalities of the api
        :return: None
        """
        item = 'Redmi 5'
        fp = 'results'
        if not os.path.exists(fp):
            test_price_obj = TestPrice()
            test_price_obj.test_search_basic(item)

        results = []
        with open(fp) as f:
            for line in f:
                result = eval(line)
                if not result['stars']:
                    result['stars'] = 0.0
                results.append(result)

        it = Item.query.filter_by(itemname=item).first()
        if it:
            it.results.delete()
            db.session.commit()
        else:
            it = Item(itemname=item)
            db.session.add(it)
            db.session.commit()

        for i in range(len(results)):
            result_db = Result(shop='Snapdeal', search_item=it, **results[i])
            db.session.add(result_db)

        db.session.commit()

        it.results.delete()
        it.query.delete()
        db.session.commit()
Exemple #20
0
def post():
    jsonData = json.dumps(request.json)
    userData = json.loads(jsonData)
    json_dict = json.loads(request.form['params'])
    app.logger.debug(json_dict)
    app.logger.debug(request.files)
    item = Item(
        name=json_dict['name'],
        description=json_dict['description'],
        period=json_dict['period'],
        remaining_days=json_dict['remaining_days'],
        remaining_format_id=json_dict['remaining_format_id'],
        category_id=json_dict['category_id'],
        shipment=json_dict['shipment'],
        price=json_dict['price'],
        user_id=json_dict['user_id']
    )

    db.session.add(item)
    db.session.commit()
    db.session.refresh(item)
    post_record = item.__dict__
    post_record.pop('_sa_instance_state')

    try:
        if 'image' in request.files.keys():
            image = request.files['image']
            response = item_image_bucket.put_object(
                Body=io.BufferedReader(image).read(),
                Key=f's3/item-images/' + str(image.filename)
            )
            item_image =  ItemImage(app.config['ITEM_IMAGE_BASE'] + response.key, post_record['id'])
            item_image.postRecord()
    except NameError:
        pass

    return jsonify({'state': True})
Exemple #21
0
def results_new():
    form = SearchForm()
    item, num, nums = form.get_search_items()
    now_time = datetime.now().strftime("%Y-%m-%d %H:%M")
    search_results = simple_search(item, SHOPS, nums)
    it = Item.query.filter_by(itemname=item).first()
    if it:
        it.results.delete()
        it.itemtime = now_time
        db.session.commit()
    else:
        it = Item(itemname=item, itemtime=now_time)
        db.session.add(it)
        db.session.commit()

    for shop, num_i in zip(SHOPS, nums):
        for i in range(num_i):
            if not search_results.get(shop)[i]['stars']:
                search_results.get(shop)[i]['stars'] = 0.0
            result_db = Result(shop=shop, search_item=it, **search_results.get(shop)[i])
            db.session.add(result_db)

    db.session.commit()
    return redirect(url_for('results'), code=307)
Exemple #22
0
 def test_invalid_duplicates(self):
     list_ = TodoList.objects.create()
     Item.objects.create(todo_list=list_, title="something")
     with self.assertRaises(ValidationError):
         item = Item(todo_list=list_, title="something")
         item.full_clean()
Exemple #23
0
def addProduct(request: HttpRequest):
    code = request.POST['code']
    name = request.POST['name']
    price = request.POST['price']
    warning_quantity = request.POST['warning_quantity']
    is_chemical = request.POST.get('is_chemical', False)
    pack_size = request.POST['pack_size']
    for_sale = request.POST.get('for_sale', False)

    valid = True
    #check to see for conflicts
    for itm in Item.objects.all():
        if itm.code == code:
            valid = False
    if valid:
        item = Item()
        item.code = code
        item.name = name
        item.price = price
        item.quantity = 0
        item.warning_quantity = warning_quantity
        item.is_chemical = is_chemical
        item.pack_size = int(pack_size)
        item.for_sale = for_sale

        item.save()
        messages.success(request, 'Product: '+name+' added successfully.')
        return HttpResponseRedirect('products')
    else:
        messages.error(request, 'Product Code: '+code+' already exists.')
        return HttpResponseRedirect('products')
Exemple #24
0
def insert_items(target, connection, **kwargs):
    # Creating list of dictionaries (items)
    items = [
        {
            "title": "Snickers box",
            "price": 12.99,
            "description":
            "Snickers is a brand name chocolate bar made by the American company Mars, Incorporated, consisting of nougat topped with caramel and peanuts that has been enrobed in milk chocolate.",
            "image_path": "https://imgur.com/Cf2LfAr.jpg",
        },
        {
            "title": "Bounty box",
            "price": 15.99,
            "description":
            "Bounty is a chocolate bar manufactured by Mars, Incorporated. It was introduced in 1951 in the United Kingdom and Canada. Bounty has a coconut filling enrobed with milk chocolate.",
            "image_path": "https://imgur.com/TfGb3t4.jpg",
        },
        {
            "title": "M&M's Chocolate Candies",
            "price": 3.99,
            "description":
            "M&M's are multi-colored button-shaped chocolates, each of which has the letter 'm' printed in lower case in white on one side, consisting of a candy shell surrounding a filling which varies depending upon the variety of M&M's.",
            "image_path": "https://imgur.com/8sMeZLn.jpg",
        },
        {
            "title": "Skittles Fruits",
            "price": 4.99,
            "description":
            "Skittles consist of hard sugar shells imprinted with the letter 'S'. The interior consists mainly of sugar, corn syrup, and hydrogenated palm kernel oil along with fruit juice, citric acid, natural and artificial flavors.",
            "image_path": "https://imgur.com/m6jeGJ5.jpg",
        },
        {
            "title": "Skittles Crazy Sours",
            "price": 4.99,
            "description":
            "Skittles consist of hard sugar shells imprinted with the letter 'S'. They're a bit different in that they don't look different, but have a different set of flavors from the Fruits set but no tangy coating.",
            "image_path": "https://i.imgur.com/RFKY2gT.png",
        },
        {
            "title": "Skittles Wild Berry",
            "price": 4.99,
            "description":
            "Skittles consist of hard sugar shells imprinted with the letter 'S'. Bite-size, colorful chewy candies. Taste the Rainbow—Wild Berry Skittles includes berry punch, strawberry, melon berry, wild cherry, and raspberry flavors.",
            "image_path": "https://i.imgur.com/f59lUj2.jpg",
        },
        {
            "title": "Skittles Brightside",
            "price": 4.99,
            "description":
            "Skittles consist of hard sugar shells imprinted with the letter 'S'.  Candy includes kiwi banana, watermelon, paradise punch, pink lemonade, and tangerine flavors",
            "image_path": "https://i.imgur.com/RWfUoQW.jpg",
        },
        {
            "title": "M&M's Minis",
            "price": 3.99,
            "description":
            "M&M's are multi-colored button-shaped chocolates, each of which has the letter 'm' printed in lower case in white on one side, consisting of a candy shell surrounding a filling which varies depending upon the variety of M&M's.",
            "image_path": "https://i.imgur.com/4ITjs8j.jpg",
        },
        {
            "title": "Twix Box",
            "price": 12.99,
            "description":
            "Twix is a chocolate bar made by Mars, Inc., consisting of a biscuit applied with other confectionery toppings and coatings (most frequently caramel and milk chocolate). Twix are packaged with two or four bars in a wrapper. Miniature and other variations of Twix bars are also available.",
            "image_path": "https://i.imgur.com/0HsdSmD.jpg",
        },
        {
            "title": "Prince Polo XXL Classic Box ",
            "price": 7.99,
            "description":
            "Prince Polo is a Polish chocolate bar It is a chocolate-covered wafer, with four layers of wafer joined by three layers of chocolate-flavored filling; Packed in a metallic gold-colored wrapper.",
            "image_path": "https://i.imgur.com/qQKfu8u.jpg",
        },
        {
            "title": "Prince Polo XXL Milk Box",
            "price": 7.99,
            "description":
            "Prince Polo is a Polish chocolate bar It is a chocolate-covered wafer, with four layers of wafer joined by three layers of chocolate-flavored filling; Packed in a metallic gold-colored wrapper.",
            "image_path": "https://i.imgur.com/Rk8kDbs.jpg",
        },
        {
            "title": "Prince Polo XXL Nuts Box",
            "price": 7.99,
            "description":
            "Prince Polo is a Polish chocolate bar It is a chocolate-covered wafer, with four layers of wafer joined by three layers of chocolate-flavored filling; Packed in a metallic gold-colored wrapper.",
            "image_path": "https://i.imgur.com/nvYVnXw.jpg",
        },
        {
            "title": "Milka Alpine Milk ",
            "price": 29.99,
            "description":
            "Milka Alpine Milk Chocolate is has the best quality of Alpine Milk added to give it that rich, creamy flavor. Alpine Milk is the delicious, smooth chocolate delight from 100% Alpine Milk, the classic for all chocolate fans.",
            "image_path": "https://i.imgur.com/J6mNhSD.jpg",
        },
        {
            "title": "Milka OREO bars",
            "price": 21.99,
            "description": "Delicious Milka Alpine Milk Chocolate with Oreo",
            "image_path": "https://i.imgur.com/3MYhogx.jpg",
        },
        {
            "title": "Present FISH Box",
            "price": 37.99,
            "description": "Box includes different chewing worms",
            "image_path": "https://i.imgur.com/RZBNQvR.jpg",
        },
        {
            "title": "Birthday Box ",
            "price": 50.99,
            "description": "Box for sweet tooth, why celebrate their birthday",
            "image_path": "https://i.imgur.com/bOPECW9.jpg",
        },
    ]

    # Adding items to Item table
    for item in items:
        instance = Item(item["title"], item["price"], item["description"],
                        item["image_path"])
        db.session.add(instance)

    db.session.commit()
Exemple #25
0
 def test_default_body(self):
     item = Item()
     self.assertEqual(item.body, "")
Exemple #26
0
from api.models import Item
import csv

file = open('API_Data_v6.csv')

temp = csv.reader(file)

temp = [i for i in temp]

objects = [
    Item(
        year=int(item[0]),
        institute_type=item[1],
        round_no=int(item[2]),
        quota=item[3],
        pool=item[4],
        institute_full=item[5],
        institute_short=item[6],
        institute_location=item[7],
        program_name=item[8],
        program_duration=item[9],
        degree_full=item[10],
        degree_short=item[11],
        category=item[12],
        opening_rank=float(item[13]),
        closing_rank=float(item[14]),
        is_preparatory=int(item[15])
    ) for item in temp[1:]
]

Item.objects.bulk_create(objects)
Exemple #27
0
def get():
    id = request.args.get('id');
    product = Item.getProductById(id);
    return jsonify(product.__dict__)
Exemple #28
0
 def test_string_repr(self):
     item = Item(title="some text")
     self.assertEqual(str(item), "some text")
Exemple #29
0
 def setUp(self) -> None:
     self.amount = 12000.0
     self.item = Item(amount=self.amount)
     self.item.save()
Exemple #30
0
class APIBaseTestCase(APITestCase, URLPatternsTestCase):
    """Test the Routable API

    Could be improved to be a generic test for all APIs
    """
    urlpatterns = [
        path('api/', include('api.urls')),
    ]

    def setUp(self) -> None:
        self.amount = 12000.0
        self.item = Item(amount=self.amount)
        self.item.save()

    def new_transaction(self, status=Transaction.STATUS_PROCESSING, location=Transaction.LOCATION_ORIGIN):
        """
        Create and save a new transaction with the class's item instance.
        :param status: The Desired status
        :param location: The Desired location
        :return: The new instance of Transaction
        """
        trans = Transaction(
            item=self.item,
            status=status,
            location=location
        )
        trans.save()
        return trans

    def get_latest_transaction(self):
        """
        Retrieves the latest transaction for the item.
        :return: Transaction
        """
        return Transaction.objects.select_related().filter(
            item__id=self.item.id).order_by('-updated_at')[0]

    def assertTransaction(self, transaction, status, location, msg=None):
        """
        Helper assertion method to check a transaction's status and location
        :param transaction: The transaction
        :param status: Expected status
        :param location: Expected location
        :param msg: Any message you would like to add
        :return: None
        """
        if transaction.status != status or transaction.location != location:
            msg = self._formatMessage(msg, 'Transaction in wrong status or location: {} {}, expected: {} {}'.format(
                transaction.status, transaction.location, status, location
            ))
            raise self.failureException(msg)

    def call_item_endpoint(self, name, response_code_expected=rest_status.HTTP_200_OK):
        """
        Call an endpoint by it's name, then assert the expected response code.
        :param name: Name of the endpoint
        :param response_code_expected: The expected response code
        :return: The response data
        """
        url = reverse(name, args=[self.item.id])
        response = self.client.post(url, format='json')
        self.assertEqual(response.status_code, response_code_expected)
        return response.data

    def call_move_endpoint(self, expected_state=Item.STATE_PROCESSING):
        """
        Calls the move endpoint and than asserts that the state is what was expected
        :param expected_state: The expected state of the Item
        :return: The response data
        """
        data = self.call_item_endpoint('item-move')
        self.assertEqual(float(data['amount']), self.item.amount)
        self.assertEqual(data['state'], expected_state)
        return data

    def call_error_endpoint(self, expected_state=Item.STATE_ERROR):
        """
        Calls the error endpoint and than asserts that the state is what was expected
        :param expected_state: The expected state of the Item
        :return: The response data
        """
        data = self.call_item_endpoint('item-error')
        self.assertEqual(float(data['amount']), self.item.amount)
        self.assertEqual(data['state'], expected_state)
        return data

    def call_fix_endpoint(self, expected_state=Item.STATE_CORRECTING):
        """
        Calls the fix endpoint and than asserts that the state is what was expected
        :param expected_state: The expected state of the Item
        :return: The response data
        """
        data = self.call_item_endpoint('item-fix')
        self.assertEqual(float(data['amount']), self.item.amount)
        self.assertEqual(data['state'], expected_state)
        return data
                    room.save()
                else:
                    ran = random.randint(0, 14)
                    room = gen_room(ranInt=ran, roomId=idCount)
                    idCount += 1
                    self.grid[x][y] = room
                    room.positionx = x
                    room.positiony = y
                    room.save()


w = World()
width = 20
height = 20
w.generate_rooms(width, height)
item = Item(1, "Torch", "This can light your path in the dark",
            "Prehistoric Cave", 1)
item.save()
item = Item(2, "Bag of Jerky", "You can smell the beef", "Prehistoric Cave", 2)
item.save()
item = Item(3, "Meat Club", "Part snack, part weapon", "Prehistoric Cave", 3)
item.save()
item = Item(4, "Animal Skin Cloak", "A small amount of protection",
            "Prehistoric Cave", 4)
item.save()
item = Item(5, "Dino-Tooth Saber", "Wickedly sharp", "Prehistoric Cave", 5)
item.save()
item = Item(
    6, "Magic Wand",
    "A smooth stick with some strange engravings on the side. It feels like it has some kind of hidden power.",
    "Medieval Wizards Tower", 1)
item.save()