1+ #
2+ # Licensed to the Apache Software Foundation (ASF) under one or more
3+ # contributor license agreements. See the NOTICE file distributed with
4+ # this work for additional information regarding copyright ownership.
5+ # The ASF licenses this file to You under the Apache License, Version 2.0
6+ # (the "License"); you may not use this file except in compliance with
7+ # the License. You may obtain a copy of the License at
8+ #
9+ # http://www.apache.org/licenses/LICENSE-2.0
10+ #
11+ # Unless required by applicable law or agreed to in writing, software
12+ # distributed under the License is distributed on an "AS IS" BASIS,
13+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+ # See the License for the specific language governing permissions and
15+ # limitations under the License.
16+ #
17+ """This executable test the pub/sub topic created by gcs_image_looper.py"""
18+
19+ from concurrent .futures import TimeoutError
20+
21+ from google .cloud import pubsub_v1
22+ from google .api_core .exceptions import AlreadyExists
23+
24+ project_id = "apache-beam-testing"
25+ subscription_id = "test-image-looper"
26+ topic_id = "Imagenet_openimage_50k_benchmark"
27+
28+ publisher = pubsub_v1 .PublisherClient ()
29+ subscriber = pubsub_v1 .SubscriberClient ()
30+ topic_path = publisher .topic_path (project_id , topic_id )
31+ subscription_path = subscriber .subscription_path (project_id , subscription_id )
32+
33+ try :
34+ subscription = subscriber .create_subscription (request = {
35+ "name" : subscription_path ,
36+ "topic" : topic_path
37+ })
38+ print (f"Subscription created: { subscription } " )
39+ except AlreadyExists :
40+ subscriber .delete_subscription (request = {"subscription" : subscription_path })
41+ subscription = subscriber .create_subscription (request = {
42+ "name" : subscription_path ,
43+ "topic" : topic_path
44+ })
45+ print (f"Subscription recreated: { subscription } " )
46+
47+ timeout = 3.0
48+
49+ total_images = []
50+
51+
52+ def callback (message : pubsub_v1 .subscriber .message .Message ) -> None :
53+ total_images .append (message .data .decode ())
54+ message .ack ()
55+
56+
57+ streaming_pull_future = subscriber .subscribe (subscription_path ,
58+ callback = callback )
59+ print (f"Listening for messages on { subscription_path } ..\n " )
60+
61+ try :
62+ # When `timeout` is not set, result() will block indefinitely,
63+ # unless an exception is encountered first.
64+ streaming_pull_future .result (timeout = timeout )
65+ except TimeoutError :
66+ streaming_pull_future .cancel () # Trigger the shutdown.
67+ streaming_pull_future .result () # Block until the shutdown is complete.
68+ print ("Results: \n " , total_images )
69+
70+ subscriber .delete_subscription (request = {"subscription" : subscription_path })
71+
72+ print (f"Subscription deleted: { subscription_path } ." )
0 commit comments