Пример #1
0
// Simple test for publishing and received versioned events using rabbitmq
func TestEventBus(t *testing.T) {
	// Create a new event bus
	bus := rabbit.NewEventBus("amqp://*****:*****@localhost:5672/", "rabbit_testevents", "testing.events")

	// Register types
	eventType := reflect.TypeOf(SampleEvent{})
	eventTypeCache := cqrs.NewTypeRegistry()
	eventTypeCache.RegisterType(SampleEvent{})

	// Create communication channels
	//
	// for closing the queue listener,
	closeChannel := make(chan chan error)
	// receiving errors from the listener thread (go routine)
	errorChannel := make(chan error)
	// and receiving events from the queue
	receiveEventChannel := make(chan cqrs.VersionedEventTransactedAccept)
	// Start receiving events by passing these channels to the worker thread (go routine)
	if err := bus.ReceiveEvents(cqrs.VersionedEventReceiverOptions{eventTypeCache, closeChannel, errorChannel, receiveEventChannel, false}); err != nil {
		t.Fatal(err)
	}

	// Publish a simple event to the exchange http://www.rabbitmq.com/tutorials/tutorial-three-python.html
	log.Println("Publishing events")
	go func() {
		if err := bus.PublishEvents([]cqrs.VersionedEvent{cqrs.VersionedEvent{
			EventType: eventType.String(),
			Event:     SampleEvent{"rabbit_TestEventBus"}}}); err != nil {
			t.Fatal(err)
		}
	}()

	// If we dont receive a message within 5 seconds this test is a failure. Use a channel to signal the timeout
	timeout := make(chan bool, 1)
	go func() {
		time.Sleep(5 * time.Second)
		timeout <- true
	}()

	// Wait on multiple channels using the select control flow.
	select {
	// Test timeout
	case <-timeout:
		t.Fatal("Test timed out")
		// Version event received channel receives a result with a channel to respond to, signifying successful processing of the message.
		// This should eventually call an event handler. See cqrs.NewVersionedEventDispatcher()
	case event := <-receiveEventChannel:
		sampleEvent := event.Event.Event.(SampleEvent)
		log.Println(sampleEvent.Message)
		event.ProcessedSuccessfully <- true
		// Receiving on this channel signifys an error has occured work processor side
	case err := <-errorChannel:
		t.Fatal(err)
	}
}
Пример #2
0
func RunScenario(t *testing.T, persistance cqrs.EventStreamRepository) {
	typeRegistry := cqrs.NewTypeRegistry()
	bus := rabbit.NewEventBus("amqp://*****:*****@localhost:5672/", "example_test", "testing.example")
	repository := cqrs.NewRepositoryWithPublisher(persistance, bus, typeRegistry)
	repository.GetTypeRegistry().RegisterAggregate(&Account{})
	repository.GetTypeRegistry().RegisterEvents(AccountCreatedEvent{}, EmailAddressChangedEvent{}, AccountCreditedEvent{}, AccountDebitedEvent{}, PasswordChangedEvent{})
	accountID := "5058e029-d329-4c4b-b111-b042e48b0c5f"

	readModel := NewReadModelAccounts()

	usersModel := NewUsersModel()

	eventDispatcher := cqrs.NewVersionedEventDispatchManager(bus, typeRegistry)

	eventDispatcher.RegisterEventHandler(AccountCreatedEvent{}, func(event cqrs.VersionedEvent) error {
		readModel.UpdateViewModel([]cqrs.VersionedEvent{event})
		usersModel.UpdateViewModel([]cqrs.VersionedEvent{event})
		return nil
	})

	eventDispatcher.RegisterEventHandler(AccountCreditedEvent{}, func(event cqrs.VersionedEvent) error {
		readModel.UpdateViewModel([]cqrs.VersionedEvent{event})
		return nil
	})

	eventDispatcher.RegisterEventHandler(AccountDebitedEvent{}, func(event cqrs.VersionedEvent) error {
		readModel.UpdateViewModel([]cqrs.VersionedEvent{event})
		return nil
	})

	eventDispatcher.RegisterEventHandler(EmailAddressChangedEvent{}, func(event cqrs.VersionedEvent) error {
		readModel.UpdateViewModel([]cqrs.VersionedEvent{event})
		usersModel.UpdateViewModel([]cqrs.VersionedEvent{event})
		return nil
	})

	eventDispatcher.RegisterEventHandler(PasswordChangedEvent{}, func(event cqrs.VersionedEvent) error {
		usersModel.UpdateViewModel([]cqrs.VersionedEvent{event})
		return nil
	})

	stopChannel := make(chan bool)
	go eventDispatcher.Listen(stopChannel)

	testCorrelationID := uuid.New()
	readModel.LoadAccounts(persistance)

	usersModel.LoadUsers(persistance)

	log.Println("Loaded accounts")
	log.Println(readModel)

	log.Println("Loaded Users")
	log.Println(usersModel)

	log.Println("Create or find an account")
	readModelAccount := readModel.Accounts[accountID]

	log.Println(readModelAccount)

	log.Println("Create or find a user")
	user := usersModel.Users[accountID]

	log.Println(user)

	var account *Account

	if readModelAccount == nil {
		log.Println("Get hash for user...")

		hashedPassword, err := GetHashForPassword("$ThisIsMyPassword1")

		if err != nil {
			t.Fatal("Error: ", err)
		}

		log.Println("Get hash for user...")

		log.Println("Create new account...")
		account = NewAccount("John", "Snow", "*****@*****.**", hashedPassword, 0.0)

		log.Println("Set ID...")
		account.SetID(accountID)

		log.Println(account)
	} else {
		account, _ = NewAccountFromHistory(accountID, repository)
	}

	log.Println(account)
	log.Println(readModel)
	log.Println(usersModel)

	account.ChangePassword("$ThisIsANOTHERPassword")

	if !account.CheckPassword("$ThisIsANOTHERPassword") {
		t.Fatal("Password is incorrect for account")
	}

	log.Println("Change email address and credit the account")
	account.ChangeEmailAddress("*****@*****.**")
	account.Credit(50)
	account.Credit(50)
	log.Println(account)
	log.Println(readModel)

	log.Println("Persist the account")
	repository.Save(account, "")
	log.Println(readModel)
	log.Println(usersModel)

	log.Println("Load the account from history")
	account, error := NewAccountFromHistory(accountID, repository)
	if error != nil {
		t.Fatal(error)
	}

	log.Println(account)
	log.Println(readModel)

	log.Println("Change the email address, credit 150, debit 200")
	lastEmailAddress := "*****@*****.**"
	account.ChangeEmailAddress(lastEmailAddress)
	account.Credit(150)
	account.Debit(200)
	log.Println(account)
	log.Println(readModel)

	log.Println("Persist the account")
	repository.Save(account, testCorrelationID)
	log.Println(readModel)
	log.Println(usersModel)

	log.Println("Load the account from history")
	account, error = NewAccountFromHistory(accountID, repository)
	if error != nil {
		t.Fatal(error)
	}

	time.Sleep(100 * time.Millisecond)
	// All events should have been replayed and the email address should be the latest
	log.Println(account)
	log.Println(readModel)
	// log.Println(usersModel)
	if account.EmailAddress != lastEmailAddress {
		t.Fatal("Expected emailaddress to be ", lastEmailAddress)
	}

	log.Println("Stop channel")
	stopChannel <- true

	log.Println("GetIntegrationEventsByCorrelationID")
	correlationEvents, err := persistance.GetIntegrationEventsByCorrelationID(testCorrelationID)
	if err != nil {
		t.Fatal(err)
	}

	if len(correlationEvents) == 0 {
		t.Fatal("Expected correlation events")
	}

	for _, correlationEvent := range correlationEvents {
		log.Println(glr.Green(fmt.Sprintf("%v", correlationEvent.Event)))
	}
}