Пример #1
0
    def test_will_delete_one_w_document_duplicates(self):
        """
        Test: Delete one document with document (duplicates exist).
        """

        api.insert_documents(doc3.copy())
        api.insert_documents(doc3.copy())

        original = next(api.read_document(doc3.copy()))
        result = api.delete_document(doc3.copy())

        self.assertDictEqual(original, result)

        # Ensure that there's still at least one document left:
        other = next(api.read_document(doc3.copy()))

        self.assertNotEqual(result["_id"], other["_id"])

        # Remove the ids, it should be the only key different between the two.
        result.pop("_id")
        other.pop("_id")

        # Then ensure that both documents are equal to each other. This means
        # that two was found, but only one remains even though both documents
        # are identical.
        self.assertDictEqual(result, other)
Пример #2
0
    def test_update_volume(self):
        """
        Test: Per the rubric, this will just update one ticker's volume.
        """
        update = {"Volume": 1000}

        doc = {"Ticker": doc2["Ticker"], "status": "test"}

        cursor = api.read_document(doc)
        previous = next(cursor)
        cursor.close()

        result = api.update_document(doc, update)

        cursor = api.read_document(doc)
        other = next(cursor)
        cursor.close()

        # Ensure that we have the same document:
        self.assertEqual(previous["_id"], other["_id"])
        self.assertNotEqual(previous["Volume"], other["Volume"])

        previous.pop("Volume")
        other.pop("Volume")

        self.assertDictEqual(previous, other)
Пример #3
0
    def reset_db(self):
        """
        Takedown: Remove all test documents from prod db.
        """
        docs = api.read_document("status", "test")
        for doc in docs:
            api.delete_document(doc)

        error = { "Error": "No documents found!", "alive": False }
        result = next(api.read_document("status", "test"))

        self.assertEqual(error, result, "Test documents still exist!")
Пример #4
0
def read(symbol = ""):
    """
    Reads a document from the collection.

    @params: Query string from URL.

    @return: JSON of first found document or error.

    @h_resp: 200 OK, 404 Not Found
    """
    status = 200
    try:
        # read_document sends the whole cursor, let's just retrieve the first
        # document in the queue for now.
        data = next(api.read_document({ "Ticker": symbol }))

        # read_document returns a hardcoded error if a document isn't found,
        # so I'll look for it here:
        if "Error" in data:
            status = 404


        res = bottle.HTTPResponse(status = status, body = get_json(data))
        return set_headers(res)
    
    except Exception as e:
        print_error(e)
Пример #5
0
def stock_report():
    """
    Select and present specific stock summary information.
    
    @params: JSON containing list.
    
    @return: Array containing all stocks found.
    
    @h_resp: 200 OK, 404 Not Found
    """
    status = 200

    try:
        # We're sure to get a list from the JSON request, which will be an
        # array of all the stocks that we need to look through.
        req = request.json["list"]
        
        data = {}
        stocks = []

        for stock in req:
            # There might be multiple responses:
            for doc in api.read_document({ "Ticker": stock }):
                # Let's append every single doc in the cursor.
                stocks.append(doc)
            
        data = { "Stocks": stocks }
    
    except Exception as e:
        status = 404
        data = { "Error: ": e }
    
    res = bottle.HTTPResponse(status = status, body = get_json(data))
    return set_headers(res)
Пример #6
0
 def test_will_find_w_whole_document(self):
     """
     Test: Find ONE document using whole dictionary.
     """
     original = doc1.copy()
     for doc in api.read_document(doc1):
         del doc["_id"]
         self.assertDictEqual(doc, doc1)
Пример #7
0
 def test_will_find_w_partial_document(self):
     """
     Test: Find ONE document using partial dictionary.
     """
     kv = {"Ticker": doc1["Ticker"], "status": "test"}
     for doc in api.read_document(kv):
         del doc["_id"]
         self.assertDictEqual(doc, doc1)
Пример #8
0
    def test_will_find_many_w_key_value(self):
        """
        Test: Find MANY documents using k, v.
        """
        api.insert_documents(doc1.copy())

        docs = api.read_document("Ticker", doc1["Ticker"])
        self.assertGreater(docs.explain()["n"],
                           1)  # There should be two results
Пример #9
0
    def test_will_delete_one_w_document(self):
        """
        Test: Delete one document with document.
        """

        # This test may not run last, not sure. Regardless, lets make sure
        # there's something to delete.
        # Update: Using a test runner, so it should run last. Regardless, I'm
        #         going to keep this insertion code in here.
        api.insert_documents(doc3.copy())

        original = next(api.read_document(doc3.copy()))
        result = api.delete_document(doc3.copy())

        self.assertDictEqual(original, result)

        error = next(api.read_document(doc3.copy()))

        self.assertEqual(error["Error"], "No documents found!")
Пример #10
0
    def test_will_not_find_w_key_value(self):
        """
        Test: Won't find a document using k, v.
        """
        kv = {"no_key": "no_value"}
        doc = next(api.read_document(list(kv.keys())[0], list(kv.values())[0]))

        self.assertNotIn("no_key", doc)
        self.assertIn("Error", doc)
        self.assertEqual(doc["Error"], "No documents found!")
Пример #11
0
    def test_will_not_find_w_document(self):
        """
        Test: Won't find a document using document.
        """
        kv = {"no_key": "no_value"}
        error = {"Error: No documents found!": -1}
        doc = next(api.read_document(kv))

        self.assertNotIn("no_key", doc)
        self.assertIn("Error", doc)
        self.assertEqual(doc["Error"], "No documents found!")
Пример #12
0
    def test_will_find_w_key_value(self):
        """
        Test: Find ONE value using k, v.
        """
        kv = {"Ticker": doc1["Ticker"]}
        docs = api.read_document(list(kv.keys())[0], list(kv.values())[0])

        for doc in docs:
            if "status" in doc:
                doc.pop("_id")
                self.assertDictEqual(doc, doc1)
Пример #13
0
    def test_will_delete_one_w_key_value(self):
        """
        Test: Delete one document with k, v.
        """
        api.insert_documents(doc3.copy())

        doc = {"Ticker": doc3["Ticker"], "status": "test"}

        original = next(api.read_document(doc3.copy()))
        result = api.delete_document(doc)

        self.assertDictEqual(original, result)
Пример #14
0
    def test_insert_exact_duplicate(self):
        """
        Test: Insert exact same document.
        """
        # Get the first instance of doc1 in db:
        doc = next(api.read_document(doc1.copy()))
        # Insert the document we just got.
        result = api.insert_documents(doc)

        # Not sure what the error is going to be, but I know for sure that
        # there's going to be one relating to duplicate ids.
        self.assertTrue("Error" in result)
Пример #15
0
    def test_update_one_document(self):
        """
        Test: Update document found.
        """
        update = {
            "Change from Open": 1.0055,
            "Performance (YTD)": 1.1809,
            "Performance (Week)": -1.0134,
            "Performance (Quarter)": 1.061
        }

        doc = {"Ticker": doc2["Ticker"], "status": "test"}

        cursor = api.read_document(doc)
        previous = next(cursor)
        cursor.close()

        result = api.update_document(doc, update)

        cursor = api.read_document(doc)
        other = next(cursor)
        cursor.close()

        # Ensure that we have the same document:
        self.assertEqual(previous["_id"], other["_id"])

        # This for-loop will test the keys from testAndPop to ensure
        # inequality, then it will pop the keys from both of the dictionaries.
        for k in update.keys():
            self.assertNotEqual(previous[k], other[k])
            # If the above passes, move to the next line.
            previous.pop(k, None)
            other.pop(k, None)

        # previous.pop("_id")
        # other.pop("_id")

        self.assertDictEqual(previous, other)
Пример #16
0
    def test_will_find_many_w_document(self):
        """
        Test: Find MANY documents with document.
        """
        original = doc1.copy()
        docs = api.read_document(original)

        if docs.explain()["n"] == 1:
            self.assertTrue(False, "Didn't find 2 documents.")

        for doc in docs:
            if "status" in doc:
                doc.pop("_id")
                self.assertDictEqual(doc, doc1)
Пример #17
0
    def test_update_none_found_upsert(self):
        """
        Test: Update will upsert a document.
        """
        original = next(api.read_document("none", "exists"))

        update = {
            "Change from Open": 1.0055,
            "Performance (YTD)": 1.1809,
            "Performance (Week)": -1.0134,
            "Performance (Quarter)": 1.061,
            "status": "test"
        }

        result = api.update_document("none", "exists", update)

        self.assertTrue(result["upserted"])
Пример #18
0
    def test_update_with_error(self):
        """
        Test: Update will fail with assertion error.
        """
        original = next(api.read_document("none", "exists"))

        # This was giving me issues initially, so it should pop an error from
        # MongoDB.
        update = {"$date": 1381264200000}

        result = api.update_document("none", "exists", update)

        self.assertIn("Error", result)
        # This is the error I was getting when first building out the API. It
        # should ensure that no document can be inserted with $date as a key.
        self.assertEqual(
            result["Error"],
            "The dollar ($) prefixed field '$date' in '$date' is not valid for storage."
        )
Пример #19
0
def portfolio(company = ""):
    """
    Retrieves all stocks under one company
    
    @params: Company from route.
    
    @return: JSON payload with a list of stocks.
    
    @h_resp: 200 OK, 404 Not Found
    """
    status = 200
    try:
        res = { "Company": company }
        
        data = api.read_document(res)

    except Exception as e:
        print_error(e)
        
    return bottle.HTTPResponse(status = status, body = get_json(res))
Пример #20
0
    def test_insert_duplicate_document(self):
        """
        Test: Insert a duplicate document.
        """

        self.assertTrue(api.insert_documents(doc1.copy()))

        docs = api.read_document({"Ticker": "AA", "status": "test"})

        first = next(docs)
        if (docs.alive):
            other = next(docs)
        else:
            self.assertTrue(False, "Duplicate document doesn't exist.")

        self.assertNotEqual(first["_id"], other["_id"])

        first.pop("_id")
        other.pop("_id")

        # Ensure that both dictionaries are the same without ids:
        self.assertDictEqual(first, other)
Пример #21
0
def get_all_stocks():
    """
    OPTIMIZATION:
    Get all stocks within the db, return as large JSON array. An aside, this
    will probably become a huge return, so it may be better to paginate this.
    
    @params: None

    @return: Array of all stocks in collection.
    """
    status = 200
    try:
        # We're sure to get a list from the JSON request, which will be an
        # array of all the stocks that we need to look through.
        data = {}
        stocks = []
        for doc in api.read_document({}):
            stocks.append(doc)

        data = { "Stocks": stocks }
        
    except Exception as e:
        status = 404
        data = { "Error: ": e }

    # So, this would work if I was just sending a JSON response. The problem is
    # I want to send an HTTPResponse. I can't find a better way to do this, so
    # I'll probably wrap setting headers in some utility function.

    # NOTE: Using @hook('after_request) doesn't seem to work unless, as
    #       mentioned above, I'm sending just a straight JSON response back.

    # return get_json(data)
    
    res = bottle.HTTPResponse(status = status, body = get_json(data))
    return set_headers(res)