blob: 11eb6afc1fae717f2de5e2f5ee89b8cb5eb629a2 [file] [log] [blame]
Ankush Menat76dd6e92021-05-23 16:19:48 +05301# Copyright (c) 2021, Frappe Technologies Pvt. Ltd. and Contributors
Rushabh Mehta982be9f2017-01-17 17:57:19 +05302# License: GNU General Public License v3. See license.txt
3
Ankush Menat76dd6e92021-05-23 16:19:48 +05304import copy
5from contextlib import contextmanager
Rushabh Mehta982be9f2017-01-17 17:57:19 +05306
7import frappe
8
9def create_test_contact_and_address():
Rushabh Mehtaa0c41b72017-01-18 14:14:20 +053010 frappe.db.sql('delete from tabContact')
Nabin Hait1aa8c2e2020-03-26 13:15:31 +053011 frappe.db.sql('delete from `tabContact Email`')
12 frappe.db.sql('delete from `tabContact Phone`')
Rushabh Mehtaa0c41b72017-01-18 14:14:20 +053013 frappe.db.sql('delete from tabAddress')
14 frappe.db.sql('delete from `tabDynamic Link`')
Rushabh Mehta982be9f2017-01-17 17:57:19 +053015
Himanshu25ab1e42019-09-30 10:08:15 +053016 frappe.get_doc({
17 "doctype": "Address",
18 "address_title": "_Test Address for Customer",
19 "address_type": "Office",
20 "address_line1": "Station Road",
21 "city": "_Test City",
22 "state": "Test State",
23 "country": "India",
24 "links": [
25 {
26 "link_doctype": "Customer",
27 "link_name": "_Test Customer"
28 }
29 ]
30 }).insert()
Rushabh Mehtaa0c41b72017-01-18 14:14:20 +053031
Himanshu25ab1e42019-09-30 10:08:15 +053032 contact = frappe.get_doc({
33 "doctype": 'Contact',
34 "first_name": "_Test Contact for _Test Customer",
35 "links": [
36 {
37 "link_doctype": "Customer",
38 "link_name": "_Test Customer"
39 }
40 ]
41 })
42 contact.add_email("test_contact_customer@example.com", is_primary=True)
43 contact.add_phone("+91 0000000000", is_primary_phone=True)
44 contact.insert()
Ankush Menat76dd6e92021-05-23 16:19:48 +053045
46
47@contextmanager
48def change_settings(doctype, settings_dict):
49 """ A context manager to ensure that settings are changed before running
50 function and restored after running it regardless of exceptions occured.
51 This is useful in tests where you want to make changes in a function but
52 don't retain those changes.
53 import and use as decorator to cover full function or using `with` statement.
54
55 example:
56 @change_settings("Stock Settings", {"item_naming_by": "Naming Series"})
57 def test_case(self):
58 ...
59 """
60
61 try:
62 settings = frappe.get_doc(doctype)
63 # remember setting
64 previous_settings = copy.deepcopy(settings_dict)
65 for key in previous_settings:
66 previous_settings[key] = getattr(settings, key)
67
68 # change setting
69 for key, value in settings_dict.items():
70 setattr(settings, key, value)
71 settings.save()
72 yield # yield control to calling function
73
74 finally:
75 # restore settings
76 settings = frappe.get_doc(doctype)
77 for key, value in previous_settings.items():
78 setattr(settings, key, value)
79 settings.save()