Esempio n. 1
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)))
	}
}
Esempio n. 2
0
func TestScenario(t *testing.T) {
	log.SetFlags(log.LstdFlags | log.Lshortfile)
	// Type Registry
	typeRegistry := cqrs.NewTypeRegistry()

	// Event sourcing
	persistance := cqrs.NewInMemoryEventStreamRepository()
	bus := cqrs.NewInMemoryEventBus()
	repository := cqrs.NewRepositoryWithPublisher(persistance, bus, typeRegistry)
	typeRegistry.RegisterAggregate(&Account{}, AccountCreatedEvent{}, EmailAddressChangedEvent{}, AccountCreditedEvent{}, AccountDebitedEvent{}, PasswordChangedEvent{})

	// Read Models
	readModel := NewReadModelAccounts()
	usersModel := NewUsersModel()

	// Command Handlers
	commandBus := cqrs.NewInMemoryCommandBus()
	commandDispatcher := cqrs.NewCommandDispatchManager(commandBus, typeRegistry)
	RegisterCommandHandlers(commandDispatcher, repository)

	// Integration events
	eventDispatcher := cqrs.NewVersionedEventDispatchManager(bus, typeRegistry)
	integrationEventsLog := cqrs.NewInMemoryEventStreamRepository()
	RegisterIntegrationEventHandlers(eventDispatcher, integrationEventsLog, readModel, usersModel)

	commandDispatcherStopChannel := make(chan bool)
	eventDispatcherStopChannel := make(chan bool)
	go commandDispatcher.Listen(commandDispatcherStopChannel, false)
	go eventDispatcher.Listen(eventDispatcherStopChannel, false)

	log.Println("Dump models")
	log.Println(readModel)
	log.Println(usersModel)

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

	log.Println("Find a user")
	user := usersModel.Users[accountID]
	log.Println(user)

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

	log.Println("Create new account...")
	createAccountCommand := cqrs.CreateCommand(
		CreateAccountCommand{"John", "Snow", "*****@*****.**", hashedPassword, 0.0})
	commandBus.PublishCommands([]cqrs.Command{createAccountCommand})

	log.Println("Dump models")
	log.Println(readModel)
	log.Println(usersModel)

	log.Println("Change Password")
	changePasswordCommand := cqrs.CreateCommand(
		ChangePasswordCommand{accountID, "$ThisIsANOTHERPassword"})
	commandBus.PublishCommands([]cqrs.Command{changePasswordCommand})

	log.Println("Change email address and credit the account")
	changeEmailAddressCommand := cqrs.CreateCommand(
		ChangeEmailAddressCommand{accountID, "*****@*****.**"})
	creditAccountCommand := cqrs.CreateCommand(
		CreditAccountCommand{accountID, 50})
	creditAccountCommand2 := cqrs.CreateCommand(
		CreditAccountCommand{accountID, 50})
	commandBus.PublishCommands([]cqrs.Command{
		changeEmailAddressCommand,
		creditAccountCommand,
		creditAccountCommand2})

	log.Println("Dump models")
	log.Println(readModel)
	log.Println(usersModel)

	log.Println("Change the email address, credit 150, debit 200")
	lastEmailAddress := "*****@*****.**"
	changeEmailAddressCommand = cqrs.CreateCommand(
		ChangeEmailAddressCommand{accountID, lastEmailAddress})
	creditAccountCommand = cqrs.CreateCommand(
		CreditAccountCommand{accountID, 150})
	debitAccountCommand := cqrs.CreateCommand(
		DebitAccountCommand{accountID, 200})
	commandBus.PublishCommands([]cqrs.Command{
		changeEmailAddressCommand,
		creditAccountCommand,
		debitAccountCommand})

	log.Println("Dump models")
	log.Println(readModel)
	log.Println(usersModel)

	time.Sleep(300 * time.Millisecond)
	log.Println("Dump history - integration events")
	if history, err := repository.GetEventStreamRepository().AllIntegrationEventsEverPublished(); err != nil {
		t.Fatal(err)
	} else {
		for _, event := range history {
			log.Println(event)
		}
	}

	log.Println("GetIntegrationEventsByCorrelationID")
	correlationEvents, err := repository.GetEventStreamRepository().GetIntegrationEventsByCorrelationID(debitAccountCommand.CorrelationID)
	if err != nil || len(correlationEvents) == 0 {
		t.Fatal(err)
	}

	for correlationEvent := range correlationEvents {
		log.Println(correlationEvent)
	}

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

	// All events should have been replayed and the email address should be the latest
	log.Println("Dump models")
	log.Println(account)
	log.Println(readModel)
	log.Println(usersModel)

	if account.EmailAddress != lastEmailAddress {
		t.Fatal("Expected emailaddress to be ", lastEmailAddress)
	}

	if account.Balance != readModel.Accounts[accountID].Balance {
		t.Fatal("Expected readmodel to be synced with write model")
	}

	eventDispatcherStopChannel <- true
	commandDispatcherStopChannel <- true
}