def test_generate_product_mix_ideas_flattened(): client = ReachPlanServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.generate_product_mix_ideas), '__call__') as call: # Designate an appropriate return value for the call. call.return_value = reach_plan_service.GenerateProductMixIdeasResponse( ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.generate_product_mix_ideas( customer_id='customer_id_value', plannable_location_id=wrappers_pb2.StringValue( value='value_value'), currency_code=wrappers_pb2.StringValue(value='value_value'), budget_micros=wrappers_pb2.Int64Value(value=541), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] assert args[0].customer_id == 'customer_id_value' assert args[0].plannable_location_id == wrappers_pb2.StringValue( value='value_value') assert args[0].currency_code == wrappers_pb2.StringValue( value='value_value') assert args[0].budget_micros == wrappers_pb2.Int64Value(value=541)
def test_get_billing_setup(transport: str = 'grpc', request_type=billing_setup_service.GetBillingSetupRequest): client = BillingSetupServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. request = request_type() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( type(client.transport.get_billing_setup), '__call__') as call: # Designate an appropriate return value for the call. call.return_value = billing_setup.BillingSetup( resource_name='resource_name_value', status=billing_setup_status.BillingSetupStatusEnum.BillingSetupStatus.UNKNOWN, start_date_time=wrappers_pb2.StringValue(value='value_value'), end_date_time=wrappers_pb2.StringValue(value='value_value'), ) response = client.get_billing_setup(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] assert args[0] == billing_setup_service.GetBillingSetupRequest() # Establish that the response is the type that we expect. assert isinstance(response, billing_setup.BillingSetup) assert response.resource_name == 'resource_name_value' assert response.status == billing_setup_status.BillingSetupStatusEnum.BillingSetupStatus.UNKNOWN
def get_device_with_filter(stub, serial, hostname): """ Fetch single device from the inventory by hostname (and optionally serial) The hostname argument is required in this case. If hostname was not provided then the lookup should be done by serial. """ # create a stream request get_all_req = services.DeviceStreamRequest() # create an uninitialized key (nop), but set the serial if given device_key = None if serial is not None: device_key = models.DeviceKey(device_id=wrappers.StringValue( value=serial)) # create the filter model with hostname and optional key set filt = models.Device(key=device_key, hostname=wrappers.StringValue(value=hostname)) # add the filter to the request get_all_req.partial_eq_filter.append(filt) # while we only expect one, we loop over everything streamed # this should be only one message, but you may want to do assertions for resp in stub.GetAll(get_all_req, timeout=RPC_TIMEOUT): print(resp)
def test_generate_reach_forecast_flattened(): client = ReachPlanServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.generate_reach_forecast), '__call__') as call: # Designate an appropriate return value for the call. call.return_value = reach_plan_service.GenerateReachForecastResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.generate_reach_forecast( customer_id='customer_id_value', campaign_duration=reach_plan_service.CampaignDuration( duration_in_days=wrappers_pb2.Int32Value(value=541)), planned_products=[ reach_plan_service.PlannedProduct( plannable_product_code=wrappers_pb2.StringValue( value='value_value')) ], ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] assert args[0].customer_id == 'customer_id_value' assert args[ 0].campaign_duration == reach_plan_service.CampaignDuration( duration_in_days=wrappers_pb2.Int32Value(value=541)) assert args[0].planned_products == [ reach_plan_service.PlannedProduct( plannable_product_code=wrappers_pb2.StringValue( value='value_value')) ]
def test_upload_conversion_adjustments_flattened(): client = ConversionAdjustmentUploadServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( type(client.transport.upload_conversion_adjustments), '__call__') as call: # Designate an appropriate return value for the call. call.return_value = conversion_adjustment_upload_service.UploadConversionAdjustmentsResponse( ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.upload_conversion_adjustments( customer_id='customer_id_value', conversion_adjustments=[ conversion_adjustment_upload_service.ConversionAdjustment( conversion_action=wrappers_pb2.StringValue( value='value_value')) ], partial_failure=True, ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] assert args[0].customer_id == 'customer_id_value' assert args[0].conversion_adjustments == [ conversion_adjustment_upload_service.ConversionAdjustment( conversion_action=wrappers_pb2.StringValue( value='value_value')) ] assert args[0].partial_failure == True
def _set_scenario_result( scenario_id: str, output: Any, exception: Any, logs: str, time_taken: float, succeeded: int, failed: int, address: str = DEFAULT_BACKEND_ADDRESS, ): with grpc.insecure_channel(address, compression=grpc.Compression.Gzip) as channel: stub = backend_pb2_grpc.BackendStub(channel) request = backend_pb2.SetScenarioResultRequest( scenarioID=scenario_id, output=wrappers_pb2.StringValue(value=json.dumps(output)), exception=wrappers_pb2.StringValue(value=json.dumps( str(exception) if exception is not None else None)), logs=logs, timeTaken=time_taken, succeeded=succeeded, failed=failed, ) stub.SetScenarioResult(request)
def main(args): # read the file containing a session token to authenticate with token = args.token_file.read().strip() # create the header object for the token callCreds = grpc.access_token_call_credentials(token) # if using a self-signed certificate (should be provided as arg) if args.cert_file: # create the channel using the self-signed cert cert = args.cert_file.read() channelCreds = grpc.ssl_channel_credentials(root_certificates=cert) else: # otherwise default to checking against CAs channelCreds = grpc.ssl_channel_credentials() connCreds = grpc.composite_channel_credentials(channelCreds, callCreds) if args.tag_value: tag_value = args.tag_value if args.tag_name: tag_name = args.tag_name # initialize a connection to the server using our connection settings (auth + TLS) with grpc.secure_channel(args.server, connCreds) as channel: tag_stub = services.InterfaceTagConfigServiceStub(channel) req = services.InterfaceTagConfigSetRequest( value=models.InterfaceTagConfig( key=models.TagKey(label=wrappers.StringValue(value=tag_name), value=wrappers.StringValue( value=tag_value)))) tag_stub.Set(req, timeout=RPC_TIMEOUT)
def test_diff_between_datastore_tables(): pre_changed = DatastoreTable(project="test", name="table", project_id="pre", namespace="pre").to_proto() post_changed = DatastoreTable(project="test", name="table", project_id="post", namespace="post").to_proto() infra_object_diff = diff_between(pre_changed, pre_changed, "datastore table") infra_object_property_diffs = infra_object_diff.infra_object_property_diffs assert len(infra_object_property_diffs) == 0 infra_object_diff = diff_between(pre_changed, post_changed, "datastore table") infra_object_property_diffs = infra_object_diff.infra_object_property_diffs assert len(infra_object_property_diffs) == 2 assert infra_object_property_diffs[0].property_name == "project_id" assert infra_object_property_diffs[0].val_existing == wrappers.StringValue( value="pre") assert infra_object_property_diffs[0].val_declared == wrappers.StringValue( value="post") assert infra_object_property_diffs[1].property_name == "namespace" assert infra_object_property_diffs[1].val_existing == wrappers.StringValue( value="pre") assert infra_object_property_diffs[1].val_declared == wrappers.StringValue( value="post")
def render(self): """Render method for confirm :return: confirm """ confirm = messaging_pb2.InteractiveMediaConfirm() if self.text is not None: confirm.text = wrappers_pb2.StringValue(value=self.text) if self.title is not None: confirm.title = wrappers_pb2.StringValue(value=self.title) if self.ok is not None: confirm.ok = wrappers_pb2.StringValue(value=self.ok) if self.dismiss is not None: confirm.dismiss = wrappers_pb2.StringValue(value=self.dismiss) return confirm
def test_generate_product_mix_ideas_flattened_error(): client = ReachPlanServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): client.generate_product_mix_ideas( reach_plan_service.GenerateProductMixIdeasRequest(), customer_id='customer_id_value', plannable_location_id=wrappers_pb2.StringValue( value='value_value'), currency_code=wrappers_pb2.StringValue(value='value_value'), budget_micros=wrappers_pb2.Int64Value(value=541), )
def test_ChangeEmail(db, fast_passwords): password = random_hex() new_email = f"{random_hex()}@couchers.org.invalid" user, token = generate_user(db, hashed_password=hash_password(password)) with account_session(db, token) as account: account.ChangeEmail( account_pb2.ChangeEmailReq( password=wrappers_pb2.StringValue(value=password), new_email=new_email, )) with session_scope(db) as session: user_updated = (session.query(User).filter(User.id == user.id).filter( User.new_email == new_email).filter( User.new_email_token_created <= func.now()).filter( User.new_email_token_expiry >= func.now())).one() token = user_updated.new_email_token with auth_api_session(db) as auth_api: res = auth_api.CompleteChangeEmail( auth_pb2.CompleteChangeEmailReq(change_email_token=token, )) with session_scope(db) as session: user_updated2 = session.query(User).filter(User.id == user.id).one() assert user_updated2.email == new_email assert user_updated2.new_email is None assert user_updated2.new_email_token is None # check there's no valid tokens left with session_scope(db) as session: assert (session.query(User).filter( User.new_email_token_created <= func.now()).filter( User.new_email_token_expiry >= func.now())).count() == 0
def test_ChangeEmail_wrong_token(db, fast_passwords): password = random_hex() new_email = f"{random_hex()}@couchers.org.invalid" user, token = generate_user(db, hashed_password=hash_password(password)) with account_session(db, token) as account: account.ChangeEmail( account_pb2.ChangeEmailReq( password=wrappers_pb2.StringValue(value=password), new_email=new_email, )) with session_scope(db) as session: user_updated = (session.query(User).filter(User.id == user.id).filter( User.new_email == new_email).filter( User.new_email_token_created <= func.now()).filter( User.new_email_token_expiry >= func.now())).one() token = user_updated.new_email_token with auth_api_session(db) as auth_api: with pytest.raises(grpc.RpcError) as e: res = auth_api.CompleteChangeEmail( auth_pb2.CompleteChangeEmailReq( change_email_token="wrongtoken", )) assert e.value.code() == grpc.StatusCode.UNAUTHENTICATED assert e.value.details() == errors.INVALID_TOKEN with session_scope(db) as session: user_updated2 = session.query(User).filter(User.id == user.id).one() assert user_updated2.email == user.email
def run(): channel = grpc.insecure_channel('localhost:50051') stub = order_management_pb2_grpc.OrderManagementStub(channel) order1 = order_management_pb2.Order( items=['Item - A', 'Item - B', 'Item - C'], price=2450.50, description='This is a Sample order - 1 : description.', destination='San Jose, CA') order = stub.getOrder(order_management_pb2.Order(id='101')) print("Order service response", order) # Unary RPC : Adding an Order response = stub.addOrder(order1) print('Add order response :', response) # Server Streaming for order_search_result in stub.searchOrders( wrappers_pb2.StringValue(value='Item - A')): print('Search Result : ', order_search_result) # Client Streaming upd_order_iterator = generate_orders_for_updates() upd_status = stub.updateOrders(upd_order_iterator) print('Order update status : ', upd_status) # Bi-di Streaming proc_order_iterator = generate_orders_for_processing() for shipment in stub.processOrders(proc_order_iterator): print(shipment)
def test_get_shared_criterion(transport: str = 'grpc', request_type=shared_criterion_service.GetSharedCriterionRequest): client = SharedCriterionServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. request = request_type() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( type(client.transport.get_shared_criterion), '__call__') as call: # Designate an appropriate return value for the call. call.return_value = shared_criterion.SharedCriterion( resource_name='resource_name_value', type_=criterion_type.CriterionTypeEnum.CriterionType.UNKNOWN, keyword=criteria.KeywordInfo(text=wrappers_pb2.StringValue(value='value_value')), ) response = client.get_shared_criterion(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] assert args[0] == shared_criterion_service.GetSharedCriterionRequest() # Establish that the response is the type that we expect. assert isinstance(response, shared_criterion.SharedCriterion) assert response.resource_name == 'resource_name_value' assert response.type_ == criterion_type.CriterionTypeEnum.CriterionType.UNKNOWN
def test_ChangeEmail_sends_proper_emails_has_password(db, fast_passwords): password = random_hex() new_email = f"{random_hex()}@couchers.org.invalid" user, token = generate_user(hashed_password=hash_password(password)) with account_session(token) as account: account.ChangeEmail( account_pb2.ChangeEmailReq( password=wrappers_pb2.StringValue(value=password), new_email=new_email, )) with session_scope() as session: jobs = (session.execute( select(BackgroundJob).where( BackgroundJob.job_type == BackgroundJobType.send_email)).scalars().all()) assert len(jobs) == 2 payload_for_notification_email = jobs[0].payload payload_for_confirmation_email_new_address = jobs[1].payload unique_string_notification_email_as_bytes = b"You requested that your email on Couchers.org be changed to" unique_string_for_confirmation_email_new_email_address_as_bytes = ( b"You requested that your email be changed to this email address on Couchers.org" ) assert unique_string_notification_email_as_bytes in payload_for_notification_email assert (unique_string_for_confirmation_email_new_email_address_as_bytes in payload_for_confirmation_email_new_address)
def get_str_val(s): """Return obj google.protobuf.StringValue :param s: string :return: StringValue """ return wrappers_pb2.StringValue(value=s)
def addOrder(self, request, context): id = uuid.uuid1() request.id = str(id) self.orderDict[request.id] = request response = wrappers_pb2.StringValue(value=str(id)) print(self.orderDict) return response
def addOrder(self, request, context): order_id = str(uuid.uuid1()) request.id = order_id logging.info("Add Order: %s", request) self.orders[order_id] = request logging.info("Orders: %s", self.orders) return wrappers_pb2.StringValue(value=order_id)
def main(): with grpc.insecure_channel("localhost:50051") as in_secure_channel: metadata_interceptor = MetadataInterceptor( ('dst_soc', '192.168.0.100')) with grpc.intercept_channel(in_secure_channel, metadata_interceptor) as channel: stub = ordermgmt_pb2_grpc.OrderManagementStub(channel) try: stub.getOrder( wrappers_pb2.StringValue(value="NOTEXISTEDORDER")) except Exception as e: print(e) for order in placed_orders: response = stub.addOrder(order) order_id = response.value order.id = order_id print("New Order ID: %s" % order_id) print(order) print() # server streaming match_orders = list( stub.searchOrders(wrappers_pb2.StringValue(value="Bicycle"))) print("Search result cout: %d" % len(match_orders)) print("Search Result : \n", "\n".join(str(_) for _ in match_orders)) # client streaming def updated_orders_gen(): for order in placed_orders: yield order stub.updateOrders(updated_orders_gen()) print("-" * 30) # bidirectional streaming need_process_orders = [ wrappers_pb2.StringValue(value=_.id) for _ in placed_orders ] def need_process_orders_gen(): for order_id in need_process_orders: yield order_id print() for shipment in stub.processOrders(need_process_orders_gen()): print("Shipment: ", shipment)
def destructive_editTask( self, request, context ) -> task_pb2.Task: # destructive_editTask , deletes the task and creates a new task with the edits. self.delTask(wrappers_pb2.UInt64Value(value=request.id), context=context) # delet item return self.addTask( wrappers_pb2.StringValue(value=request.description), context=context) # add new item and return
def _deserialize_from_proto(cls, proto, **unused_kwargs): if proto.Is(wrappers_pb2.StringValue.DESCRIPTOR): unpacked = wrappers_pb2.StringValue() proto.Unpack(unpacked) return cls(name=unpacked.value) raise AssertionError( "Did not receive proto of correct type during deserialization. " f"Expected type {wrappers_pb2.StringValue.DESCRIPTOR.full_name}, " f"got {proto.TypeName()}")
def updateOrders(self, request_iterator, context): logging.info("Update orders") updated_orders = ["Updated IDs:"] for order in request_iterator: self.orders[order.id] = order updated_orders.append(order.id) updated_orders = " ".join(updated_orders) logging.info(updated_orders) return wrappers_pb2.StringValue(value=updated_orders)
def test_add(stub, count) -> Mapping[int, str]: tasks = {} for i in range(count): desc = random_string_generator(99) task: task_pb2.Task = stub.addTask(wrappers_pb2.StringValue(value=desc)) logging.debug(f"Added Task {pformat(task)}") tasks[task.id] = task.description return tasks
def test_ChangePassword_regression(db, fast_passwords): # send_password_changed_email wasn't working # user has old password and is changing to new password old_password = random_hex() new_password = random_hex() user, token = generate_user(hashed_password=hash_password(old_password)) with account_session(token) as account: account.ChangePassword( account_pb2.ChangePasswordReq( old_password=wrappers_pb2.StringValue(value=old_password), new_password=wrappers_pb2.StringValue(value=new_password), )) with session_scope() as session: updated_user = session.execute( select(User).where(User.id == user.id)).scalar_one() assert updated_user.hashed_password == hash_password(new_password)
def test_update_page_errors(db): user, token = generate_user() with session_scope() as session: c_id = create_community(session, 0, 2, "Root node", [user], [], None).id with pages_session(token) as api: page_id = api.CreatePlace( pages_pb2.CreatePlaceReq( title="dummy title", content="dummy content", address="dummy address", location=pages_pb2.Coordinate( lat=1, lng=1, ), )).page_id with pytest.raises(grpc.RpcError) as e: api.UpdatePage( pages_pb2.UpdatePageReq( page_id=page_id, title=wrappers_pb2.StringValue(value=""), )) assert e.value.code() == grpc.StatusCode.INVALID_ARGUMENT assert e.value.details() == errors.MISSING_PAGE_TITLE with pytest.raises(grpc.RpcError) as e: api.UpdatePage( pages_pb2.UpdatePageReq( page_id=page_id, content=wrappers_pb2.StringValue(value=""), )) assert e.value.code() == grpc.StatusCode.INVALID_ARGUMENT assert e.value.details() == errors.MISSING_PAGE_CONTENT with pytest.raises(grpc.RpcError) as e: api.UpdatePage( pages_pb2.UpdatePageReq( page_id=page_id, address=wrappers_pb2.StringValue(value=""), )) assert e.value.code() == grpc.StatusCode.INVALID_ARGUMENT assert e.value.details() == errors.MISSING_PAGE_ADDRESS
def get_device_by_serial(stub, serial): """ Fetch a single device from the inventory by serial number. """ # create a unary device request, setting the key to the given serial req = services.DeviceRequest( key={"device_id": wrappers.StringValue(value=serial)}) # issue the request and print it resp = stub.GetOne(req) print(resp)
def test_ChangePassword_normal(db, fast_passwords): # user has old password and is changing to new password old_password = random_hex() new_password = random_hex() user, token = generate_user(hashed_password=hash_password(old_password)) with account_session(token) as account: with patch("couchers.servicers.account.send_password_changed_email") as mock: account.ChangePassword( account_pb2.ChangePasswordReq( old_password=wrappers_pb2.StringValue(value=old_password), new_password=wrappers_pb2.StringValue(value=new_password), ) ) mock.assert_called_once() with session_scope() as session: updated_user = session.query(User).filter(User.id == user.id).one() assert updated_user.hashed_password == hash_password(new_password)
def test_ChangePassword_add_with_password(db, fast_passwords): # user does not have an old password and is adding a new password, but supplied a password new_password = random_hex() user, token = generate_user(db, hashed_password=None) with account_session(db, token) as account: with pytest.raises(grpc.RpcError) as e: account.ChangePassword( account_pb2.ChangePasswordReq( old_password=wrappers_pb2.StringValue( value="wrong password"), new_password=wrappers_pb2.StringValue(value=new_password), )) assert e.value.code() == grpc.StatusCode.INVALID_ARGUMENT assert e.value.details() == errors.NO_PASSWORD with session_scope(db) as session: updated_user = session.query(User).filter(User.id == user.id).one() assert updated_user.hashed_password == None
def test_get_campaign(transport: str = 'grpc', request_type=campaign_service.GetCampaignRequest): client = CampaignServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. request = request_type() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_campaign), '__call__') as call: # Designate an appropriate return value for the call. call.return_value = campaign.Campaign( resource_name='resource_name_value', status=campaign_status.CampaignStatusEnum.CampaignStatus.UNKNOWN, serving_status=campaign_serving_status.CampaignServingStatusEnum. CampaignServingStatus.UNKNOWN, ad_serving_optimization_status=ad_serving_optimization_status. AdServingOptimizationStatusEnum.AdServingOptimizationStatus. UNKNOWN, advertising_channel_type=advertising_channel_type. AdvertisingChannelTypeEnum.AdvertisingChannelType.UNKNOWN, advertising_channel_sub_type=advertising_channel_sub_type. AdvertisingChannelSubTypeEnum.AdvertisingChannelSubType.UNKNOWN, experiment_type=campaign_experiment_type. CampaignExperimentTypeEnum.CampaignExperimentType.UNKNOWN, bidding_strategy_type=bidding_strategy_type. BiddingStrategyTypeEnum.BiddingStrategyType.UNKNOWN, video_brand_safety_suitability=brand_safety_suitability. BrandSafetySuitabilityEnum.BrandSafetySuitability.UNKNOWN, payment_mode=payment_mode.PaymentModeEnum.PaymentMode.UNKNOWN, bidding_strategy=wrappers_pb2.StringValue(value='value_value'), ) response = client.get_campaign(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] assert args[0] == campaign_service.GetCampaignRequest() # Establish that the response is the type that we expect. assert isinstance(response, campaign.Campaign) assert response.resource_name == 'resource_name_value' assert response.status == campaign_status.CampaignStatusEnum.CampaignStatus.UNKNOWN assert response.serving_status == campaign_serving_status.CampaignServingStatusEnum.CampaignServingStatus.UNKNOWN assert response.ad_serving_optimization_status == ad_serving_optimization_status.AdServingOptimizationStatusEnum.AdServingOptimizationStatus.UNKNOWN assert response.advertising_channel_type == advertising_channel_type.AdvertisingChannelTypeEnum.AdvertisingChannelType.UNKNOWN assert response.advertising_channel_sub_type == advertising_channel_sub_type.AdvertisingChannelSubTypeEnum.AdvertisingChannelSubType.UNKNOWN assert response.experiment_type == campaign_experiment_type.CampaignExperimentTypeEnum.CampaignExperimentType.UNKNOWN assert response.bidding_strategy_type == bidding_strategy_type.BiddingStrategyTypeEnum.BiddingStrategyType.UNKNOWN assert response.video_brand_safety_suitability == brand_safety_suitability.BrandSafetySuitabilityEnum.BrandSafetySuitability.UNKNOWN assert response.payment_mode == payment_mode.PaymentModeEnum.PaymentMode.UNKNOWN
def test_ChangePassword_normal_long_password(db, fast_passwords): # user has old password and is changing to new password, but used short password old_password = random_hex() new_password = random_hex(length=1000) user, token = generate_user(hashed_password=hash_password(old_password)) with account_session(token) as account: with pytest.raises(grpc.RpcError) as e: account.ChangePassword( account_pb2.ChangePasswordReq( old_password=wrappers_pb2.StringValue(value=old_password), new_password=wrappers_pb2.StringValue(value=new_password), ) ) assert e.value.code() == grpc.StatusCode.INVALID_ARGUMENT assert e.value.details() == errors.PASSWORD_TOO_LONG with session_scope() as session: updated_user = session.query(User).filter(User.id == user.id).one() assert updated_user.hashed_password == hash_password(old_password)