You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

78 lines
2.3 KiB

  1. # Copyright 2020 Coop IT Easy SCRL fs
  2. # Robin Keunen <robin@coopiteasy.be>
  3. # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
  4. import json
  5. import requests
  6. from lxml import html
  7. import odoo
  8. from odoo.addons.base_rest.tests.common import BaseRestCase
  9. HOST = "127.0.0.1"
  10. PORT = odoo.tools.config["http_port"]
  11. class BaseEMCRestCase(BaseRestCase):
  12. @classmethod
  13. def setUpClass(cls, *args, **kwargs):
  14. super().setUpClass(*args, **kwargs)
  15. cls.AuthApiKey = cls.env["auth.api.key"]
  16. cls.api_key_test = cls.env.ref(
  17. "easy_my_coop_api.auth_api_key_manager_emc_demo"
  18. )
  19. def _add_api_key(self, headers):
  20. key_dict = {"API-KEY": self.api_key_test.key}
  21. if headers:
  22. headers.update(key_dict)
  23. else:
  24. headers = key_dict
  25. return headers
  26. def setUp(self):
  27. super().setUp()
  28. self.session = requests.Session()
  29. def http_get(self, url, headers=None):
  30. headers = self._add_api_key(headers)
  31. if url.startswith("/"):
  32. url = "http://{}:{}{}".format(HOST, PORT, url)
  33. return self.session.get(url, headers=headers)
  34. def http_get_content(self, route, headers=None):
  35. response = self.http_get(route, headers=headers)
  36. self.assertEquals(response.status_code, 200)
  37. content = response.content.decode("utf-8")
  38. return json.loads(content)
  39. def http_post(self, url, data, headers=None):
  40. headers = self._add_api_key(headers)
  41. if url.startswith("/"):
  42. url = "http://{}:{}{}".format(HOST, PORT, url)
  43. return self.session.post(url, json=data, headers=headers)
  44. @staticmethod
  45. def html_doc(response):
  46. """Get an HTML LXML document."""
  47. return html.fromstring(response.content)
  48. def login(self, login, password):
  49. url = "/web/login"
  50. response = self.http_get(url)
  51. self.assertEquals(response.status_code, 200)
  52. doc = self.html_doc(response)
  53. token = doc.xpath("//input[@name='csrf_token']")[0].get("value")
  54. response = self.http_post(
  55. url=url,
  56. data={"login": login, "password": password, "csrf_token": token},
  57. )
  58. self.assertEquals(response.status_code, 200)
  59. return response