def test_file_upload_limit(self): from dataent.utils.file_manager import MaxFileSizeReachedError from dataent.limits import update_limits, clear_limit from dataent import _dict update_limits({ 'space': 1, 'space_usage': { 'files_size': (1024**2), 'database_size': 0, 'backup_size': 0, 'total': (1024**2) } }) # Rebuild the dataent.local.conf to take up the changes from site_config dataent.local.conf = _dict(dataent.get_site_config()) self.assertRaises(MaxFileSizeReachedError, save_file, '_test_max_space.txt', 'This files test for max space usage', "", "", self.get_folder("Test Folder 2", "Home").name) # Scrub the site_config and rebuild dataent.local.conf clear_limit("space") dataent.local.conf = _dict(dataent.get_site_config())
def test_insert_note(self): # Go to Authorize url self.driver.get( "api/method/dataent.integrations.oauth2.authorize?client_id=" + self.client_id + "&scope=all%20openid&response_type=code&redirect_uri=http%3A%2F%2Flocalhost" ) time.sleep(2) # Login username = self.driver.find("#login_email")[0] username.send_keys("*****@*****.**") password = self.driver.find("#login_password")[0] password.send_keys("Eastern_43A1W") sign_in = self.driver.find(".btn-login")[0] sign_in.submit() time.sleep(2) # Allow access to resource allow = self.driver.find("#allow")[0] allow.click() time.sleep(2) # Get authorization code from redirected URL auth_code = urlparse(self.driver.driver.current_url).query.split("=")[1] payload = "grant_type=authorization_code&code=" payload += auth_code payload += "&redirect_uri=http%3A%2F%2Flocalhost&client_id=" payload += self.client_id headers = {'content-type':'application/x-www-form-urlencoded'} # Request for bearer token token_response = requests.post( dataent.get_site_config().host_name + "/api/method/dataent.integrations.oauth2.get_token", data=payload, headers=headers) # Parse bearer token json bearer_token = token_response.json() client = DataentOAuth2Client(dataent.get_site_config().host_name, bearer_token.get("access_token")) notes = [ {"doctype": "Note", "title": "Sing", "public": True}, {"doctype": "Note", "title": "a", "public": True}, {"doctype": "Note", "title": "Song", "public": True}, {"doctype": "Note", "title": "of", "public": True}, {"doctype": "Note", "title": "sixpence", "public": True} ] for note in notes: client.insert(note) self.assertTrue(len(dataent.get_all("Note")) == 5)
def test_restrict_scheduler_events(self): dataent.set_user("Administrator") dormant_date = add_days(today(), -5) dataent.db.sql('update tabUser set last_active=%s', dormant_date) restrict_scheduler_events_if_dormant() dataent.local.conf = _dict(dataent.get_site_config()) self.assertFalse("all" in get_enabled_scheduler_events()) self.assertTrue(dataent.conf.get('dormant', False)) clear_limit("expiry") dataent.local.conf = _dict(dataent.get_site_config())
def test_auth_via_api_key_secret(self): # generate api ke and api secret for administrator keys = generate_keys("Administrator") dataent.db.commit() generated_secret = dataent.utils.password.get_decrypted_password( "User", "Administrator", fieldname='api_secret') api_key = dataent.db.get_value("User", "Administrator", "api_key") header = { "Authorization": "token {}:{}".format(api_key, generated_secret) } res = requests.post(dataent.get_site_config().host_name + "/api/method/dataent.auth.get_logged_user", headers=header) self.assertEqual(res.status_code, 200) self.assertEqual("Administrator", res.json()["message"]) self.assertEqual(keys['api_secret'], generated_secret) header = { "Authorization": "Basic {}".format( base64.b64encode( dataent.safe_encode("{}:{}".format( api_key, generated_secret))).decode()) } res = requests.post(dataent.get_site_config().host_name + "/api/method/dataent.auth.get_logged_user", headers=header) self.assertEqual(res.status_code, 200) self.assertEqual("Administrator", res.json()["message"]) # Valid api key, invalid api secret api_secret = "ksk&93nxoe3os" header = {"Authorization": "token {}:{}".format(api_key, api_secret)} res = requests.post(dataent.get_site_config().host_name + "/api/method/dataent.auth.get_logged_user", headers=header) self.assertEqual(res.status_code, 403) # random api key and api secret api_key = "@3djdk3kld" api_secret = "ksk&93nxoe3os" header = {"Authorization": "token {}:{}".format(api_key, api_secret)} res = requests.post(dataent.get_site_config().host_name + "/api/method/dataent.auth.get_logged_user", headers=header) self.assertEqual(res.status_code, 401)
def emulate_request(): # Emulate Woocommerce Request headers = { "X-Wc-Webhook-Event": "created", "X-Wc-Webhook-Signature": "h1SjzQMPwd68MF5bficeFq20/RkQeRLsb9AVCUz/rLs=" } # Emulate Request Data data = """{"id":74,"parent_id":0,"number":"74","order_key":"wc_order_5aa1281c2dacb","created_via":"checkout","version":"3.3.3","status":"processing","currency":"INR","date_created":"2018-03-08T12:10:04","date_created_gmt":"2018-03-08T12:10:04","date_modified":"2018-03-08T12:10:04","date_modified_gmt":"2018-03-08T12:10:04","discount_total":"0.00","discount_tax":"0.00","shipping_total":"150.00","shipping_tax":"0.00","cart_tax":"0.00","total":"649.00","total_tax":"0.00","prices_include_tax":false,"customer_id":12,"customer_ip_address":"103.54.99.5","customer_user_agent":"mozilla\\/5.0 (x11; linux x86_64) applewebkit\\/537.36 (khtml, like gecko) chrome\\/64.0.3282.186 safari\\/537.36","customer_note":"","billing":{"first_name":"Tony","last_name":"Stark","company":"Woocommerce","address_1":"Mumbai","address_2":"","city":"Dadar","state":"MH","postcode":"123","country":"IN","email":"*****@*****.**","phone":"123457890"},"shipping":{"first_name":"Tony","last_name":"Stark","company":"","address_1":"Mumbai","address_2":"","city":"Dadar","state":"MH","postcode":"123","country":"IN"},"payment_method":"cod","payment_method_title":"Cash on delivery","transaction_id":"","date_paid":null,"date_paid_gmt":null,"date_completed":null,"date_completed_gmt":null,"cart_hash":"8e76b020d5790066496f244860c4703f","meta_data":[],"line_items":[{"id":80,"name":"Marvel","product_id":56,"variation_id":0,"quantity":1,"tax_class":"","subtotal":"499.00","subtotal_tax":"0.00","total":"499.00","total_tax":"0.00","taxes":[],"meta_data":[],"sku":"","price":499}],"tax_lines":[],"shipping_lines":[{"id":81,"method_title":"Flat rate","method_id":"flat_rate:1","total":"150.00","total_tax":"0.00","taxes":[],"meta_data":[{"id":623,"key":"Items","value":"Marvel × 1"}]}],"fee_lines":[],"coupon_lines":[],"refunds":[]}""" # Build URL port = dataent.get_site_config().webserver_port or '8000' if os.environ.get('CI'): host = 'localhost' else: host = dataent.local.site url = "http://{site}:{port}/api/method/epaas.epaas_integrations.connectors.woocommerce_connection.order".format( site=host, port=port) r = requests.post(url=url, headers=headers, data=data) time.sleep(5) return r
def test_site_expiry(self): user = dataent.get_doc('User', '*****@*****.**') user.enabled = 1 user.new_password = '******' user.save() update_limits({'expiry': add_to_date(today(), days=-1), 'support_email': '*****@*****.**'}) dataent.local.conf = _dict(dataent.get_site_config()) dataent.db.commit() res = requests.post(get_url(), params={'cmd': 'login', 'usr': '******', 'pwd': 'Eastern_43A1W', 'device': 'desktop'}) # While site is expired status code returned is 417 Failed Expectation self.assertEqual(res.status_code, 417) clear_limit("expiry") dataent.local.conf = _dict(dataent.get_site_config())
def test_disable_scheduler_on_expiry(self): update_limits({'expiry': add_to_date(today(), days=-1)}) dataent.local.conf = _dict(dataent.get_site_config()) if not dataent.db.exists('User', '*****@*****.**'): user = dataent.new_doc('User') user.email = '*****@*****.**' user.first_name = 'Test_scheduler' user.save() user.add_roles('System Manager') dataent.db.commit() dataent.set_user("*****@*****.**") disable_scheduler_on_expiry() ss = dataent.get_doc("System Settings") self.assertFalse(ss.enable_scheduler) clear_limit("expiry") dataent.local.conf = _dict(dataent.get_site_config())
def check_valid_openid_response(access_token=None): # Returns True for valid response # Use token in header headers = {} if access_token: headers["Authorization"] = 'Bearer' + access_token # check openid for email [email protected] openid_response = requests.get( dataent.get_site_config().host_name + "/api/method/dataent.integrations.oauth2.openid_profile", headers=headers) return True if openid_response.status_code == 200 else False
def test_user_limit_for_site(self): update_limits({'users': get_total_users()}) # reload site config from dataent import _dict dataent.local.conf = _dict(dataent.get_site_config()) # Create a new user user = dataent.new_doc('User') user.email = '*****@*****.**' user.first_name = 'Test_max_user' self.assertRaises(MaxUsersReachedError, user.add_roles, 'System Manager') if dataent.db.exists('User', '*****@*****.**'): delete_contact('*****@*****.**') dataent.delete_doc('User', '*****@*****.**') # Clear the user limit clear_limit('users')
def __init__(self, port=None): self.port = port or dataent.get_site_config().webserver_port or '8000' chrome_options = Options() capabilities = DesiredCapabilities.CHROME if os.environ.get('CI'): self.host = 'localhost' else: self.host = dataent.local.site # enable browser logging capabilities['loggingPrefs'] = {'browser':'ALL'} chrome_options.add_argument('--no-sandbox') chrome_options.add_argument('--start-maximized') self.driver = webdriver.Chrome(chrome_options=chrome_options, desired_capabilities=capabilities, port=9515) # self.driver.set_window_size(1080,800) self.cur_route = None self.logged_in = False
def test_resource_owner_password_credentials_grant(self): # Set payload payload = "grant_type=password" payload += "&[email protected]" payload += "&password=Eastern_43A1W" payload += "&client_id=" + self.client_id payload += "&scope=openid%20all" headers = {'content-type': 'application/x-www-form-urlencoded'} # Request for bearer token token_response = requests.post( dataent.get_site_config().host_name + "/api/method/dataent.integrations.oauth2.get_token", data=payload, headers=headers) # Parse bearer token json bearer_token = token_response.json() # Check token for valid response self.assertTrue( check_valid_openid_response(bearer_token.get("access_token")))
def test_login_using_authorization_code(self): # Go to Authorize url self.driver.get( "api/method/dataent.integrations.oauth2.authorize?client_id=" + self.client_id + "&scope=all%20openid&response_type=code&redirect_uri=http%3A%2F%2Flocalhost" ) time.sleep(2) # Login username = self.driver.find("#login_email")[0] username.send_keys("*****@*****.**") password = self.driver.find("#login_password")[0] password.send_keys("Eastern_43A1W") sign_in = self.driver.find(".btn-login")[0] sign_in.submit() time.sleep(2) # Allow access to resource allow = self.driver.find("#allow")[0] allow.click() time.sleep(2) # Get authorization code from redirected URL auth_code = urlparse( self.driver.driver.current_url).query.split("=")[1] payload = "grant_type=authorization_code&code=" payload += auth_code payload += "&redirect_uri=http%3A%2F%2Flocalhost&client_id=" payload += self.client_id headers = {'content-type': 'application/x-www-form-urlencoded'} # Request for bearer token token_response = requests.post( dataent.get_site_config().host_name + "/api/method/dataent.integrations.oauth2.get_token", data=payload, headers=headers) # Parse bearer token json bearer_token = token_response.json() self.assertTrue(bearer_token.get("access_token")) self.assertTrue(bearer_token.get("expires_in")) self.assertTrue(bearer_token.get("id_token")) self.assertTrue(bearer_token.get("refresh_token")) self.assertTrue(bearer_token.get("scope")) self.assertTrue(bearer_token.get("token_type") == "Bearer") self.assertTrue( check_valid_openid_response(bearer_token.get("access_token"))) # Revoke Token revoke_token_response = requests.post( dataent.get_site_config().host_name + "/api/method/dataent.integrations.oauth2.revoke_token", data="token=" + bearer_token.get("access_token")) self.assertTrue(revoke_token_response.status_code == 200) # Check revoked token self.assertFalse( check_valid_openid_response(bearer_token.get("access_token")))