def test_private_file_download(self):
        # create new private file
        new_private_file = frappe.get_doc({
            'doctype':
            self.test_doctype,
            'file_name':
            self.file_name,
            'content':
            base64.b64encode(self.test_content.encode('utf-8')),
            'is_private':
            1,
        })
        new_private_file.insert()

        # access the created file
        private_file_link = get_site_url(
            frappe.local.site) + new_private_file.file_url

        try:
            request = requests.post(private_file_link, headers=self.header)
            last_doc = frappe.get_last_doc('Access Log')

            if request.ok:
                # check for the access log of downloaded file
                self.assertEqual(new_private_file.doctype,
                                 last_doc.export_from)
                self.assertEqual(new_private_file.name,
                                 last_doc.reference_document)

        except requests.ConnectionError:
            pass

        # cleanup
        new_private_file.delete()
Example #2
0
	def send_now(self):
		self.validate_attachment()
		media = self.get_attachment()
		self.db_set('status', 'In Progress')
		if media:
			media = get_site_url(frappe.local.site) + media.file_url

		WhatsAppMessage.send_whatsapp_message(
			receiver_list = self.get_whatsapp_contact(),
			message = self.message,
			doctype = self.doctype,
			docname = self.name,
			media = media
		)

		self.db_set('status', 'Completed')
Example #3
0
	def get_message_dict(self):
		args = {
			'from_': self.from_,
			'to': self.to,
			'body': self.message,
			'status_callback': '{}/api/method/twilio_integration.twilio_integration.api.whatsapp_message_status_callback'.format(get_site_url(frappe.local.site))
		}
		if self.media_link:
			args['media_url'] = [self.media_link]

		return args
Example #4
0
	def test_api(self):
		response = requests.post(get_site_url(frappe.local.site) + "/api/method/test_server_script")
		self.assertEqual(response.status_code, 200)
		self.assertEqual("hello", response.json()["message"])
Example #5
0
class TestResourceAPI(unittest.TestCase):
    SITE_URL = get_site_url(frappe.local.site)
    RESOURCE_URL = f"{SITE_URL}/api/resource"
    DOCTYPE = "ToDo"
    GENERATED_DOCUMENTS = []

    @classmethod
    @maintain_state
    def setUpClass(self):
        for _ in range(10):
            doc = frappe.get_doc({
                "doctype": "ToDo",
                "description": frappe.mock("paragraph")
            }).insert()
            self.GENERATED_DOCUMENTS.append(doc.name)

    @classmethod
    @maintain_state
    def tearDownClass(self):
        for name in self.GENERATED_DOCUMENTS:
            frappe.delete_doc_if_exists(self.DOCTYPE, name)

    @property
    def sid(self):
        if not getattr(self, "_sid", None):
            self._sid = requests.post(
                f"{self.SITE_URL}/api/method/login",
                data={
                    "usr": "******",
                    "pwd": frappe.conf.admin_password or "admin",
                },
            ).cookies.get("sid")

        return self._sid

    def get(self, path, params=""):
        return requests.get(
            f"{self.RESOURCE_URL}/{path}?sid={self.sid}{params}")

    def post(self, path, data):
        return requests.post(f"{self.RESOURCE_URL}/{path}?sid={self.sid}",
                             data=frappe.as_json(data))

    def put(self, path, data):
        return requests.put(f"{self.RESOURCE_URL}/{path}?sid={self.sid}",
                            data=frappe.as_json(data))

    def delete(self, path):
        return requests.delete(f"{self.RESOURCE_URL}/{path}?sid={self.sid}")

    def test_unauthorized_call(self):
        # test 1: fetch documents without auth
        response = requests.get(f"{self.RESOURCE_URL}/{self.DOCTYPE}")
        self.assertEqual(response.status_code, 403)

    def test_get_list(self):
        # test 2: fetch documents without params
        response = self.get(self.DOCTYPE)
        self.assertEqual(response.status_code, 200)
        self.assertIsInstance(response.json(), dict)
        self.assertIn("data", response.json())

    def test_get_list_limit(self):
        # test 3: fetch data with limit
        response = self.get(self.DOCTYPE, "&limit=2")
        self.assertEqual(response.status_code, 200)
        self.assertEqual(len(response.json()["data"]), 2)

    def test_get_list_dict(self):
        # test 4: fetch response as (not) dict
        response = self.get(self.DOCTYPE, "&as_dict=True")
        json = frappe._dict(response.json())
        self.assertEqual(response.status_code, 200)
        self.assertIsInstance(json.data, list)
        self.assertIsInstance(json.data[0], dict)

        response = self.get(self.DOCTYPE, "&as_dict=False")
        json = frappe._dict(response.json())
        self.assertEqual(response.status_code, 200)
        self.assertIsInstance(json.data, list)
        self.assertIsInstance(json.data[0], list)

    def test_get_list_debug(self):
        # test 5: fetch response with debug
        response = self.get(self.DOCTYPE, "&debug=true")
        self.assertEqual(response.status_code, 200)
        self.assertIn("exc", response.json())
        self.assertIsInstance(response.json()["exc"], str)
        self.assertIsInstance(eval(response.json()["exc"]), list)

    def test_get_list_fields(self):
        # test 6: fetch response with fields
        response = self.get(self.DOCTYPE, r'&fields=["description"]')
        self.assertEqual(response.status_code, 200)
        json = frappe._dict(response.json())
        self.assertIn("description", json.data[0])

    def test_create_document(self):
        # test 7: POST method on /api/resource to create doc
        data = {"description": frappe.mock("paragraph")}
        response = self.post(self.DOCTYPE, data)
        self.assertEqual(response.status_code, 200)
        docname = response.json()["data"]["name"]
        self.assertIsInstance(docname, str)
        self.GENERATED_DOCUMENTS.append(docname)

    def test_update_document(self):
        # test 8: PUT method on /api/resource to update doc
        generated_desc = frappe.mock("paragraph")
        data = {"description": generated_desc}
        random_doc = choice(self.GENERATED_DOCUMENTS)
        desc_before_update = frappe.db.get_value(self.DOCTYPE, random_doc,
                                                 "description")

        response = self.put(f"{self.DOCTYPE}/{random_doc}", data=data)
        self.assertEqual(response.status_code, 200)
        self.assertNotEqual(response.json()["data"]["description"],
                            desc_before_update)
        self.assertEqual(response.json()["data"]["description"],
                         generated_desc)

    def test_delete_document(self):
        # test 9: DELETE method on /api/resource
        doc_to_delete = choice(self.GENERATED_DOCUMENTS)
        response = self.delete(f"{self.DOCTYPE}/{doc_to_delete}")
        self.assertEqual(response.status_code, 202)
        self.assertDictEqual(response.json(), {"message": "ok"})
        self.GENERATED_DOCUMENTS.remove(doc_to_delete)

        non_existent_doc = frappe.generate_hash(length=12)
        response = self.delete(f"{self.DOCTYPE}/{non_existent_doc}")
        self.assertEqual(response.status_code, 404)
        self.assertDictEqual(response.json(), {})