SchemaTest.java 10.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package org.apache.pulsar.tests.integration.schema;

import static org.apache.pulsar.common.naming.TopicName.PUBLIC_TENANT;
22
import static org.testng.Assert.assertEquals;
23
import static org.testng.Assert.assertNotEquals;
24 25 26 27

import com.google.common.collect.Sets;
import lombok.extern.slf4j.Slf4j;
import org.apache.pulsar.client.admin.PulsarAdmin;
28
import org.apache.pulsar.client.api.*;
29
import org.apache.pulsar.client.api.schema.GenericRecord;
30
import org.apache.pulsar.client.api.schema.SchemaDefinition;
31 32 33
import org.apache.pulsar.common.naming.TopicDomain;
import org.apache.pulsar.common.naming.TopicName;
import org.apache.pulsar.tests.integration.schema.Schemas.Person;
34
import org.apache.pulsar.tests.integration.schema.Schemas.PersonConsumeSchema;
35
import org.apache.pulsar.tests.integration.schema.Schemas.Student;
36
import org.apache.pulsar.tests.integration.schema.Schemas.AvroLogicalType;
37 38 39 40
import org.apache.pulsar.tests.integration.suites.PulsarTestSuite;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

41
import java.math.BigDecimal;
42 43 44
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalTime;
45 46
import java.util.ArrayList;
import java.util.List;
47

48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
/**
 * Test Pulsar Schema.
 */
@Slf4j
public class SchemaTest extends PulsarTestSuite {

    private PulsarClient client;
    private PulsarAdmin admin;

    @BeforeMethod
    public void setup() throws Exception {
        this.client = PulsarClient.builder()
            .serviceUrl(pulsarCluster.getPlainTextServiceUrl())
            .build();
        this.admin = PulsarAdmin.builder()
            .serviceHttpUrl(pulsarCluster.getHttpServiceUrl())
            .build();
    }

    @Test
    public void testCreateSchemaAfterDeletion() throws Exception {
        final String tenant = PUBLIC_TENANT;
        final String namespace = "test-namespace-" + randomName(16);
        final String topic = "test-create-schema-after-deletion";
        final String fqtn = TopicName.get(
             TopicDomain.persistent.value(),
             tenant,
             namespace,
             topic
         ).toString();

        admin.namespaces().createNamespace(
            tenant + "/" + namespace,
            Sets.newHashSet(pulsarCluster.getClusterName())
        );

        // Create a topic with `Person`
        try (Producer<Person> producer = client.newProducer(Schema.AVRO(Person.class))
             .topic(fqtn)
             .create()
        ) {
            Person person = new Person();
            person.setName("Tom Hanks");
            person.setAge(60);

            producer.send(person);

            log.info("Successfully published person : {}", person);
        }

        log.info("Deleting schema of topic {}", fqtn);
        // delete the schema
        admin.schemas().deleteSchema(fqtn);
        log.info("Successfully deleted schema of topic {}", fqtn);

        // after deleting the topic, try to create a topic with a different schema
        try (Producer<Student> producer = client.newProducer(Schema.AVRO(Student.class))
             .topic(fqtn)
             .create()
        ) {
            Student student = new Student();
            student.setName("Tom Jerry");
            student.setAge(30);
            student.setGpa(6);
            student.setGpa(10);

            producer.send(student);

            log.info("Successfully published student : {}", student);
        }
    }

120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
    @Test
    public void testMultiVersionSchema() throws Exception {
        final String tenant = PUBLIC_TENANT;
        final String namespace = "test-namespace-" + randomName(16);
        final String topic = "test-multi-version-schema";
        final String fqtn = TopicName.get(
                TopicDomain.persistent.value(),
                tenant,
                namespace,
                topic
        ).toString();

        admin.namespaces().createNamespace(
                tenant + "/" + namespace,
                Sets.newHashSet(pulsarCluster.getClusterName())
        );

137
        Producer<Person> producer = client.newProducer(Schema.AVRO(
138 139 140 141
                SchemaDefinition.<Person>builder().withAlwaysAllowNull
                        (false).withSupportSchemaVersioning(true).
                        withPojo(Person.class).build()))
                .topic(fqtn)
142
                .create();
143

144 145 146
        Person person = new Person();
        person.setName("Tom Hanks");
        person.setAge(60);
147

148
        Consumer<PersonConsumeSchema> consumer = client.newConsumer(Schema.AVRO(
149 150 151
                SchemaDefinition.<PersonConsumeSchema>builder().withAlwaysAllowNull
                        (false).withSupportSchemaVersioning(true).
                        withPojo(PersonConsumeSchema.class).build()))
152
                .subscriptionName("test")
153 154
                .topic(fqtn)
                .subscribe();
155 156 157 158 159 160 161 162 163 164 165 166

        producer.send(person);
        log.info("Successfully published person : {}", person);

        PersonConsumeSchema personConsumeSchema = consumer.receive().getValue();
        assertEquals("Tom Hanks", personConsumeSchema.getName());
        assertEquals(60, personConsumeSchema.getAge());
        assertEquals("male", personConsumeSchema.getGender());

        producer.close();
        consumer.close();
        log.info("Successfully consumer personConsumeSchema : {}", personConsumeSchema);
167
    }
168

169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
    @Test
    public void testAvroLogicalType() throws Exception {
        final String tenant = PUBLIC_TENANT;
        final String namespace = "test-namespace-" + randomName(16);
        final String topic = "test-logical-type-schema";
        final String fqtn = TopicName.get(
                TopicDomain.persistent.value(),
                tenant,
                namespace,
                topic
        ).toString();

        admin.namespaces().createNamespace(
                tenant + "/" + namespace,
                Sets.newHashSet(pulsarCluster.getClusterName())
        );

        AvroLogicalType messageForSend = AvroLogicalType.builder()
                .decimal(new BigDecimal("12.34"))
                .timestampMicros(System.currentTimeMillis() * 1000)
189
                .timestampMillis(Instant.parse("2019-03-26T04:39:58.469Z"))
190 191 192 193 194
                .timeMillis(LocalTime.now())
                .timeMicros(System.currentTimeMillis() * 1000)
                .date(LocalDate.now())
                .build();

195
        Producer<AvroLogicalType> producer = client
196 197
                .newProducer(Schema.AVRO(SchemaDefinition.<AvroLogicalType>builder().withPojo(AvroLogicalType.class)
                        .withJSR310ConversionEnabled(true).build()))
198
                .topic(fqtn)
199
                .create();
200

201
        Consumer<AvroLogicalType> consumer = client
202 203
                .newConsumer(Schema.AVRO(AvroLogicalType.class))
                .topic(fqtn)
204 205 206 207 208 209 210
                .subscriptionName("test")
                .subscribe();

        producer.send(messageForSend);
        log.info("Successfully published avro logical type message : {}", messageForSend);

        AvroLogicalType received = consumer.receive().getValue();
211
        assertEquals(received, messageForSend);
212

213 214
        producer.close();
        consumer.close();
215

216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258
        log.info("Successfully consumer avro logical type message : {}", received);
    }

    @Test
    public void testAutoConsumeSchemaSubscribeFirst() throws Exception {
        final String tenant = PUBLIC_TENANT;
        final String namespace = "test-namespace-" + randomName(16);
        final String topic = "test-auto-consume-schema";
        final String fqtn = TopicName.get(
                TopicDomain.persistent.value(),
                tenant,
                namespace,
                topic
        ).toString();

        admin.namespaces().createNamespace(
                tenant + "/" + namespace,
                Sets.newHashSet(pulsarCluster.getClusterName())
        );

        Consumer<GenericRecord> consumer = client
                .newConsumer(Schema.AUTO_CONSUME())
                .topic(fqtn)
                .subscriptionName("test")
                .subscribe();

        Producer<Person> producer = client
                .newProducer(Schema.AVRO(Person.class))
                .topic(fqtn)
                .create();

        Person person = new Person();
        person.setName("Tom Hanks");
        person.setAge(60);
        producer.send(person);

        GenericRecord genericRecord = consumer.receive().getValue();

        assertEquals(genericRecord.getField("name"), "Tom Hanks");
        assertEquals(genericRecord.getField("age"), 60);

        consumer.close();
        producer.close();
259 260
    }

261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
    @Test
    public void testPrimitiveSchemaTypeCompatibilityCheck() {
        List<Schema> schemas = new ArrayList<>();

        schemas.add(Schema.STRING);
        schemas.add(Schema.INT8);
        schemas.add(Schema.INT16);
        schemas.add(Schema.INT32);
        schemas.add(Schema.INT64);
        schemas.add(Schema.BOOL);
        schemas.add(Schema.DOUBLE);
        schemas.add(Schema.FLOAT);
        schemas.add(Schema.DATE);
        schemas.add(Schema.TIME);
        schemas.add(Schema.TIMESTAMP);
276 277 278 279
        schemas.add(Schema.INSTANT);
        schemas.add(Schema.LOCAL_DATE);
        schemas.add(Schema.LOCAL_TIME);
        schemas.add(Schema.LOCAL_DATE_TIME);
280

281 282
        schemas.forEach(schemaProducer -> {
            schemas.forEach(schemaConsumer -> {
283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
                try {
                    String topicName = schemaProducer.getSchemaInfo().getName() + schemaConsumer.getSchemaInfo().getName();
                        client.newProducer(schemaProducer)
                                .topic(topicName)
                                .create().close();

                        client.newConsumer(schemaConsumer)
                                .topic(topicName)
                                .subscriptionName("test")
                                .subscribe().close();
                    assertEquals(schemaProducer.getSchemaInfo().getType(),
                            schemaConsumer.getSchemaInfo().getType());

                } catch (PulsarClientException e) {
                    assertNotEquals(schemaProducer.getSchemaInfo().getType(),
                            schemaConsumer.getSchemaInfo().getType());
                }

            });
        });

    }

306
}
307