blob: 2156bd51a4a9362e2c4ee44d1d0f8d128cec1252 [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
Chillar Anand915b3432021-09-02 16:44:59 +05309
Rushabh Mehta982be9f2017-01-17 17:57:19 +053010def create_test_contact_and_address():
Rushabh Mehtaa0c41b72017-01-18 14:14:20 +053011 frappe.db.sql('delete from tabContact')
Nabin Hait1aa8c2e2020-03-26 13:15:31 +053012 frappe.db.sql('delete from `tabContact Email`')
13 frappe.db.sql('delete from `tabContact Phone`')
Rushabh Mehtaa0c41b72017-01-18 14:14:20 +053014 frappe.db.sql('delete from tabAddress')
15 frappe.db.sql('delete from `tabDynamic Link`')
Rushabh Mehta982be9f2017-01-17 17:57:19 +053016
Himanshu25ab1e42019-09-30 10:08:15 +053017 frappe.get_doc({
18 "doctype": "Address",
19 "address_title": "_Test Address for Customer",
20 "address_type": "Office",
21 "address_line1": "Station Road",
22 "city": "_Test City",
23 "state": "Test State",
24 "country": "India",
25 "links": [
26 {
27 "link_doctype": "Customer",
28 "link_name": "_Test Customer"
29 }
30 ]
31 }).insert()
Rushabh Mehtaa0c41b72017-01-18 14:14:20 +053032
Himanshu25ab1e42019-09-30 10:08:15 +053033 contact = frappe.get_doc({
34 "doctype": 'Contact',
35 "first_name": "_Test Contact for _Test Customer",
36 "links": [
37 {
38 "link_doctype": "Customer",
39 "link_name": "_Test Customer"
40 }
41 ]
42 })
43 contact.add_email("test_contact_customer@example.com", is_primary=True)
44 contact.add_phone("+91 0000000000", is_primary_phone=True)
45 contact.insert()
Ankush Menat76dd6e92021-05-23 16:19:48 +053046
47
48@contextmanager
49def change_settings(doctype, settings_dict):
50 """ A context manager to ensure that settings are changed before running
51 function and restored after running it regardless of exceptions occured.
52 This is useful in tests where you want to make changes in a function but
53 don't retain those changes.
54 import and use as decorator to cover full function or using `with` statement.
55
56 example:
57 @change_settings("Stock Settings", {"item_naming_by": "Naming Series"})
58 def test_case(self):
59 ...
60 """
61
62 try:
63 settings = frappe.get_doc(doctype)
64 # remember setting
65 previous_settings = copy.deepcopy(settings_dict)
66 for key in previous_settings:
67 previous_settings[key] = getattr(settings, key)
68
69 # change setting
70 for key, value in settings_dict.items():
71 setattr(settings, key, value)
72 settings.save()
73 yield # yield control to calling function
74
75 finally:
76 # restore settings
77 settings = frappe.get_doc(doctype)
78 for key, value in previous_settings.items():
79 setattr(settings, key, value)
80 settings.save()