Пример #1
0
func Test_NetworkMachineToJson(t *testing.T) {
	m := nm.NewMachine("test", "default")

	jsonBin, _ := json.MarshalIndent(m, "", " ")
	jsonStr := string(jsonBin)
	expected := strings.Join([]string{
		"{",
		" \"name\": \"test\",",
		" \"machine\": \"default\",",
		" \"content\": {",
		"  \"machines\": {}",
		" },",
		" \"properties\": {}",
		"}",
	}, "\n")
	if jsonStr != expected {
		t.Errorf("Unexpected JSON serialisation")
	}
}
Пример #2
0
func (f *Factory) createMachine(def MachineDefinition, name string) (hps.IMachine, error) {
	var m hps.IMachine
	switch def.Type {
	case "state-machine":
		stm := sm.NewMachine(name, def.Name)

		for pname, pdef := range def.Properties {
			p := stm.AddProperty(pname, pdef.Type)

			if pdef.Comment != "" {
				p.SetComment(pdef.Comment)
			}
		}

		var definition struct {
			States      []string                   `json:"states"`
			Initial     string                     `json:"initial"`
			Properties  map[string]json.RawMessage `json:"properties"`
			Transitions map[string]map[string][]json.RawMessage
		}

		if err := json.Unmarshal(def.Structure, &definition); err != nil {
			return nil, err
		}

		for _, state := range definition.States {
			stm.AddState(state)
		}

		stm.SetState(definition.Initial)

		for from, toTr := range definition.Transitions {
			for to, trs := range toTr {
				for _, tr := range trs {
					trigger, err := f.loadTriggerFromJSON(tr)
					if err != nil {
						return nil, fmt.Errorf("Cannot read transition from '%v' to '%v'. %v", from, to, err)
					}

					s, _ := stm.GetState(from)
					s.AddTransition(to, trigger)
				}
			}
		}

		m = stm
	case "network-machine":
		var definition struct {
			Network string `json:"network"`
		}

		if err := json.Unmarshal(def.Structure, &definition); err != nil {
			return nil, err
		}

		nwt, err := f.CreateNetwork(definition.Network)
		if err != nil {
			return nil, err
		}

		ntm := nm.NewMachine(name, def.Name)
		for pname, pdef := range def.Properties {
			ntm.AddProperty(pname, pdef.Type)
		}

		for _, m := range nwt {
			ntm.AddMachine(m)
		}
		m = ntm
	}

	if constructor, ok := f.constructors[def.Name]; ok {
		m = constructor(m)
	}
	return m, nil
}